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