2 * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
3 * Copyright (C) 2013 - Harris Bakiras <harris.bakiras@lip6.fr>,
4 * Peter Senna Tschudin <peter.senna@lip6.fr>
6 * This file must be used under the terms of the CeCILL.
7 * This source file is licensed as described in the file COPYING, which
8 * you should have received as part of this distribution. The terms
9 * are also available at
10 * http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt
14 #ifndef AST_JITVISITOR_HXX
15 #define AST_JITVISITOR_HXX
24 #include "visitor_common.hxx"
25 #include "shortcutvisitor.hxx"
26 #include "printvisitor.hxx"
27 #include "mutevisitor.hxx"
29 // Needed by visitprivate(const OpExp &)
30 // Needed by visitprivate(const LogicalOpExp &)
31 #include "generic_operations.hxx"
32 #include "types_or_and.hxx"
33 #include "configvariable.hxx"
34 #include "overload.hxx"
35 #include "scilabexception.hxx"
37 //#include "matrix_transpose_int.hxx"
40 #include "doublecomplex.h"
41 #include "matrix_transpose.h"
42 #include "os_swprintf.h"
45 //#include "HandleManagement.h"
49 #include "localization.h"
51 #include "scilabWrite.hxx"
52 #include "context.hxx"
56 #include "alltypes.hxx"
62 #include "llvm/IR/Constants.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/IRBuilder.h"
65 #include "llvm/IR/LLVMContext.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/Type.h"
69 #include "llvm/Analysis/Verifier.h"
70 #include "llvm/Support/TargetSelect.h"
71 #include "llvm/ExecutionEngine/ExecutionEngine.h"
72 #include "llvm/ExecutionEngine/JIT.h"
73 #include "llvm/PassManager.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "vmkit_core.h"
80 #include <sys/types.h>
82 #include "llvm/IR/Attributes.h"
83 #include "llvm/IR/Function.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/CodeGen/GCStrategy.h"
86 #include "llvm/CodeGen/JITCodeEmitter.h"
87 #include "llvm/CodeGen/MachineFunction.h"
88 #include "llvm/ExecutionEngine/ExecutionEngine.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/ManagedStatic.h"
91 //#include "llvm/Support/Debug.h"
92 //#include "llvm/Support/raw_ostream.h"
93 #include <llvm/LinkAllPasses.h>
97 #include "../src/cpp/llvm-wrapper-generated.cpp"
102 typedef double (*jitptr_t) ();
104 class JITVisitor : public ConstVisitor
110 llvm::Value* _result;
111 bool m_bSingleResult;
112 llvm::LLVMContext *context;
113 llvm::Module *TheModule;
114 llvm::IRBuilder<> *Builder;
115 llvm::ExecutionEngine* ee;
116 llvm::FunctionPassManager* pm;
117 llvm::Type* uintptrType;
118 symbol::Context * scilabContext;
121 void visit (const SeqExp &e)
126 void visit (const IntExp &e)
131 void visit (const FloatExp &e)
136 void visit (const DoubleExp &e)
141 void visit (const OpExp &e)
146 void visit (const SimpleVar &e)
153 JITVisitor() : ConstVisitor()
155 llvm::InitializeNativeTarget();
156 context = &llvm::getGlobalContext();
157 Builder = new llvm::IRBuilder<> (*context);
159 m_bSingleResult = false;
160 TheModule = new llvm::Module("scilab jit", *context);
163 llvm::EngineBuilder engine (TheModule);
164 llvm::TargetOptions options;
165 options.NoFramePointerElim = true;
166 engine.setTargetOptions(options);
167 engine.setEngineKind(llvm::EngineKind::JIT);
168 engine.setErrorStr(&err);
170 ee = engine.create();
173 fprintf(stderr, "Could not create ExecutionEngine: %s\n", err.c_str());
176 ee->DisableLazyCompilation(0);
177 ee->addModule(TheModule);
178 TheModule->setDataLayout(ee->getDataLayout()->getStringRepresentation());
179 pm = NULL; /* TODO : init */
181 uintptrType = TheModule->getPointerSize() == llvm::Module::Pointer32 ?
182 llvm::Type::getInt32Ty(*context) : llvm::Type::getInt64Ty(*context);
184 TheModule = llvm::makeLLVMModuleContents(TheModule);
187 for (llvm::Module::iterator cur = TheModule->begin(), end = TheModule->end(); cur != end; cur++)
189 void* ptr = dlsym(RTLD_DEFAULT, cur->getName().data());
190 //printf("%s ---> %p\n", cur->getName().data(), ptr);
193 ee->updateGlobalMapping(cur, ptr);
197 scilabContext = symbol::Context::getInstance();
200 void result_set(llvm::Value* const gtVal)
202 m_bSingleResult = true;
206 llvm::Value* result_get()
211 void visitprivate(const DoubleExp &e)
213 if (e.getBigDouble() == NULL)
215 Double *pdbl = new Double(e.value_get());
216 (const_cast<DoubleExp *>(&e))->setBigDouble(pdbl);
219 // llvm::Value* res = llvm::ConstantFP::get(llvm::getGlobalContext(), llvm::APFloat(e.getBigDouble()));
220 llvm::Value* res = llvm::ConstantInt::get(uintptrType, (uintptr_t)e.getBigDouble());
221 res = Builder->CreateIntToPtr(res, llvm::PointerType::getUnqual(TheModule->getTypeByName("class.types::Double")));
227 void visitprivate(const FloatExp &e)
231 void visitprivate(const IntExp &e)
235 void visitprivate(const SeqExp &e)
239 std::list<Exp *>::const_iterator itExp;
241 for (itExp = e.exps_get().begin (); itExp != e.exps_get().end (); ++itExp)
243 //reset default values
245 llvm::FunctionType *FT = llvm::FunctionType::get(llvm::Type::getDoubleTy(*context), false);
246 llvm::Function *TheFunction = llvm::Function::Create(FT, llvm::Function::ExternalLinkage, "TheFunction", TheModule);
247 llvm::BasicBlock *BB = llvm::BasicBlock::Create(llvm::getGlobalContext(), "entry", TheFunction);
248 Builder->SetInsertPoint(BB);
250 (*itExp)->accept(*this);
252 if (1 || result_get() != NULL)
254 Builder->CreateRet(result_get());
256 void* res = ee->getPointerToFunction(TheFunction);
257 jitptr_t myJit = (jitptr_t) res;
258 double result = myJit();
259 std::cout << "coucou result : " << result << std::endl;
264 llvm::Value* const llvm_value_one = llvm::ConstantFP::get(llvm::getGlobalContext(), llvm::APFloat(1.0));
265 llvm::Value* llvm_rec_power (llvm::Value* x, llvm::Value* n)
267 llvm::ConstantFP* ncfp = llvm::dyn_cast<llvm::ConstantFP>(n);
272 return llvm_value_one;
274 if (ncfp->isNegative())
276 llvm::Value* moduloN = Builder->CreateFMul(llvm::ConstantFP::get(llvm::getGlobalContext(), llvm::APFloat(-1.0)), n);
277 // return 1 / (x * llvm_rec_power(x, (-1 * n)-1))
278 return Builder->CreateFDiv(llvm_value_one, Builder->CreateFMul(x, llvm_rec_power(x, Builder->CreateFSub(moduloN, llvm_value_one, "OpExp::minus")), "OpExp::times"), "OpExp::rdivide");
282 // return x * llvm_rec_power(x, n-1)
283 return Builder->CreateFMul(x, llvm_rec_power(x, Builder->CreateFSub(n, llvm_value_one, "OpExp::minus")), "OpExp::times");
286 void visitprivate(const OpExp &e)
289 switch (e.kind_get())
291 case OpExp::invalid_kind :
293 std::cout << "OpExp::invalid_kind" << std::endl;
296 case OpExp::bool_kind :
298 std::cout << "OpExp::bool_kind" << std::endl;
301 case OpExp::string_kind :
303 std::cout << "OpExp::string_kind" << std::endl;
306 case OpExp::integer_kind :
308 std::cout << "OpExp::integer_kind" << std::endl;
311 case OpExp::float_kind :
313 std::cout << "OpExp::float_kind" << std::endl;
316 case OpExp::double_kind :
318 std::cout << "OpExp::double_kind" << std::endl;
321 case OpExp::float_complex_kind :
325 case OpExp::double_complex_kind :
329 case OpExp::bool_matrix_kind :
333 case OpExp::string_matrix_kind :
337 case OpExp::integer_matrix_kind :
341 case OpExp::float_matrix_kind :
345 case OpExp::double_matrix_kind :
349 case OpExp::float_complex_matrix_kind :
353 case OpExp::double_complex_matrix_kind :
357 case OpExp::matrix_kind :
364 /*getting what to assign*/
365 e.left_get().accept(*this);
366 llvm::Value *pITL = result_get();
368 /*getting what to assign*/
369 e.right_get().accept(*this);
370 llvm::Value *pITR = result_get();
372 llvm::Value *pResult = NULL;
373 switch (e.oper_get())
377 //%5 = call i32 @_Z17AddDoubleToDoublePN5types6DoubleES1_PS1_(%"class.types::Double"* %3, %"class.types::Double"* %4, %"class.types::Double"** %pdbl1)
378 // pResult = Builder->CreateFAdd(pITL, pITR, "OpExp::plus");
380 llvm::Value * tmp = Builder->CreateAlloca(llvm::PointerType::getUnqual(TheModule->getTypeByName("class.types::Double")));
382 //printf("%p \n",TheModule->getFunction("_Z17AddDoubleToDoublePN5types6DoubleES1_PS1_"));
384 Builder->CreateCall3(TheModule->getFunction("_Z17AddDoubleToDoublePN5types6DoubleES1_PS1_"), pITR, pITL, tmp);
386 pResult = Builder->CreateLoad(tmp);
391 pResult = Builder->CreateFSub(pITL, pITR, "OpExp::minus");
396 pResult = Builder->CreateFMul(pITL, pITR, "OpExp::times");
399 case OpExp::rdivide :
401 pResult = Builder->CreateFDiv(pITL, pITR, "OpExp::rdivide");
404 case OpExp::ldivide :
406 pResult = Builder->CreateFDiv(pITR, pITL, "OpExp::ldivide");
411 pResult = llvm_rec_power(pITL, pITR);
414 case OpExp::unaryMinus :
416 pResult = Builder->CreateFSub(pITL, pITR, "OpExp::unaryMinus");
421 pResult = Builder->CreateUIToFP(Builder->CreateFCmpUEQ(pITL, pITR, "OpExp::eq"), llvm::Type::getDoubleTy(llvm::getGlobalContext()), "booltodouble");
426 pResult = Builder->CreateUIToFP(Builder->CreateNot(Builder->CreateFCmpUEQ(pITL, pITR, "OpExp::eq"), "not"), llvm::Type::getDoubleTy(llvm::getGlobalContext()), "booltodouble");
431 pResult = Builder->CreateUIToFP(Builder->CreateFCmpULT(pITL, pITR, "OpExp::lt"), llvm::Type::getDoubleTy(llvm::getGlobalContext()), "booltodouble");
436 pResult = Builder->CreateUIToFP(Builder->CreateFCmpULE(pITL, pITR, "OpExp::le"), llvm::Type::getDoubleTy(llvm::getGlobalContext()), "booltodouble");
441 pResult = Builder->CreateUIToFP(Builder->CreateFCmpUGT(pITL, pITR, "OpExp::gt"), llvm::Type::getDoubleTy(llvm::getGlobalContext()), "booltodouble");
446 pResult = Builder->CreateUIToFP(Builder->CreateFCmpUGE(pITL, pITR, "OpExp::ge"), llvm::Type::getDoubleTy(llvm::getGlobalContext()), "booltodouble");
451 std::cout << "Operation not supported, returning 42..." << std::endl;
452 pResult = llvm::ConstantFP::get(llvm::getGlobalContext(), llvm::APFloat(42.0));
459 result_set(llvm::ConstantFP::get(llvm::getGlobalContext(), llvm::APFloat(42.0)));
464 void visitprivate (const AssignExp &e)
466 /*getting what to assign*/
468 const SimpleVar *pVar = dynamic_cast<const SimpleVar*>(&e.left_exp_get());
472 /*getting what to assign*/
473 e.right_exp_get().accept(*this);
475 llvm::Value *pITR = result_get();
479 //mod->getFunction("_ZN6symbol7Context3putERKNS_6SymbolERN5types12InternalTypeE");
480 llvm::Value * llvmScilabContext = llvm::ConstantInt::get(uintptrType, (uintptr_t)scilabContext);
481 llvmScilabContext = Builder->CreateIntToPtr(llvmScilabContext, llvm::PointerType::getUnqual(TheModule->getTypeByName("class.symbol::Context")));
483 llvm::Value * llvmSym = llvm::ConstantInt::get(uintptrType, (uintptr_t)&pVar->name_get());
484 llvmSym = Builder->CreateIntToPtr(llvmSym, llvm::PointerType::getUnqual(TheModule->getTypeByName("class.symbol::Symbol")));
487 Builder->CreateCall3(TheModule->getFunction("_ZN6symbol7Context3putERKNS_6SymbolERN5types12InternalTypeE"), llvmScilabContext, llvmSym, pITR);
489 //symbol::Context::getInstance()->put(pVar->name_get(), *pIT);
493 llvm::Value *pResult = NULL;
496 void visitprivate (const SimpleVar &e)
498 /* InternalType * pI = symbol::Context::getInstance()->get(e.name_get());
502 if (e.is_verbose() && pI->isCallable() == false && ConfigVariable::isPromptShow())
504 std::wostringstream ostr;
505 ostr << e.name_get().name_get() << L" = " << L"(" << pI->getRef() << L")" << std::endl;
507 scilabWriteW(ostr.str().c_str());
508 VariableToString(pI);
517 wchar_t szError[bsiz];
518 os_swprintf(szError, bsiz, _W("Undefined variable: %ls\n"), e.name_get().name_get().c_str());
519 throw ScilabError(szError, 999, e.location_get());
520 //Err, SimpleVar doesn't exist in Scilab scopes.
524 void visit (const BoolExp &e)
529 void visit (const NilExp &e)
534 void visit (const ColonVar &e)
539 void visit (const DollarVar &e)
544 void visit (const ArrayListVar &e)
549 void visit (const FieldExp &e)
555 void visit (const LogicalOpExp &e)
560 void visit (const AssignExp &e)
565 void visit (const CellCallExp &e)
570 void visit (const CallExp &e)
575 void visit (const IfExp &e)
580 void visit (const TryCatchExp &e)
585 void visit (const WhileExp &e)
590 void visit (const ForExp &e)
595 void visit (const BreakExp &e)
600 void visit (const ContinueExp &e)
605 void visit (const ReturnExp &e)
610 void visit (const SelectExp &e)
615 void visit (const CaseExp &e)
620 void visit (const ArrayListExp &e)
625 void visit (const AssignListExp &e)
630 void visit (const NotExp &e)
635 void visit (const TransposeExp &e)
640 void visit (const VarDec &e)
645 void visit (const FunctionDec &e)
650 void visit(const ListExp &e)
654 void visit (const MatrixExp &e)
659 void visit (const MatrixLineExp &e)
664 void visit (const CellExp &e)
669 void visit (const StringExp &e)
674 void visit (const CommentExp &e)
680 #endif // !AST_JITVISITOR_HXX