Fix LLVM build.
[mono-project/dkf.git] / mono / mini / mini-llvm-cpp.cpp
blob7bb23ad9301240c72e921c144ccdb3b1ed8a9681
1 //
2 // mini-llvm-cpp.cpp: C++ support classes for the mono LLVM integration
3 //
4 // (C) 2009 Novell, Inc.
5 //
7 //
8 // We need to override some stuff in LLVM, but this cannot be done using the C
9 // interface, so we have to use some C++ code here.
10 // The things which we override are:
11 // - the default JIT code manager used by LLVM doesn't allocate memory using
12 // MAP_32BIT, we require it.
13 // - add some callbacks so we can obtain the size of methods and their exception
14 // tables.
18 // Mono's internal header files are not C++ clean, so avoid including them if
19 // possible
22 #include <stdint.h>
24 #include <llvm/Support/raw_ostream.h>
25 #include <llvm/PassManager.h>
26 #include <llvm/ExecutionEngine/ExecutionEngine.h>
27 #include <llvm/ExecutionEngine/JITMemoryManager.h>
28 #include <llvm/ExecutionEngine/JITEventListener.h>
29 #include <llvm/Target/TargetOptions.h>
30 #include <llvm/Target/TargetData.h>
31 #include <llvm/Target/TargetRegisterInfo.h>
32 #include <llvm/Analysis/Verifier.h>
33 #include <llvm/Transforms/Scalar.h>
34 #include <llvm/Support/CommandLine.h>
35 #include "llvm/Support/PassNameParser.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include <llvm/CodeGen/Passes.h>
38 #include <llvm/CodeGen/MachineFunctionPass.h>
39 #include <llvm/CodeGen/MachineFunction.h>
40 #include <llvm/CodeGen/MachineFrameInfo.h>
41 #include <llvm/Support/PassManagerBuilder.h>
42 //#include <llvm/LinkAllPasses.h>
44 #include "llvm-c/Core.h"
45 #include "llvm-c/ExecutionEngine.h"
47 #include "mini-llvm-cpp.h"
49 #define LLVM_CHECK_VERSION(major,minor) \
50 ((LLVM_MAJOR_VERSION > (major)) || \
51 ((LLVM_MAJOR_VERSION == (major)) && (LLVM_MINOR_VERSION >= (minor))))
53 extern "C" void LLVMInitializeX86TargetInfo();
55 using namespace llvm;
57 class MonoJITMemoryManager : public JITMemoryManager
59 private:
60 JITMemoryManager *mm;
62 public:
63 /* Callbacks installed by mono */
64 AllocCodeMemoryCb *alloc_cb;
66 MonoJITMemoryManager ();
67 ~MonoJITMemoryManager ();
69 void setMemoryWritable (void);
71 void setMemoryExecutable (void);
73 void AllocateGOT();
75 unsigned char *getGOTBase() const {
76 return mm->getGOTBase ();
79 void setPoisonMemory(bool) {
82 unsigned char *startFunctionBody(const Function *F,
83 uintptr_t &ActualSize);
85 unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
86 unsigned Alignment);
88 void endFunctionBody(const Function *F, unsigned char *FunctionStart,
89 unsigned char *FunctionEnd);
91 unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
93 uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment);
95 void deallocateMemForFunction(const Function *F);
97 unsigned char*startExceptionTable(const Function* F,
98 uintptr_t &ActualSize);
100 void endExceptionTable(const Function *F, unsigned char *TableStart,
101 unsigned char *TableEnd,
102 unsigned char* FrameRegister);
104 virtual void deallocateFunctionBody(void*) {
107 virtual void deallocateExceptionTable(void*) {
111 MonoJITMemoryManager::MonoJITMemoryManager ()
113 mm = JITMemoryManager::CreateDefaultMemManager ();
116 MonoJITMemoryManager::~MonoJITMemoryManager ()
118 delete mm;
121 void
122 MonoJITMemoryManager::setMemoryWritable (void)
126 void
127 MonoJITMemoryManager::setMemoryExecutable (void)
131 void
132 MonoJITMemoryManager::AllocateGOT()
134 mm->AllocateGOT ();
137 unsigned char *
138 MonoJITMemoryManager::startFunctionBody(const Function *F,
139 uintptr_t &ActualSize)
141 // FIXME: This leaks memory
142 if (ActualSize == 0)
143 ActualSize = 128;
144 return alloc_cb (wrap (F), ActualSize);
147 unsigned char *
148 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
149 unsigned Alignment)
151 return alloc_cb (wrap (F), StubSize);
154 void
155 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
156 unsigned char *FunctionEnd)
160 unsigned char *
161 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
163 return new unsigned char [Size];
166 uint8_t *
167 MonoJITMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
169 return new unsigned char [Size];
172 void
173 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
177 unsigned char*
178 MonoJITMemoryManager::startExceptionTable(const Function* F,
179 uintptr_t &ActualSize)
181 return startFunctionBody(F, ActualSize);
184 void
185 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
186 unsigned char *TableEnd,
187 unsigned char* FrameRegister)
191 class MonoJITEventListener : public JITEventListener {
193 public:
194 FunctionEmittedCb *emitted_cb;
196 MonoJITEventListener (FunctionEmittedCb *cb) {
197 emitted_cb = cb;
200 virtual void NotifyFunctionEmitted(const Function &F,
201 void *Code, size_t Size,
202 const EmittedFunctionDetails &Details) {
204 * X86TargetMachine::setCodeModelForJIT() sets the code model to Large on amd64,
205 * which means the JIT will generate calls of the form
206 * mov reg, <imm>
207 * call *reg
208 * Our trampoline code can't patch this. Passing CodeModel::Small to createJIT
209 * doesn't seem to work, we need Default. A discussion is here:
210 * http://lists.cs.uiuc.edu/pipermail/llvmdev/2009-December/027999.html
211 * There seems to no way to get the TargeMachine used by an EE either, so we
212 * install a profiler hook and reset the code model here.
213 * This should be inside an ifdef, but we can't include our config.h either,
214 * since its definitions conflict with LLVM's config.h.
217 //#if defined(TARGET_X86) || defined(TARGET_AMD64)
218 #ifndef LLVM_MONO_BRANCH
219 /* The LLVM mono branch contains a workaround, so this is not needed */
220 if (Details.MF->getTarget ().getCodeModel () == CodeModel::Large) {
221 Details.MF->getTarget ().setCodeModel (CodeModel::Default);
223 #endif
224 //#endif
226 emitted_cb (wrap (&F), Code, (char*)Code + Size);
230 static MonoJITMemoryManager *mono_mm;
231 static MonoJITEventListener *mono_event_listener;
233 static FunctionPassManager *fpm;
235 void
236 mono_llvm_optimize_method (LLVMValueRef method)
238 verifyFunction (*(unwrap<Function> (method)));
239 fpm->run (*unwrap<Function> (method));
242 void
243 mono_llvm_dump_value (LLVMValueRef value)
245 /* Same as LLVMDumpValue (), but print to stdout */
246 fflush (stdout);
247 outs () << (*unwrap<Value> (value));
250 /* Missing overload for building an alloca with an alignment */
251 LLVMValueRef
252 mono_llvm_build_alloca (LLVMBuilderRef builder, LLVMTypeRef Ty,
253 LLVMValueRef ArraySize,
254 int alignment, const char *Name)
256 return wrap (unwrap (builder)->Insert (new AllocaInst (unwrap (Ty), unwrap (ArraySize), alignment), Name));
259 LLVMValueRef
260 mono_llvm_build_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
261 const char *Name, gboolean is_volatile)
263 return wrap(unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name));
266 LLVMValueRef
267 mono_llvm_build_aligned_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
268 const char *Name, gboolean is_volatile, int alignment)
270 LoadInst *ins;
272 ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
273 ins->setAlignment (alignment);
275 return wrap(ins);
278 LLVMValueRef
279 mono_llvm_build_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
280 gboolean is_volatile)
282 return wrap(unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile));
285 LLVMValueRef
286 mono_llvm_build_aligned_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
287 gboolean is_volatile, int alignment)
289 StoreInst *ins;
291 ins = unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile);
292 ins->setAlignment (alignment);
294 return wrap (ins);
297 void
298 mono_llvm_replace_uses_of (LLVMValueRef var, LLVMValueRef v)
300 Value *V = ConstantExpr::getTruncOrBitCast (unwrap<Constant> (v), unwrap (var)->getType ());
301 unwrap (var)->replaceAllUsesWith (V);
304 static cl::list<const PassInfo*, bool, PassNameParser>
305 PassList(cl::desc("Optimizations available:"));
307 static void
308 force_pass_linking (void)
310 // Make sure the rest is linked in, but never executed
311 if (getenv ("FOO") != (char*)-1)
312 return;
314 // This is a subset of the passes in LinkAllPasses.h
315 // The utility passes and the interprocedural passes are commented out
317 (void) llvm::createAAEvalPass();
318 (void) llvm::createAggressiveDCEPass();
319 (void) llvm::createAliasAnalysisCounterPass();
320 (void) llvm::createAliasDebugger();
322 (void) llvm::createArgumentPromotionPass();
323 (void) llvm::createStructRetPromotionPass();
325 (void) llvm::createBasicAliasAnalysisPass();
326 (void) llvm::createLibCallAliasAnalysisPass(0);
327 (void) llvm::createScalarEvolutionAliasAnalysisPass();
328 (void) llvm::createBlockPlacementPass();
329 (void) llvm::createBreakCriticalEdgesPass();
330 (void) llvm::createCFGSimplificationPass();
332 (void) llvm::createConstantMergePass();
333 (void) llvm::createConstantPropagationPass();
336 (void) llvm::createDeadArgEliminationPass();
338 (void) llvm::createDeadCodeEliminationPass();
339 (void) llvm::createDeadInstEliminationPass();
340 (void) llvm::createDeadStoreEliminationPass();
342 (void) llvm::createDeadTypeEliminationPass();
343 (void) llvm::createDomOnlyPrinterPass();
344 (void) llvm::createDomPrinterPass();
345 (void) llvm::createDomOnlyViewerPass();
346 (void) llvm::createDomViewerPass();
347 (void) llvm::createEdgeProfilerPass();
348 (void) llvm::createOptimalEdgeProfilerPass();
349 (void) llvm::createFunctionInliningPass();
350 (void) llvm::createAlwaysInlinerPass();
351 (void) llvm::createGlobalDCEPass();
352 (void) llvm::createGlobalOptimizerPass();
353 (void) llvm::createGlobalsModRefPass();
354 (void) llvm::createIPConstantPropagationPass();
355 (void) llvm::createIPSCCPPass();
357 (void) llvm::createIndVarSimplifyPass();
358 (void) llvm::createInstructionCombiningPass();
360 (void) llvm::createInternalizePass(false);
362 (void) llvm::createLCSSAPass();
363 (void) llvm::createLICMPass();
364 (void) llvm::createLazyValueInfoPass();
365 (void) llvm::createLoopDependenceAnalysisPass();
367 (void) llvm::createLoopExtractorPass();
369 (void) llvm::createLoopSimplifyPass();
370 (void) llvm::createLoopStrengthReducePass();
371 (void) llvm::createLoopUnrollPass();
372 (void) llvm::createLoopUnswitchPass();
373 (void) llvm::createLoopRotatePass();
374 (void) llvm::createLowerInvokePass();
376 (void) llvm::createLowerSetJmpPass();
378 (void) llvm::createLowerSwitchPass();
379 (void) llvm::createNoAAPass();
381 (void) llvm::createNoProfileInfoPass();
382 (void) llvm::createProfileEstimatorPass();
383 (void) llvm::createProfileVerifierPass();
384 (void) llvm::createProfileLoaderPass();
386 (void) llvm::createPromoteMemoryToRegisterPass();
387 (void) llvm::createDemoteRegisterToMemoryPass();
389 (void) llvm::createPruneEHPass();
390 (void) llvm::createPostDomOnlyPrinterPass();
391 (void) llvm::createPostDomPrinterPass();
392 (void) llvm::createPostDomOnlyViewerPass();
393 (void) llvm::createPostDomViewerPass();
395 (void) llvm::createReassociatePass();
396 (void) llvm::createSCCPPass();
397 (void) llvm::createScalarReplAggregatesPass();
398 (void) llvm::createSimplifyLibCallsPass();
400 (void) llvm::createSingleLoopExtractorPass();
401 (void) llvm::createStripSymbolsPass();
402 (void) llvm::createStripNonDebugSymbolsPass();
403 (void) llvm::createStripDeadDebugInfoPass();
404 (void) llvm::createStripDeadPrototypesPass();
405 (void) llvm::createTailCallEliminationPass();
406 (void) llvm::createTailDuplicationPass();
407 (void) llvm::createJumpThreadingPass();
410 (void) llvm::createUnifyFunctionExitNodesPass();
412 (void) llvm::createInstCountPass();
413 (void) llvm::createCodeGenPreparePass();
414 (void) llvm::createGVNPass();
415 (void) llvm::createMemCpyOptPass();
416 (void) llvm::createLoopDeletionPass();
418 (void) llvm::createPostDomTree();
419 (void) llvm::createPostDomFrontier();
420 (void) llvm::createInstructionNamerPass();
421 (void) llvm::createPartialSpecializationPass();
422 (void) llvm::createFunctionAttrsPass();
423 (void) llvm::createMergeFunctionsPass();
424 (void) llvm::createPrintModulePass(0);
425 (void) llvm::createPrintFunctionPass("", 0);
426 (void) llvm::createDbgInfoPrinterPass();
427 (void) llvm::createModuleDebugInfoPrinterPass();
428 (void) llvm::createPartialInliningPass();
429 (void) llvm::createGEPSplitterPass();
430 (void) llvm::createLintPass();
432 (void) llvm::createSinkingPass();
435 LLVMExecutionEngineRef
436 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb)
438 std::string Error;
440 force_pass_linking ();
442 LLVMInitializeX86Target ();
443 LLVMInitializeX86TargetInfo ();
445 mono_mm = new MonoJITMemoryManager ();
446 mono_mm->alloc_cb = alloc_cb;
448 JITExceptionHandling = true;
449 // PrettyStackTrace installs signal handlers which trip up libgc
450 DisablePrettyStackTrace = true;
452 ExecutionEngine *EE = ExecutionEngine::createJIT (unwrap (MP), &Error, mono_mm, CodeGenOpt::Default);
453 if (!EE) {
454 errs () << "Unable to create LLVM ExecutionEngine: " << Error << "\n";
455 g_assert_not_reached ();
457 EE->InstallExceptionTableRegister (exception_cb);
458 mono_event_listener = new MonoJITEventListener (emitted_cb);
459 EE->RegisterJITEventListener (mono_event_listener);
461 fpm = new FunctionPassManager (unwrap (MP));
463 fpm->add(new TargetData(*EE->getTargetData()));
465 PassRegistry &Registry = *PassRegistry::getPassRegistry();
466 initializeCore(Registry);
467 initializeScalarOpts(Registry);
468 //initializeIPO(Registry);
469 initializeAnalysis(Registry);
470 initializeIPA(Registry);
471 initializeTransformUtils(Registry);
472 initializeInstCombine(Registry);
473 //initializeInstrumentation(Registry);
474 initializeTarget(Registry);
476 llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "", false);
478 if (PassList.size() > 0) {
479 /* Use the passes specified by the env variable */
480 /* Only the passes in force_pass_linking () can be used */
481 for (unsigned i = 0; i < PassList.size(); ++i) {
482 const PassInfo *PassInf = PassList[i];
483 Pass *P = 0;
485 if (PassInf->getNormalCtor())
486 P = PassInf->getNormalCtor()();
487 fpm->add (P);
489 } else {
490 /* Use the same passes used by 'opt' by default, without the ipo passes */
491 const char *opts = "-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -domtree -domfrontier -scalarrepl -simplify-libcalls -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 -preverify -domtree -verify";
492 char **args;
493 int i;
495 args = g_strsplit (opts, " ", 1000);
496 for (i = 0; args [i]; i++)
498 llvm::cl::ParseCommandLineOptions (i, args, "", false);
499 g_strfreev (args);
501 for (unsigned i = 0; i < PassList.size(); ++i) {
502 const PassInfo *PassInf = PassList[i];
503 Pass *P = 0;
505 if (PassInf->getNormalCtor())
506 P = PassInf->getNormalCtor()();
507 fpm->add (P);
511 fpm->add(createInstructionCombiningPass());
512 fpm->add(createReassociatePass());
513 fpm->add(createGVNPass());
514 fpm->add(createCFGSimplificationPass());
518 return wrap(EE);
521 void
522 mono_llvm_dispose_ee (LLVMExecutionEngineRef ee)
524 delete unwrap (ee);
526 delete fpm;