2009-08-28 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     void *getDlsymTable() const {
72                 return mm->getDlsymTable ();
73     }
74
75         void setPoisonMemory(bool) {
76         }
77       
78         void SetDlsymTable(void *ptr);
79   
80         unsigned char *startFunctionBody(const Function *F, 
81                                                                          uintptr_t &ActualSize);
82   
83         unsigned char *allocateStub(const GlobalValue* F, unsigned StubSize,
84                                                                  unsigned Alignment);
85   
86         void endFunctionBody(const Function *F, unsigned char *FunctionStart,
87                                                  unsigned char *FunctionEnd);
88
89         unsigned char *allocateSpace(intptr_t Size, unsigned Alignment);
90
91         uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment);
92   
93         void deallocateMemForFunction(const Function *F);
94   
95         unsigned char*startExceptionTable(const Function* F,
96                                                                           uintptr_t &ActualSize);
97   
98         void endExceptionTable(const Function *F, unsigned char *TableStart,
99                                                    unsigned char *TableEnd, 
100                                                    unsigned char* FrameRegister);
101 };
102
103 MonoJITMemoryManager::MonoJITMemoryManager ()
104 {
105         SizeRequired = true;
106         mm = JITMemoryManager::CreateDefaultMemManager ();
107 }
108
109 MonoJITMemoryManager::~MonoJITMemoryManager ()
110 {
111 }
112
113 void
114 MonoJITMemoryManager::setMemoryWritable (void)
115 {
116 }
117
118 void
119 MonoJITMemoryManager::setMemoryExecutable (void)
120 {
121 }
122
123 void
124 MonoJITMemoryManager::AllocateGOT()
125 {
126         mm->AllocateGOT ();
127 }
128   
129 void
130 MonoJITMemoryManager::SetDlsymTable(void *ptr)
131 {
132         mm->SetDlsymTable (ptr);
133 }
134   
135 unsigned char *
136 MonoJITMemoryManager::startFunctionBody(const Function *F, 
137                                         uintptr_t &ActualSize)
138 {
139         return alloc_cb (wrap (F), ActualSize);
140 }
141   
142 unsigned char *
143 MonoJITMemoryManager::allocateStub(const GlobalValue* F, unsigned StubSize,
144                            unsigned Alignment)
145 {
146         return alloc_cb (wrap (F), StubSize);
147 }
148   
149 void
150 MonoJITMemoryManager::endFunctionBody(const Function *F, unsigned char *FunctionStart,
151                                   unsigned char *FunctionEnd)
152 {
153         emitted_cb (wrap (F), FunctionStart, FunctionEnd);
154 }
155
156 unsigned char *
157 MonoJITMemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
158 {
159         return new unsigned char [Size];
160 }
161
162 uint8_t *
163 MonoJITMemoryManager::allocateGlobal(uintptr_t Size, unsigned Alignment)
164 {
165         return new unsigned char [Size];
166 }
167
168 void
169 MonoJITMemoryManager::deallocateMemForFunction(const Function *F)
170 {
171 }
172   
173 unsigned char*
174 MonoJITMemoryManager::startExceptionTable(const Function* F,
175                                           uintptr_t &ActualSize)
176 {
177         return alloc_cb (wrap (F), ActualSize);
178 }
179   
180 void
181 MonoJITMemoryManager::endExceptionTable(const Function *F, unsigned char *TableStart,
182                                         unsigned char *TableEnd, 
183                                         unsigned char* FrameRegister)
184 {
185 }
186
187 static MonoJITMemoryManager *mono_mm;
188
189 static FunctionPassManager *fpm;
190
191 static LLVMContext ctx;
192
193 void
194 mono_llvm_optimize_method (LLVMValueRef method)
195 {
196         verifyFunction (*(unwrap<Function> (method)));
197         fpm->run (*unwrap<Function> (method));
198 }
199
200 void
201 mono_llvm_dump_value (LLVMValueRef value)
202 {
203         /* Same as LLVMDumpValue (), but print to stdout */
204         outs () << (*unwrap<Value> (value));
205 }
206
207 /* Missing overload for building an alloca with an alignment */
208 LLVMValueRef
209 mono_llvm_build_alloca (LLVMBuilderRef builder, LLVMTypeRef Ty, 
210                                                 LLVMValueRef ArraySize,
211                                                 int alignment, const char *Name)
212 {
213         return wrap (unwrap (builder)->Insert (new AllocaInst (unwrap (Ty), unwrap (ArraySize), alignment), Name));
214 }
215
216 LLVMValueRef 
217 mono_llvm_build_volatile_load (LLVMBuilderRef builder, LLVMValueRef PointerVal,
218                                                            const char *Name)
219 {
220         return wrap(unwrap(builder)->CreateLoad(unwrap(PointerVal), true, Name));
221 }
222
223 static cl::list<const PassInfo*, bool, PassNameParser>
224 PassList(cl::desc("Optimizations available:"));
225
226 LLVMExecutionEngineRef
227 mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb)
228 {
229   std::string Error;
230
231   LLVMInitializeX86Target ();
232   LLVMInitializeX86TargetInfo ();
233
234   llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "", false);
235
236   mono_mm = new MonoJITMemoryManager ();
237   mono_mm->alloc_cb = alloc_cb;
238   mono_mm->emitted_cb = emitted_cb;
239
240   DwarfExceptionHandling = true;
241   // PrettyStackTrace installs signal handlers which trip up libgc
242   DisablePrettyStackTrace = true;
243
244   ExecutionEngine *EE = ExecutionEngine::createJIT (unwrap (MP), &Error, mono_mm, CodeGenOpt::Default);
245   if (!EE) {
246           errs () << "Unable to create LLVM ExecutionEngine: " << Error << "\n";
247           g_assert_not_reached ();
248   }
249   EE->InstallExceptionTableRegister (exception_cb);
250
251   fpm = new FunctionPassManager (unwrap (MP));
252
253   fpm->add(new TargetData(*EE->getTargetData()));
254   /* Add a random set of passes */
255   /* Make this run-time configurable */
256   fpm->add(createInstructionCombiningPass());
257   fpm->add(createReassociatePass());
258   fpm->add(createGVNPass());
259   fpm->add(createCFGSimplificationPass());
260
261   /* Add passes specified by the env variable */
262   /* FIXME: This can only add passes which are linked in, thus are already used */
263   for (unsigned i = 0; i < PassList.size(); ++i) {
264       const PassInfo *PassInf = PassList[i];
265       Pass *P = 0;
266
267       if (PassInf->getNormalCtor())
268                   P = PassInf->getNormalCtor()();
269           if (dynamic_cast<MachineFunctionPass*>(P) != 0) {
270                   errs () << PassInf->getPassName () << " is a machine function pass.\n";
271           } else {
272                   fpm->add (P);
273           }
274   }
275
276   return wrap(EE);
277 }
278
279 void
280 mono_llvm_dispose_ee (LLVMExecutionEngineRef ee)
281 {
282         delete unwrap (ee);
283
284         delete fpm;
285 }