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
24 //undef those as llvm defines them on its own config.h as well.
25 #undef PACKAGE_BUGREPORT
28 #undef PACKAGE_TARNAME
29 #undef PACKAGE_VERSION
33 #include <llvm/Support/raw_ostream.h>
34 #include <llvm/PassManager.h>
35 #include <llvm/ExecutionEngine/ExecutionEngine.h>
36 #include <llvm/ExecutionEngine/JITMemoryManager.h>
37 #include <llvm/ExecutionEngine/JITEventListener.h>
38 #include <llvm/Target/TargetOptions.h>
39 #include <llvm/Target/TargetRegisterInfo.h>
40 #include <llvm/Analysis/Verifier.h>
41 #include <llvm/Analysis/Passes.h>
42 #include <llvm/Transforms/Scalar.h>
43 #include <llvm/Support/CommandLine.h>
44 #include "llvm/Support/PassNameParser.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include <llvm/CodeGen/Passes.h>
47 #include <llvm/CodeGen/MachineFunctionPass.h>
48 #include <llvm/CodeGen/MachineFunction.h>
49 #include <llvm/CodeGen/MachineFrameInfo.h>
50 #include <llvm/IR/Function.h>
51 #include <llvm/IR/IRBuilder.h>
52 #include <llvm/IR/Module.h>
53 //#include <llvm/LinkAllPasses.h>
55 #include "llvm-c/Core.h"
56 #include "llvm-c/ExecutionEngine.h"
58 #include "mini-llvm-cpp.h"
60 #define LLVM_CHECK_VERSION(major,minor) \
61 ((LLVM_MAJOR_VERSION > (major)) || \
62 ((LLVM_MAJOR_VERSION == (major)) && (LLVM_MINOR_VERSION >= (minor))))
64 // extern "C" void LLVMInitializeARMTargetInfo();
65 // extern "C" void LLVMInitializeARMTarget ();
66 // extern "C" void LLVMInitializeARMTargetMC ();
70 #ifndef MONO_CROSS_COMPILE
72 class MonoJITMemoryManager : public JITMemoryManager
78 /* Callbacks installed by mono */
79 AllocCodeMemoryCb *alloc_cb;
82 MonoJITMemoryManager ();
83 ~MonoJITMemoryManager ();
85 void setMemoryWritable (void);
87 void setMemoryExecutable (void);
91 unsigned char *getGOTBase() const {
92 return mm->getGOTBase ();
95 void setPoisonMemory(bool) {
98 unsigned char *startFunctionBody(const Function *F,
99 uintptr_t &ActualSize);
101 unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
104 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
105 unsigned char *FunctionEnd);
107 unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
109 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment);
111 void deallocateMemForFunction(const Function *F);
113 unsigned char*startExceptionTable(const Function* F,
114 uintptr_t &ActualSize);
116 void endExceptionTable(const Function *F, unsigned char *TableStart,
117 unsigned char *TableEnd,
118 unsigned char* FrameRegister);
120 virtual void deallocateFunctionBody(void*) {
123 virtual void deallocateExceptionTable(void*) {
126 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID,
127 StringRef SectionName) {
133 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID,
134 StringRef SectionName, bool IsReadOnly) {
140 virtual bool applyPermissions(std::string*) {
146 virtual bool finalizeMemory(std::string *ErrMsg = 0) {
152 virtual void* getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure) {
156 err = dlsym_cb (Name.c_str (), &res);
158 outs () << "Unable to resolve: " << Name << ": " << err << "\n";
166 MonoJITMemoryManager::MonoJITMemoryManager ()
168 mm = JITMemoryManager::CreateDefaultMemManager ();
171 MonoJITMemoryManager::~MonoJITMemoryManager ()
177 MonoJITMemoryManager::setMemoryWritable (void)
182 MonoJITMemoryManager::setMemoryExecutable (void)
187 MonoJITMemoryManager::AllocateGOT()
193 MonoJITMemoryManager::startFunctionBody(const Function *F,
194 uintptr_t &ActualSize)
196 // FIXME: This leaks memory
199 return alloc_cb (wrap (F), ActualSize);
203 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
206 return alloc_cb (wrap (F), StubSize);
210 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
211 unsigned char *FunctionEnd)
216 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
218 return new unsigned char [Size];
222 MonoJITMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
224 return new unsigned char [Size];
228 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
233 MonoJITMemoryManager::startExceptionTable(const Function* F,
234 uintptr_t &ActualSize)
236 return startFunctionBody(F, ActualSize);
240 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
241 unsigned char *TableEnd,
242 unsigned char* FrameRegister)
246 #endif /* !MONO_CROSS_COMPILE */
248 class MonoJITEventListener : public JITEventListener {
251 FunctionEmittedCb *emitted_cb;
253 MonoJITEventListener (FunctionEmittedCb *cb) {
257 virtual void NotifyFunctionEmitted(const Function &F,
258 void *Code, size_t Size,
259 const EmittedFunctionDetails &Details) {
261 * X86TargetMachine::setCodeModelForJIT() sets the code model to Large on amd64,
262 * which means the JIT will generate calls of the form
265 * Our trampoline code can't patch this. Passing CodeModel::Small to createJIT
266 * doesn't seem to work, we need Default. A discussion is here:
267 * http://lists.cs.uiuc.edu/pipermail/llvmdev/2009-December/027999.html
268 * There seems to no way to get the TargeMachine used by an EE either, so we
269 * install a profiler hook and reset the code model here.
270 * This should be inside an ifdef, but we can't include our config.h either,
271 * since its definitions conflict with LLVM's config.h.
272 * The LLVM mono branch contains a workaround.
274 emitted_cb (wrap (&F), Code, (char*)Code + Size);
278 #ifndef MONO_CROSS_COMPILE
279 static MonoJITMemoryManager *mono_mm;
281 static MonoJITEventListener *mono_event_listener;
283 static FunctionPassManager *fpm;
286 mono_llvm_optimize_method (LLVMValueRef method)
289 * The verifier does some checks on the whole module, leading to quadratic behavior.
291 //verifyFunction (*(unwrap<Function> (method)));
292 fpm->run (*unwrap<Function> (method));
296 mono_llvm_dump_value (LLVMValueRef value)
298 /* Same as LLVMDumpValue (), but print to stdout */
300 outs () << (*unwrap<Value> (value));
303 /* Missing overload for building an alloca with an alignment */
305 mono_llvm_build_alloca (LLVMBuilderRef builder, LLVMTypeRef Ty,
306 LLVMValueRef ArraySize,
307 int alignment, const char *Name)
309 return wrap (unwrap (builder)->Insert (new AllocaInst (unwrap (Ty), unwrap (ArraySize), alignment), Name));
313 mono_llvm_build_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
314 const char *Name, gboolean is_volatile)
316 return wrap(unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name));
320 mono_llvm_build_aligned_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
321 const char *Name, gboolean is_volatile, int alignment)
325 ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
326 ins->setAlignment (alignment);
332 mono_llvm_build_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
333 gboolean is_volatile)
335 return wrap(unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile));
339 mono_llvm_build_aligned_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
340 gboolean is_volatile, int alignment)
344 ins = unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile);
345 ins->setAlignment (alignment);
351 mono_llvm_build_cmpxchg (LLVMBuilderRef builder, LLVMValueRef ptr, LLVMValueRef cmp, LLVMValueRef val)
353 AtomicCmpXchgInst *ins;
355 ins = unwrap(builder)->CreateAtomicCmpXchg (unwrap(ptr), unwrap (cmp), unwrap (val), SequentiallyConsistent);
360 mono_llvm_build_atomic_rmw (LLVMBuilderRef builder, AtomicRMWOp op, LLVMValueRef ptr, LLVMValueRef val)
362 AtomicRMWInst::BinOp aop = AtomicRMWInst::Xchg;
366 case LLVM_ATOMICRMW_OP_XCHG:
367 aop = AtomicRMWInst::Xchg;
369 case LLVM_ATOMICRMW_OP_ADD:
370 aop = AtomicRMWInst::Add;
373 g_assert_not_reached ();
377 ins = unwrap (builder)->CreateAtomicRMW (aop, unwrap (ptr), unwrap (val), AcquireRelease);
382 mono_llvm_build_fence (LLVMBuilderRef builder)
386 ins = unwrap (builder)->CreateFence (AcquireRelease);
391 mono_llvm_replace_uses_of (LLVMValueRef var, LLVMValueRef v)
393 Value *V = ConstantExpr::getTruncOrBitCast (unwrap<Constant> (v), unwrap (var)->getType ());
394 unwrap (var)->replaceAllUsesWith (V);
397 static cl::list<const PassInfo*, bool, PassNameParser>
398 PassList(cl::desc("Optimizations available:"));
401 force_pass_linking (void)
403 // Make sure the rest is linked in, but never executed
404 if (g_getenv ("FOO") != (char*)-1)
407 // This is a subset of the passes in LinkAllPasses.h
408 // The utility passes and the interprocedural passes are commented out
410 (void) llvm::createAAEvalPass();
411 (void) llvm::createAggressiveDCEPass();
412 (void) llvm::createAliasAnalysisCounterPass();
413 (void) llvm::createAliasDebugger();
415 (void) llvm::createArgumentPromotionPass();
416 (void) llvm::createStructRetPromotionPass();
418 (void) llvm::createBasicAliasAnalysisPass();
419 (void) llvm::createLibCallAliasAnalysisPass(0);
420 (void) llvm::createScalarEvolutionAliasAnalysisPass();
421 //(void) llvm::createBlockPlacementPass();
422 (void) llvm::createBreakCriticalEdgesPass();
423 (void) llvm::createCFGSimplificationPass();
425 (void) llvm::createConstantMergePass();
426 (void) llvm::createConstantPropagationPass();
429 (void) llvm::createDeadArgEliminationPass();
431 (void) llvm::createDeadCodeEliminationPass();
432 (void) llvm::createDeadInstEliminationPass();
433 (void) llvm::createDeadStoreEliminationPass();
435 (void) llvm::createDeadTypeEliminationPass();
436 (void) llvm::createDomOnlyPrinterPass();
437 (void) llvm::createDomPrinterPass();
438 (void) llvm::createDomOnlyViewerPass();
439 (void) llvm::createDomViewerPass();
440 (void) llvm::createEdgeProfilerPass();
441 (void) llvm::createOptimalEdgeProfilerPass();
442 (void) llvm::createFunctionInliningPass();
443 (void) llvm::createAlwaysInlinerPass();
444 (void) llvm::createGlobalDCEPass();
445 (void) llvm::createGlobalOptimizerPass();
446 (void) llvm::createGlobalsModRefPass();
447 (void) llvm::createIPConstantPropagationPass();
448 (void) llvm::createIPSCCPPass();
450 (void) llvm::createIndVarSimplifyPass();
451 (void) llvm::createInstructionCombiningPass();
453 (void) llvm::createInternalizePass(false);
455 (void) llvm::createLCSSAPass();
456 (void) llvm::createLICMPass();
457 (void) llvm::createLazyValueInfoPass();
458 //(void) llvm::createLoopDependenceAnalysisPass();
460 (void) llvm::createLoopExtractorPass();
462 (void) llvm::createLoopSimplifyPass();
463 (void) llvm::createLoopStrengthReducePass();
464 (void) llvm::createLoopUnrollPass();
465 (void) llvm::createLoopUnswitchPass();
466 (void) llvm::createLoopRotatePass();
467 (void) llvm::createLowerInvokePass();
469 (void) llvm::createLowerSetJmpPass();
471 (void) llvm::createLowerSwitchPass();
472 (void) llvm::createNoAAPass();
474 (void) llvm::createNoProfileInfoPass();
475 (void) llvm::createProfileEstimatorPass();
476 (void) llvm::createProfileVerifierPass();
477 (void) llvm::createProfileLoaderPass();
479 (void) llvm::createPromoteMemoryToRegisterPass();
480 (void) llvm::createDemoteRegisterToMemoryPass();
482 (void) llvm::createPruneEHPass();
483 (void) llvm::createPostDomOnlyPrinterPass();
484 (void) llvm::createPostDomPrinterPass();
485 (void) llvm::createPostDomOnlyViewerPass();
486 (void) llvm::createPostDomViewerPass();
488 (void) llvm::createReassociatePass();
489 (void) llvm::createSCCPPass();
490 (void) llvm::createScalarReplAggregatesPass();
491 //(void) llvm::createSimplifyLibCallsPass();
493 (void) llvm::createSingleLoopExtractorPass();
494 (void) llvm::createStripSymbolsPass();
495 (void) llvm::createStripNonDebugSymbolsPass();
496 (void) llvm::createStripDeadDebugInfoPass();
497 (void) llvm::createStripDeadPrototypesPass();
498 (void) llvm::createTailCallEliminationPass();
499 (void) llvm::createTailDuplicationPass();
500 (void) llvm::createJumpThreadingPass();
503 (void) llvm::createUnifyFunctionExitNodesPass();
505 (void) llvm::createInstCountPass();
506 (void) llvm::createCodeGenPreparePass();
507 (void) llvm::createGVNPass();
508 (void) llvm::createMemCpyOptPass();
509 (void) llvm::createLoopDeletionPass();
511 (void) llvm::createPostDomTree();
512 (void) llvm::createPostDomFrontier();
513 (void) llvm::createInstructionNamerPass();
514 (void) llvm::createPartialSpecializationPass();
515 (void) llvm::createFunctionAttrsPass();
516 (void) llvm::createMergeFunctionsPass();
517 (void) llvm::createPrintModulePass(0);
518 (void) llvm::createPrintFunctionPass("", 0);
519 (void) llvm::createDbgInfoPrinterPass();
520 (void) llvm::createModuleDebugInfoPrinterPass();
521 (void) llvm::createPartialInliningPass();
522 (void) llvm::createGEPSplitterPass();
523 (void) llvm::createLintPass();
525 (void) llvm::createSinkingPass();
528 #ifndef MONO_CROSS_COMPILE
530 LLVMExecutionEngineRef
531 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb, DlSymCb *dlsym_cb)
535 force_pass_linking ();
538 LLVMInitializeARMTarget ();
539 LLVMInitializeARMTargetInfo ();
540 LLVMInitializeARMTargetMC ();
542 LLVMInitializeX86Target ();
543 LLVMInitializeX86TargetInfo ();
544 LLVMInitializeX86TargetMC ();
547 mono_mm = new MonoJITMemoryManager ();
548 mono_mm->alloc_cb = alloc_cb;
549 mono_mm->dlsym_cb = dlsym_cb;
552 * The Default code model doesn't seem to work on amd64,
553 * test_0_fields_with_big_offsets (among others) crashes, because LLVM tries to call
554 * memset using a normal pcrel code which is in 32bit memory, while memset isn't.
558 opts.JITExceptionHandling = 1;
560 EngineBuilder b (unwrap (MP));
562 ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setCodeModel (CodeModel::Large).setAllocateGVsWithCode (true).create ();
564 ExecutionEngine *EE = b.setJITMemoryManager (mono_mm).setTargetOptions (opts).setAllocateGVsWithCode (true).create ();
568 EE->InstallExceptionTableRegister (exception_cb);
569 mono_event_listener = new MonoJITEventListener (emitted_cb);
570 EE->RegisterJITEventListener (mono_event_listener);
572 fpm = new FunctionPassManager (unwrap (MP));
574 fpm->add(new DataLayout(*EE->getDataLayout()));
576 PassRegistry &Registry = *PassRegistry::getPassRegistry();
577 initializeCore(Registry);
578 initializeScalarOpts(Registry);
579 initializeAnalysis(Registry);
580 initializeIPA(Registry);
581 initializeTransformUtils(Registry);
582 initializeInstCombine(Registry);
583 initializeTarget(Registry);
585 llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "");
587 if (PassList.size() > 0) {
588 /* Use the passes specified by the env variable */
589 /* Only the passes in force_pass_linking () can be used */
590 for (unsigned i = 0; i < PassList.size(); ++i) {
591 const PassInfo *PassInf = PassList[i];
594 if (PassInf->getNormalCtor())
595 P = PassInf->getNormalCtor()();
599 /* Use the same passes used by 'opt' by default, without the ipo passes */
600 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";
604 args = g_strsplit (opts, " ", 1000);
605 for (i = 0; args [i]; i++)
607 llvm::cl::ParseCommandLineOptions (i, args, "");
610 for (unsigned i = 0; i < PassList.size(); ++i) {
611 const PassInfo *PassInf = PassList[i];
614 if (PassInf->getNormalCtor())
615 P = PassInf->getNormalCtor()();
616 g_assert (P->getPassKind () == llvm::PT_Function || P->getPassKind () == llvm::PT_Loop);
621 fpm->add(createInstructionCombiningPass());
622 fpm->add(createReassociatePass());
623 fpm->add(createGVNPass());
624 fpm->add(createCFGSimplificationPass());
632 mono_llvm_dispose_ee (LLVMExecutionEngineRef ee)
641 LLVMExecutionEngineRef
642 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb, DlSymCb *dlsym_cb)
644 g_assert_not_reached ();
649 mono_llvm_dispose_ee (LLVMExecutionEngineRef ee)
651 g_assert_not_reached ();
656 LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
659 g_assert_not_reached ();
663 LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global)
665 g_assert_not_reached ();
669 #endif /* !MONO_CROSS_COMPILE */