2009-11-11 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/Target/TargetOptions.h>
29 #include <llvm/Target/TargetData.h>
30 #include <llvm/Analysis/Verifier.h>
31 #include <llvm/Transforms/Scalar.h>
32 #include <llvm/Support/CommandLine.h>
33 #include "llvm/Support/PassNameParser.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include <llvm/CodeGen/Passes.h>
36 #include <llvm/CodeGen/MachineFunctionPass.h>
37 //#include <llvm/LinkAllPasses.h>
38
39 #include "llvm-c/Core.h"
40 #include "llvm-c/ExecutionEngine.h"
41
42 #include "mini-llvm-cpp.h"
43
44 extern "C" void LLVMInitializeX86TargetInfo();
45
46 using namespace llvm;
47
48 class MonoJITMemoryManager : public JITMemoryManager
49 {
50 private:
51         JITMemoryManager *mm;
52
53 public:
54         /* Callbacks installed by mono */
55         AllocCodeMemoryCb *alloc_cb;
56         FunctionEmittedCb *emitted_cb;
57
58         MonoJITMemoryManager ();
59         ~MonoJITMemoryManager ();
60
61         void setMemoryWritable (void);
62
63         void setMemoryExecutable (void);
64
65         void AllocateGOT();
66
67     unsigned char *getGOTBase() const {
68                 return mm->getGOTBase ();
69     }
70
71 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION < 7
72     void *getDlsymTable() const {
73                 return mm->getDlsymTable ();
74     }
75
76         void SetDlsymTable(void *ptr);
77 #endif
78
79         void setPoisonMemory(bool) {
80         }
81
82         unsigned char *startFunctionBody(const Function *F, 
83                                                                          uintptr_t &ActualSize);
84   
85         unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
86                                                                  unsigned Alignment);
87   
88         void endFunctionBody(const Function *F, unsigned char *FunctionStart,
89                                                  unsigned char *FunctionEnd);
90
91         unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
92
93         uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment);
94   
95         void deallocateMemForFunction(const Function *F);
96   
97         unsigned char*startExceptionTable(const Function* F,
98                                                                           uintptr_t &ActualSize);
99   
100         void endExceptionTable(const Function *F, unsigned char *TableStart,
101                                                    unsigned char *TableEnd, 
102                                                    unsigned char* FrameRegister);
103
104 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION >= 7
105         virtual void deallocateFunctionBody(void*) {
106         }
107
108         virtual void deallocateExceptionTable(void*) {
109         }
110 #endif
111 };
112
113 MonoJITMemoryManager::MonoJITMemoryManager ()
114 {
115         SizeRequired = true;
116         mm = JITMemoryManager::CreateDefaultMemManager ();
117 }
118
119 MonoJITMemoryManager::~MonoJITMemoryManager ()
120 {
121 }
122
123 void
124 MonoJITMemoryManager::setMemoryWritable (void)
125 {
126 }
127
128 void
129 MonoJITMemoryManager::setMemoryExecutable (void)
130 {
131 }
132
133 void
134 MonoJITMemoryManager::AllocateGOT()
135 {
136         mm->AllocateGOT ();
137 }
138
139 #if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION < 7  
140 void
141 MonoJITMemoryManager::SetDlsymTable(void *ptr)
142 {
143         mm->SetDlsymTable (ptr);
144 }
145 #endif
146
147 unsigned char *
148 MonoJITMemoryManager::startFunctionBody(const Function *F, 
149                                         uintptr_t &ActualSize)
150 {
151         return alloc_cb (wrap (F), ActualSize);
152 }
153   
154 unsigned char *
155 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
156                            unsigned Alignment)
157 {
158         return alloc_cb (wrap (F), StubSize);
159 }
160   
161 void
162 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
163                                   unsigned char *FunctionEnd)
164 {
165         emitted_cb (wrap (F), FunctionStart, FunctionEnd);
166 }
167
168 unsigned char *
169 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
170 {
171         return new unsigned char [Size];
172 }
173
174 uint8_t *
175 MonoJITMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
176 {
177         return new unsigned char [Size];
178 }
179
180 void
181 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
182 {
183 }
184   
185 unsigned char*
186 MonoJITMemoryManager::startExceptionTable(const Function* F,
187                                           uintptr_t &ActualSize)
188 {
189         return alloc_cb (wrap (F), ActualSize);
190 }
191   
192 void
193 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
194                                         unsigned char *TableEnd, 
195                                         unsigned char* FrameRegister)
196 {
197 }
198
199 static MonoJITMemoryManager *mono_mm;
200
201 static FunctionPassManager *fpm;
202
203 static LLVMContext ctx;
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_volatile_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
230                                                            const char *Name)
231 {
232         return wrap(unwrap(builder)->CreateLoad(unwrap(PointerVal), true, 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 LLVMExecutionEngineRef
246 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb)
247 {
248   std::string Error;
249
250   LLVMInitializeX86Target ();
251   LLVMInitializeX86TargetInfo ();
252
253   llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "", false);
254
255   mono_mm = new MonoJITMemoryManager ();
256   mono_mm->alloc_cb = alloc_cb;
257   mono_mm->emitted_cb = emitted_cb;
258
259   DwarfExceptionHandling = true;
260   // PrettyStackTrace installs signal handlers which trip up libgc
261   DisablePrettyStackTrace = true;
262
263   ExecutionEngine *EE = ExecutionEngine::createJIT (unwrap (MP), &Error, mono_mm, CodeGenOpt::Default);
264   if (!EE) {
265           errs () << "Unable to create LLVM ExecutionEngine: " << Error << "\n";
266           g_assert_not_reached ();
267   }
268   EE->InstallExceptionTableRegister (exception_cb);
269
270   fpm = new FunctionPassManager (unwrap (MP));
271
272   fpm->add(new TargetData(*EE->getTargetData()));
273   /* Add a random set of passes */
274   /* Make this run-time configurable */
275   fpm->add(createInstructionCombiningPass());
276   fpm->add(createReassociatePass());
277   fpm->add(createGVNPass());
278   fpm->add(createCFGSimplificationPass());
279
280   /* Add passes specified by the env variable */
281   /* FIXME: This can only add passes which are linked in, thus are already used */
282   for (unsigned i = 0; i < PassList.size(); ++i) {
283       const PassInfo *PassInf = PassList[i];
284       Pass *P = 0;
285
286       if (PassInf->getNormalCtor())
287                   P = PassInf->getNormalCtor()();
288           if (dynamic_cast<MachineFunctionPass*>(P) != 0) {
289                   errs () << PassInf->getPassName () << " is a machine function pass.\n";
290           } else {
291                   fpm->add (P);
292           }
293   }
294
295   return wrap(EE);
296 }
297
298 void
299 mono_llvm_dispose_ee (LLVMExecutionEngineRef ee)
300 {
301         delete unwrap (ee);
302
303         delete fpm;
304 }