2 // mini-llvm-cpp.cpp: C++ support classes for the mono LLVM integration
4 // (C) 2009-2011 Novell, Inc.
5 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
9 // We need to override some stuff in LLVM, but this cannot be done using the C
10 // interface, so we have to use some C++ code here.
11 // The things which we override are:
12 // - the default JIT code manager used by LLVM doesn't allocate memory using
13 // MAP_32BIT, we require it.
14 // - add some callbacks so we can obtain the size of methods and their exception
19 // Mono's internal header files are not C++ clean, so avoid including them if
27 #include <llvm/Support/raw_ostream.h>
28 #include <llvm/Support/Host.h>
29 #include <llvm/PassManager.h>
30 #include <llvm/ExecutionEngine/ExecutionEngine.h>
31 #include <llvm/ExecutionEngine/JITMemoryManager.h>
32 #include <llvm/ExecutionEngine/JITEventListener.h>
33 #include <llvm/Target/TargetOptions.h>
34 #include <llvm/Target/TargetRegisterInfo.h>
35 #include <llvm/IR/Verifier.h>
36 #include <llvm/Analysis/Passes.h>
37 #include <llvm/Transforms/Scalar.h>
38 #include <llvm/Support/CommandLine.h>
39 #include <llvm/IR/LegacyPassNameParser.h>
40 #include <llvm/Support/PrettyStackTrace.h>
41 #include <llvm/CodeGen/Passes.h>
42 #include <llvm/CodeGen/MachineFunctionPass.h>
43 #include <llvm/CodeGen/MachineFunction.h>
44 #include <llvm/CodeGen/MachineFrameInfo.h>
45 #include <llvm/IR/Function.h>
46 #include <llvm/IR/IRBuilder.h>
47 #include <llvm/IR/Module.h>
49 #include <llvm-c/Core.h>
50 #include <llvm-c/ExecutionEngine.h>
52 #include "mini-llvm-cpp.h"
54 // extern "C" void LLVMInitializeARMTargetInfo();
55 // extern "C" void LLVMInitializeARMTarget ();
56 // extern "C" void LLVMInitializeARMTargetMC ();
60 #ifndef MONO_CROSS_COMPILE
62 static void (*unhandled_exception)() = default_mono_llvm_unhandled_exception;
65 mono_llvm_set_unhandled_exception_handler (void)
67 std::set_terminate (unhandled_exception);
70 class MonoJITMemoryManager : public JITMemoryManager
76 /* Callbacks installed by mono */
77 AllocCodeMemoryCb *alloc_cb;
79 ExceptionTableCb *exception_cb;
81 MonoJITMemoryManager ();
82 ~MonoJITMemoryManager ();
84 void setMemoryWritable (void);
86 void setMemoryExecutable (void);
90 unsigned char *getGOTBase() const {
91 return mm->getGOTBase ();
94 void setPoisonMemory(bool) {
97 unsigned char *startFunctionBody(const Function *F,
98 uintptr_t &ActualSize);
100 unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
103 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
104 unsigned char *FunctionEnd);
106 unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
108 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment);
110 void deallocateMemForFunction(const Function *F);
112 unsigned char*startExceptionTable(const Function* F,
113 uintptr_t &ActualSize);
115 void endExceptionTable(const Function *F, unsigned char *TableStart,
116 unsigned char *TableEnd,
117 unsigned char* FrameRegister);
119 virtual void deallocateFunctionBody(void*) {
122 virtual void deallocateExceptionTable(void*) {
125 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID,
126 StringRef SectionName) {
132 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID,
133 StringRef SectionName, bool IsReadOnly) {
139 virtual bool applyPermissions(std::string*) {
145 virtual bool finalizeMemory(std::string *ErrMsg = 0) {
151 virtual void* getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure) {
155 err = dlsym_cb (Name.c_str (), &res);
157 outs () << "Unable to resolve: " << Name << ": " << err << "\n";
165 MonoJITMemoryManager::MonoJITMemoryManager ()
167 mm = JITMemoryManager::CreateDefaultMemManager ();
170 MonoJITMemoryManager::~MonoJITMemoryManager ()
176 MonoJITMemoryManager::setMemoryWritable (void)
181 MonoJITMemoryManager::setMemoryExecutable (void)
186 MonoJITMemoryManager::AllocateGOT()
192 MonoJITMemoryManager::startFunctionBody(const Function *F,
193 uintptr_t &ActualSize)
195 // FIXME: This leaks memory
198 return alloc_cb (wrap (F), ActualSize);
202 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
205 return alloc_cb (wrap (F), StubSize);
209 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
210 unsigned char *FunctionEnd)
215 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
217 return new unsigned char [Size];
221 MonoJITMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
223 return new unsigned char [Size];
227 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
232 MonoJITMemoryManager::startExceptionTable(const Function* F,
233 uintptr_t &ActualSize)
235 return startFunctionBody(F, ActualSize);
239 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
240 unsigned char *TableEnd,
241 unsigned char* FrameRegister)
243 exception_cb (FrameRegister);
248 class MonoJITMemoryManager {
251 #endif /* !MONO_CROSS_COMPILE */
253 class MonoJITEventListener : public JITEventListener {
256 FunctionEmittedCb *emitted_cb;
258 MonoJITEventListener (FunctionEmittedCb *cb) {
262 virtual void NotifyFunctionEmitted(const Function &F,
263 void *Code, size_t Size,
264 const EmittedFunctionDetails &Details) {
265 emitted_cb (wrap (&F), Code, (char*)Code + Size);
272 MonoJITMemoryManager *mm;
273 MonoJITEventListener *listener;
274 FunctionPassManager *fpm;
278 mono_llvm_optimize_method (MonoEERef eeref, LLVMValueRef method)
280 MonoEE *mono_ee = (MonoEE*)eeref;
283 * The verifier does some checks on the whole module, leading to quadratic behavior.
285 //verifyFunction (*(unwrap<Function> (method)));
286 mono_ee->fpm->run (*unwrap<Function> (method));
290 mono_llvm_dump_value (LLVMValueRef value)
292 /* Same as LLVMDumpValue (), but print to stdout */
294 outs () << (*unwrap<Value> (value));
297 /* Missing overload for building an alloca with an alignment */
299 mono_llvm_build_alloca (LLVMBuilderRef builder, LLVMTypeRef Ty,
300 LLVMValueRef ArraySize,
301 int alignment, const char *Name)
303 return wrap (unwrap (builder)->Insert (new AllocaInst (unwrap (Ty), unwrap (ArraySize), alignment), Name));
307 mono_llvm_build_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
308 const char *Name, gboolean is_volatile, BarrierKind barrier)
310 LoadInst *ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
313 case LLVM_BARRIER_NONE:
315 case LLVM_BARRIER_ACQ:
316 ins->setOrdering(Acquire);
318 case LLVM_BARRIER_SEQ:
319 ins->setOrdering(SequentiallyConsistent);
322 g_assert_not_reached ();
330 mono_llvm_build_aligned_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
331 const char *Name, gboolean is_volatile, int alignment)
335 ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
336 ins->setAlignment (alignment);
342 mono_llvm_build_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
343 gboolean is_volatile, BarrierKind barrier)
345 StoreInst *ins = unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile);
348 case LLVM_BARRIER_NONE:
350 case LLVM_BARRIER_REL:
351 ins->setOrdering(Release);
353 case LLVM_BARRIER_SEQ:
354 ins->setOrdering(SequentiallyConsistent);
357 g_assert_not_reached ();
365 mono_llvm_build_aligned_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
366 gboolean is_volatile, int alignment)
370 ins = unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile);
371 ins->setAlignment (alignment);
377 mono_llvm_build_cmpxchg (LLVMBuilderRef builder, LLVMValueRef ptr, LLVMValueRef cmp, LLVMValueRef val)
379 AtomicCmpXchgInst *ins;
381 ins = unwrap(builder)->CreateAtomicCmpXchg (unwrap(ptr), unwrap (cmp), unwrap (val), SequentiallyConsistent, SequentiallyConsistent);
386 mono_llvm_build_atomic_rmw (LLVMBuilderRef builder, AtomicRMWOp op, LLVMValueRef ptr, LLVMValueRef val)
388 AtomicRMWInst::BinOp aop = AtomicRMWInst::Xchg;
392 case LLVM_ATOMICRMW_OP_XCHG:
393 aop = AtomicRMWInst::Xchg;
395 case LLVM_ATOMICRMW_OP_ADD:
396 aop = AtomicRMWInst::Add;
399 g_assert_not_reached ();
403 ins = unwrap (builder)->CreateAtomicRMW (aop, unwrap (ptr), unwrap (val), SequentiallyConsistent);
408 mono_llvm_build_fence (LLVMBuilderRef builder, BarrierKind kind)
411 AtomicOrdering ordering;
413 g_assert (kind != LLVM_BARRIER_NONE);
416 case LLVM_BARRIER_ACQ:
419 case LLVM_BARRIER_REL:
422 case LLVM_BARRIER_SEQ:
423 ordering = SequentiallyConsistent;
426 g_assert_not_reached ();
430 ins = unwrap (builder)->CreateFence (ordering);
435 mono_llvm_set_must_tail (LLVMValueRef call_ins)
437 CallInst *ins = (CallInst*)unwrap (call_ins);
439 ins->setTailCallKind (CallInst::TailCallKind::TCK_MustTail);
443 mono_llvm_replace_uses_of (LLVMValueRef var, LLVMValueRef v)
445 Value *V = ConstantExpr::getTruncOrBitCast (unwrap<Constant> (v), unwrap (var)->getType ());
446 unwrap (var)->replaceAllUsesWith (V);
450 mono_llvm_create_constant_data_array (const uint8_t *data, int len)
452 return wrap(ConstantDataArray::get (*unwrap(LLVMGetGlobalContext ()), makeArrayRef(data, len)));
456 mono_llvm_set_is_constant (LLVMValueRef global_var)
458 unwrap<GlobalVariable>(global_var)->setConstant (true);
462 mono_llvm_set_preserveall_cc (LLVMValueRef func)
464 unwrap<Function>(func)->setCallingConv (CallingConv::PreserveAll);
468 mono_llvm_set_call_preserveall_cc (LLVMValueRef func)
470 unwrap<CallInst>(func)->setCallingConv (CallingConv::PreserveAll);
473 static cl::list<const PassInfo*, bool, PassNameParser>
474 PassList(cl::desc("Optimizations available:"));
477 force_pass_linking (void)
479 // Make sure the rest is linked in, but never executed
480 if (g_getenv ("FOO") != (char*)-1)
483 // This is a subset of the passes in LinkAllPasses.h
484 // The utility passes and the interprocedural passes are commented out
486 (void) llvm::createAAEvalPass();
487 (void) llvm::createAggressiveDCEPass();
488 (void) llvm::createAliasAnalysisCounterPass();
489 (void) llvm::createAliasDebugger();
491 (void) llvm::createArgumentPromotionPass();
492 (void) llvm::createStructRetPromotionPass();
494 (void) llvm::createBasicAliasAnalysisPass();
495 (void) llvm::createLibCallAliasAnalysisPass(0);
496 (void) llvm::createScalarEvolutionAliasAnalysisPass();
497 //(void) llvm::createBlockPlacementPass();
498 (void) llvm::createBreakCriticalEdgesPass();
499 (void) llvm::createCFGSimplificationPass();
501 (void) llvm::createConstantMergePass();
502 (void) llvm::createConstantPropagationPass();
505 (void) llvm::createDeadArgEliminationPass();
507 (void) llvm::createDeadCodeEliminationPass();
508 (void) llvm::createDeadInstEliminationPass();
509 (void) llvm::createDeadStoreEliminationPass();
511 (void) llvm::createDeadTypeEliminationPass();
512 (void) llvm::createDomOnlyPrinterPass();
513 (void) llvm::createDomPrinterPass();
514 (void) llvm::createDomOnlyViewerPass();
515 (void) llvm::createDomViewerPass();
516 (void) llvm::createEdgeProfilerPass();
517 (void) llvm::createOptimalEdgeProfilerPass();
518 (void) llvm::createFunctionInliningPass();
519 (void) llvm::createAlwaysInlinerPass();
520 (void) llvm::createGlobalDCEPass();
521 (void) llvm::createGlobalOptimizerPass();
522 (void) llvm::createGlobalsModRefPass();
523 (void) llvm::createIPConstantPropagationPass();
524 (void) llvm::createIPSCCPPass();
526 (void) llvm::createIndVarSimplifyPass();
527 (void) llvm::createInstructionCombiningPass();
529 (void) llvm::createInternalizePass(false);
531 (void) llvm::createLCSSAPass();
532 (void) llvm::createLICMPass();
533 (void) llvm::createLazyValueInfoPass();
534 //(void) llvm::createLoopDependenceAnalysisPass();
536 (void) llvm::createLoopExtractorPass();
538 (void) llvm::createLoopSimplifyPass();
539 (void) llvm::createLoopStrengthReducePass();
540 (void) llvm::createLoopUnrollPass();
541 (void) llvm::createLoopUnswitchPass();
542 (void) llvm::createLoopRotatePass();
543 (void) llvm::createLowerInvokePass();
545 (void) llvm::createLowerSetJmpPass();
547 (void) llvm::createLowerSwitchPass();
548 (void) llvm::createNoAAPass();
550 (void) llvm::createNoProfileInfoPass();
551 (void) llvm::createProfileEstimatorPass();
552 (void) llvm::createProfileVerifierPass();
553 (void) llvm::createProfileLoaderPass();
555 (void) llvm::createPromoteMemoryToRegisterPass();
556 (void) llvm::createDemoteRegisterToMemoryPass();
558 (void) llvm::createPruneEHPass();
559 (void) llvm::createPostDomOnlyPrinterPass();
560 (void) llvm::createPostDomPrinterPass();
561 (void) llvm::createPostDomOnlyViewerPass();
562 (void) llvm::createPostDomViewerPass();
564 (void) llvm::createReassociatePass();
565 (void) llvm::createSCCPPass();
566 (void) llvm::createScalarReplAggregatesPass();
567 //(void) llvm::createSimplifyLibCallsPass();
569 (void) llvm::createSingleLoopExtractorPass();
570 (void) llvm::createStripSymbolsPass();
571 (void) llvm::createStripNonDebugSymbolsPass();
572 (void) llvm::createStripDeadDebugInfoPass();
573 (void) llvm::createStripDeadPrototypesPass();
574 (void) llvm::createTailCallEliminationPass();
575 (void) llvm::createTailDuplicationPass();
576 (void) llvm::createJumpThreadingPass();
579 (void) llvm::createUnifyFunctionExitNodesPass();
581 (void) llvm::createInstCountPass();
582 (void) llvm::createCodeGenPreparePass();
583 (void) llvm::createGVNPass();
584 (void) llvm::createMemCpyOptPass();
585 (void) llvm::createLoopDeletionPass();
587 (void) llvm::createPostDomTree();
588 (void) llvm::createPostDomFrontier();
589 (void) llvm::createInstructionNamerPass();
590 (void) llvm::createPartialSpecializationPass();
591 (void) llvm::createFunctionAttrsPass();
592 (void) llvm::createMergeFunctionsPass();
593 (void) llvm::createPrintModulePass(0);
594 (void) llvm::createPrintFunctionPass("", 0);
595 (void) llvm::createDbgInfoPrinterPass();
596 (void) llvm::createModuleDebugInfoPrinterPass();
597 (void) llvm::createPartialInliningPass();
598 (void) llvm::createGEPSplitterPass();
599 (void) llvm::createLintPass();
601 (void) llvm::createSinkingPass();
604 #ifndef MONO_CROSS_COMPILE
606 static gboolean inited;
614 force_pass_linking ();
617 LLVMInitializeARMTarget ();
618 LLVMInitializeARMTargetInfo ();
619 LLVMInitializeARMTargetMC ();
620 #elif defined(TARGET_X86) || defined(TARGET_AMD64)
621 LLVMInitializeX86Target ();
622 LLVMInitializeX86TargetInfo ();
623 LLVMInitializeX86TargetMC ();
624 #elif defined(TARGET_POWERPC)
625 LLVMInitializePowerPCTarget ();
626 LLVMInitializePowerPCTargetInfo ();
627 LLVMInitializePowerPCTargetMC ();
629 #error Unsupported mono-llvm target
632 PassRegistry &Registry = *PassRegistry::getPassRegistry();
633 initializeCore(Registry);
634 initializeScalarOpts(Registry);
635 initializeAnalysis(Registry);
636 initializeIPA(Registry);
637 initializeTransformUtils(Registry);
638 initializeInstCombine(Registry);
639 initializeTarget(Registry);
641 llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "");
647 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb, DlSymCb *dlsym_cb, LLVMExecutionEngineRef *ee)
654 mono_ee = new MonoEE ();
656 MonoJITMemoryManager *mono_mm = new MonoJITMemoryManager ();
657 mono_mm->alloc_cb = alloc_cb;
658 mono_mm->dlsym_cb = dlsym_cb;
659 mono_mm->exception_cb = exception_cb;
660 mono_ee->mm = mono_mm;
663 * The Default code model doesn't seem to work on amd64,
664 * test_0_fields_with_big_offsets (among others) crashes, because LLVM tries to call
665 * memset using a normal pcrel code which is in 32bit memory, while memset isn't.
669 opts.JITExceptionHandling = 1;
671 StringRef cpu_name = sys::getHostCPUName ();
673 // EngineBuilder no longer has a copy assignment operator (?)
674 std::unique_ptr<Module> Owner(unwrap(MP));
675 EngineBuilder b (std::move(Owner));
676 ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setAllocateGVsWithCode (true).setMCPU (cpu_name).create ();
681 MonoJITEventListener *listener = new MonoJITEventListener (emitted_cb);
682 EE->RegisterJITEventListener (listener);
683 mono_ee->listener = listener;
685 FunctionPassManager *fpm = new FunctionPassManager (unwrap (MP));
688 fpm->add(new DataLayoutPass(*EE->getDataLayout()));
690 if (PassList.size() > 0) {
691 /* Use the passes specified by the env variable */
692 /* Only the passes in force_pass_linking () can be used */
693 for (unsigned i = 0; i < PassList.size(); ++i) {
694 const PassInfo *PassInf = PassList[i];
697 if (PassInf->getNormalCtor())
698 P = PassInf->getNormalCtor()();
702 /* Use the same passes used by 'opt' by default, without the ipo passes */
703 const char *opts = "-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -gvn -simplifycfg";
707 args = g_strsplit (opts, " ", 1000);
708 for (i = 0; args [i]; i++)
710 llvm::cl::ParseCommandLineOptions (i, args, "");
713 for (unsigned i = 0; i < PassList.size(); ++i) {
714 const PassInfo *PassInf = PassList[i];
717 if (PassInf->getNormalCtor())
718 P = PassInf->getNormalCtor()();
719 g_assert (P->getPassKind () == llvm::PT_Function || P->getPassKind () == llvm::PT_Loop);
724 fpm->add(createInstructionCombiningPass());
725 fpm->add(createReassociatePass());
726 fpm->add(createGVNPass());
727 fpm->add(createCFGSimplificationPass());
737 mono_llvm_dispose_ee (MonoEERef *eeref)
739 MonoEE *mono_ee = (MonoEE*)eeref;
743 //delete mono_ee->mm;
744 delete mono_ee->listener;
751 mono_llvm_set_unhandled_exception_handler (void)
756 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb, DlSymCb *dlsym_cb, LLVMExecutionEngineRef *ee)
758 g_assert_not_reached ();
763 mono_llvm_dispose_ee (MonoEERef *eeref)
765 g_assert_not_reached ();
770 LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
773 g_assert_not_reached ();
777 LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global)
779 g_assert_not_reached ();
783 #endif /* !MONO_CROSS_COMPILE */