Fixed.
[mono.git] / mono / mini / mini-llvm-cpp.cpp
1 //
2 // mini-llvm-cpp.cpp: C++ support classes for the mono LLVM integration
3 //
4 // (C) 2009 Novell, Inc.
5 //
6
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.
15 //
16
17 //
18 // Mono's internal header files are not C++ clean, so avoid including them if 
19 // possible
20 //
21
22 #include <stdint.h>
23
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/StandardPasses.h>
42 //#include <llvm/LinkAllPasses.h>
43
44 #include "llvm-c/Core.h"
45 #include "llvm-c/ExecutionEngine.h"
46
47 #include "mini-llvm-cpp.h"
48
49 extern "C" void LLVMInitializeX86TargetInfo();
50
51 using namespace llvm;
52
53 class MonoJITMemoryManager : public JITMemoryManager
54 {
55 private:
56         JITMemoryManager *mm;
57
58 public:
59         /* Callbacks installed by mono */
60         AllocCodeMemoryCb *alloc_cb;
61
62         MonoJITMemoryManager ();
63         ~MonoJITMemoryManager ();
64
65         void setMemoryWritable (void);
66
67         void setMemoryExecutable (void);
68
69         void AllocateGOT();
70
71     unsigned char *getGOTBase() const {
72                 return mm->getGOTBase ();
73     }
74
75 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION < 7
76     void *getDlsymTable() const {
77                 return mm->getDlsymTable ();
78     }
79
80         void SetDlsymTable(void *ptr);
81 #endif
82
83         void setPoisonMemory(bool) {
84         }
85
86         unsigned char *startFunctionBody(const Function *F, 
87                                                                          uintptr_t &ActualSize);
88   
89         unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
90                                                                  unsigned Alignment);
91   
92         void endFunctionBody(const Function *F, unsigned char *FunctionStart,
93                                                  unsigned char *FunctionEnd);
94
95         unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
96
97         uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment);
98   
99         void deallocateMemForFunction(const Function *F);
100   
101         unsigned char*startExceptionTable(const Function* F,
102                                                                           uintptr_t &ActualSize);
103   
104         void endExceptionTable(const Function *F, unsigned char *TableStart,
105                                                    unsigned char *TableEnd, 
106                                                    unsigned char* FrameRegister);
107
108 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION >= 7
109         virtual void deallocateFunctionBody(void*) {
110         }
111
112         virtual void deallocateExceptionTable(void*) {
113         }
114 #endif
115 };
116
117 MonoJITMemoryManager::MonoJITMemoryManager ()
118 {
119         SizeRequired = true;
120         mm = JITMemoryManager::CreateDefaultMemManager ();
121 }
122
123 MonoJITMemoryManager::~MonoJITMemoryManager ()
124 {
125 }
126
127 void
128 MonoJITMemoryManager::setMemoryWritable (void)
129 {
130 }
131
132 void
133 MonoJITMemoryManager::setMemoryExecutable (void)
134 {
135 }
136
137 void
138 MonoJITMemoryManager::AllocateGOT()
139 {
140         mm->AllocateGOT ();
141 }
142
143 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION < 7  
144 void
145 MonoJITMemoryManager::SetDlsymTable(void *ptr)
146 {
147         mm->SetDlsymTable (ptr);
148 }
149 #endif
150
151 unsigned char *
152 MonoJITMemoryManager::startFunctionBody(const Function *F, 
153                                         uintptr_t &ActualSize)
154 {
155         return alloc_cb (wrap (F), ActualSize);
156 }
157   
158 unsigned char *
159 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
160                            unsigned Alignment)
161 {
162         return alloc_cb (wrap (F), StubSize);
163 }
164   
165 void
166 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
167                                   unsigned char *FunctionEnd)
168 {
169 }
170
171 unsigned char *
172 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
173 {
174         return new unsigned char [Size];
175 }
176
177 uint8_t *
178 MonoJITMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
179 {
180         return new unsigned char [Size];
181 }
182
183 void
184 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
185 {
186 }
187   
188 unsigned char*
189 MonoJITMemoryManager::startExceptionTable(const Function* F,
190                                           uintptr_t &ActualSize)
191 {
192         return alloc_cb (wrap (F), ActualSize);
193 }
194   
195 void
196 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
197                                         unsigned char *TableEnd, 
198                                         unsigned char* FrameRegister)
199 {
200 }
201
202 static MonoJITMemoryManager *mono_mm;
203
204 static FunctionPassManager *fpm;
205
206 void
207 mono_llvm_optimize_method (LLVMValueRef method)
208 {
209         verifyFunction (*(unwrap<Function> (method)));
210         fpm->run (*unwrap<Function> (method));
211 }
212
213 void
214 mono_llvm_dump_value (LLVMValueRef value)
215 {
216         /* Same as LLVMDumpValue (), but print to stdout */
217         outs () << (*unwrap<Value> (value));
218 }
219
220 /* Missing overload for building an alloca with an alignment */
221 LLVMValueRef
222 mono_llvm_build_alloca (LLVMBuilderRef builder, LLVMTypeRef Ty, 
223                                                 LLVMValueRef ArraySize,
224                                                 int alignment, const char *Name)
225 {
226         return wrap (unwrap (builder)->Insert (new AllocaInst (unwrap (Ty), unwrap (ArraySize), alignment), Name));
227 }
228
229 LLVMValueRef 
230 mono_llvm_build_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
231                                           const char *Name, gboolean is_volatile)
232 {
233         return wrap(unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name));
234 }
235
236 LLVMValueRef 
237 mono_llvm_build_aligned_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
238                                                           const char *Name, gboolean is_volatile, int alignment)
239 {
240         LoadInst *ins;
241
242         ins = unwrap(builder)->CreateLoad(unwrap(PointerVal), is_volatile, Name);
243         ins->setAlignment (alignment);
244
245         return wrap(ins);
246 }
247
248 LLVMValueRef 
249 mono_llvm_build_store (LLVMBuilderRef builder, LLVMValueRef Val, LLVMValueRef PointerVal,
250                                           gboolean is_volatile)
251 {
252         return wrap(unwrap(builder)->CreateStore(unwrap(Val), unwrap(PointerVal), is_volatile));
253 }
254
255 void
256 mono_llvm_replace_uses_of (LLVMValueRef var, LLVMValueRef v)
257 {
258         Value *V = ConstantExpr::getTruncOrBitCast (unwrap<Constant> (v), unwrap (var)->getType ());
259         unwrap (var)->replaceAllUsesWith (V);
260 }
261
262 static cl::list<const PassInfo*, bool, PassNameParser>
263 PassList(cl::desc("Optimizations available:"));
264
265 class MonoJITEventListener : public JITEventListener {
266
267 public:
268         FunctionEmittedCb *emitted_cb;
269
270         MonoJITEventListener (FunctionEmittedCb *cb) {
271                 emitted_cb = cb;
272         }
273
274         virtual void NotifyFunctionEmitted(const Function &F,
275                                                                            void *Code, size_t Size,
276                                                                            const EmittedFunctionDetails &Details) {
277                 /*
278                  * X86TargetMachine::setCodeModelForJIT() sets the code model to Large on amd64,
279                  * which means the JIT will generate calls of the form
280                  * mov reg, <imm>
281                  * call *reg
282                  * Our trampoline code can't patch this. Passing CodeModel::Small to createJIT
283                  * doesn't seem to work, we need Default. A discussion is here:
284                  * http://lists.cs.uiuc.edu/pipermail/llvmdev/2009-December/027999.html
285                  * There seems to no way to get the TargeMachine used by an EE either, so we
286                  * install a profiler hook and reset the code model here.
287                  * This should be inside an ifdef, but we can't include our config.h either,
288                  * since its definitions conflict with LLVM's config.h.
289                  *
290                  */
291                 //#if defined(TARGET_X86) || defined(TARGET_AMD64)
292 #ifndef LLVM_MONO_BRANCH
293                 /* The LLVM mono branch contains a workaround, so this is not needed */
294                 if (Details.MF->getTarget ().getCodeModel () == CodeModel::Large) {
295                         Details.MF->getTarget ().setCodeModel (CodeModel::Default);
296                 }
297 #endif
298                 //#endif
299
300                 emitted_cb (wrap (&F), Code, (char*)Code + Size);
301         }
302 };
303
304 LLVMExecutionEngineRef
305 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb)
306 {
307   std::string Error;
308
309   LLVMInitializeX86Target ();
310   LLVMInitializeX86TargetInfo ();
311
312   llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "", false);
313
314   mono_mm = new MonoJITMemoryManager ();
315   mono_mm->alloc_cb = alloc_cb;
316
317 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION < 8
318    DwarfExceptionHandling = true;
319 #else
320    JITExceptionHandling = true;
321 #endif
322   // PrettyStackTrace installs signal handlers which trip up libgc
323   DisablePrettyStackTrace = true;
324
325   ExecutionEngine *EE = ExecutionEngine::createJIT (unwrap (MP), &Error, mono_mm, CodeGenOpt::Default);
326   if (!EE) {
327           errs () << "Unable to create LLVM ExecutionEngine: " << Error << "\n";
328           g_assert_not_reached ();
329   }
330   EE->InstallExceptionTableRegister (exception_cb);
331   EE->RegisterJITEventListener (new MonoJITEventListener (emitted_cb));
332
333   fpm = new FunctionPassManager (unwrap (MP));
334
335   fpm->add(new TargetData(*EE->getTargetData()));
336   /* Add a random set of passes */
337   /* Make this run-time configurable */
338   //createStandardFunctionPasses (fpm, 2);
339   fpm->add(createInstructionCombiningPass());
340   fpm->add(createReassociatePass());
341   fpm->add(createGVNPass());
342   fpm->add(createCFGSimplificationPass());
343
344   /* Add passes specified by the env variable */
345   /* FIXME: This can only add passes which are linked in, thus are already used */
346   for (unsigned i = 0; i < PassList.size(); ++i) {
347       const PassInfo *PassInf = PassList[i];
348       Pass *P = 0;
349
350       if (PassInf->getNormalCtor())
351                   P = PassInf->getNormalCtor()();
352           fpm->add (P);
353   }
354
355   return wrap(EE);
356 }
357
358 void
359 mono_llvm_dispose_ee (LLVMExecutionEngineRef ee)
360 {
361         delete unwrap (ee);
362
363         delete fpm;
364 }