Add target analysis passes to the codegen pipeline for MCJIT.
[oota-llvm.git] / lib / ExecutionEngine / ExecutionEngineBindings.cpp
1 //===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the C bindings for the ExecutionEngine library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "jit"
15 #include "llvm-c/ExecutionEngine.h"
16 #include "llvm/ExecutionEngine/ExecutionEngine.h"
17 #include "llvm/ExecutionEngine/GenericValue.h"
18 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include <cstring>
23
24 using namespace llvm;
25
26 // Wrapping the C bindings types.
27 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
28
29 inline DataLayout *unwrap(LLVMTargetDataRef P) {
30   return reinterpret_cast<DataLayout*>(P);
31 }
32   
33 inline LLVMTargetDataRef wrap(const DataLayout *P) {
34   return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout*>(P));
35 }
36
37 inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
38   return reinterpret_cast<TargetLibraryInfo*>(P);
39 }
40
41 inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
42   TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
43   return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
44 }
45
46 inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
47   return
48   reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
49 }
50
51 /*===-- Operations on generic values --------------------------------------===*/
52
53 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
54                                                 unsigned long long N,
55                                                 LLVMBool IsSigned) {
56   GenericValue *GenVal = new GenericValue();
57   GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
58   return wrap(GenVal);
59 }
60
61 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
62   GenericValue *GenVal = new GenericValue();
63   GenVal->PointerVal = P;
64   return wrap(GenVal);
65 }
66
67 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
68   GenericValue *GenVal = new GenericValue();
69   switch (unwrap(TyRef)->getTypeID()) {
70   case Type::FloatTyID:
71     GenVal->FloatVal = N;
72     break;
73   case Type::DoubleTyID:
74     GenVal->DoubleVal = N;
75     break;
76   default:
77     llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
78   }
79   return wrap(GenVal);
80 }
81
82 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
83   return unwrap(GenValRef)->IntVal.getBitWidth();
84 }
85
86 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
87                                          LLVMBool IsSigned) {
88   GenericValue *GenVal = unwrap(GenValRef);
89   if (IsSigned)
90     return GenVal->IntVal.getSExtValue();
91   else
92     return GenVal->IntVal.getZExtValue();
93 }
94
95 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
96   return unwrap(GenVal)->PointerVal;
97 }
98
99 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
100   switch (unwrap(TyRef)->getTypeID()) {
101   case Type::FloatTyID:
102     return unwrap(GenVal)->FloatVal;
103   case Type::DoubleTyID:
104     return unwrap(GenVal)->DoubleVal;
105   default:
106     llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
107   }
108 }
109
110 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
111   delete unwrap(GenVal);
112 }
113
114 /*===-- Operations on execution engines -----------------------------------===*/
115
116 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
117                                             LLVMModuleRef M,
118                                             char **OutError) {
119   std::string Error;
120   EngineBuilder builder(unwrap(M));
121   builder.setEngineKind(EngineKind::Either)
122          .setErrorStr(&Error);
123   if (ExecutionEngine *EE = builder.create()){
124     *OutEE = wrap(EE);
125     return 0;
126   }
127   *OutError = strdup(Error.c_str());
128   return 1;
129 }
130
131 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
132                                         LLVMModuleRef M,
133                                         char **OutError) {
134   std::string Error;
135   EngineBuilder builder(unwrap(M));
136   builder.setEngineKind(EngineKind::Interpreter)
137          .setErrorStr(&Error);
138   if (ExecutionEngine *Interp = builder.create()) {
139     *OutInterp = wrap(Interp);
140     return 0;
141   }
142   *OutError = strdup(Error.c_str());
143   return 1;
144 }
145
146 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
147                                         LLVMModuleRef M,
148                                         unsigned OptLevel,
149                                         char **OutError) {
150   std::string Error;
151   EngineBuilder builder(unwrap(M));
152   builder.setEngineKind(EngineKind::JIT)
153          .setErrorStr(&Error)
154          .setOptLevel((CodeGenOpt::Level)OptLevel);
155   if (ExecutionEngine *JIT = builder.create()) {
156     *OutJIT = wrap(JIT);
157     return 0;
158   }
159   *OutError = strdup(Error.c_str());
160   return 1;
161 }
162
163 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
164                                         size_t SizeOfPassedOptions) {
165   LLVMMCJITCompilerOptions options;
166   memset(&options, 0, sizeof(options)); // Most fields are zero by default.
167   options.CodeModel = LLVMCodeModelJITDefault;
168   
169   memcpy(PassedOptions, &options,
170          std::min(sizeof(options), SizeOfPassedOptions));
171 }
172
173 LLVMBool LLVMCreateMCJITCompilerForModule(
174     LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
175     LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
176     char **OutError) {
177   LLVMMCJITCompilerOptions options;
178   // If the user passed a larger sized options struct, then they were compiled
179   // against a newer LLVM. Tell them that something is wrong.
180   if (SizeOfPassedOptions > sizeof(options)) {
181     *OutError = strdup(
182       "Refusing to use options struct that is larger than my own; assuming "
183       "LLVM library mismatch.");
184     return 1;
185   }
186   
187   // Defend against the user having an old version of the API by ensuring that
188   // any fields they didn't see are cleared. We must defend against fields being
189   // set to the bitwise equivalent of zero, and assume that this means "do the
190   // default" as if that option hadn't been available.
191   LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
192   memcpy(&options, PassedOptions, SizeOfPassedOptions);
193   
194   TargetOptions targetOptions;
195   targetOptions.NoFramePointerElim = options.NoFramePointerElim;
196   targetOptions.EnableFastISel = options.EnableFastISel;
197
198   std::string Error;
199   EngineBuilder builder(unwrap(M));
200   builder.setEngineKind(EngineKind::JIT)
201          .setErrorStr(&Error)
202          .setUseMCJIT(true)
203          .setOptLevel((CodeGenOpt::Level)options.OptLevel)
204          .setCodeModel(unwrap(options.CodeModel))
205          .setTargetOptions(targetOptions);
206   if (options.MCJMM)
207     builder.setMCJITMemoryManager(unwrap(options.MCJMM));
208   if (ExecutionEngine *JIT = builder.create()) {
209     *OutJIT = wrap(JIT);
210     return 0;
211   }
212   *OutError = strdup(Error.c_str());
213   return 1;
214 }
215
216 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
217                                    LLVMModuleProviderRef MP,
218                                    char **OutError) {
219   /* The module provider is now actually a module. */
220   return LLVMCreateExecutionEngineForModule(OutEE,
221                                             reinterpret_cast<LLVMModuleRef>(MP),
222                                             OutError);
223 }
224
225 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
226                                LLVMModuleProviderRef MP,
227                                char **OutError) {
228   /* The module provider is now actually a module. */
229   return LLVMCreateInterpreterForModule(OutInterp,
230                                         reinterpret_cast<LLVMModuleRef>(MP),
231                                         OutError);
232 }
233
234 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
235                                LLVMModuleProviderRef MP,
236                                unsigned OptLevel,
237                                char **OutError) {
238   /* The module provider is now actually a module. */
239   return LLVMCreateJITCompilerForModule(OutJIT,
240                                         reinterpret_cast<LLVMModuleRef>(MP),
241                                         OptLevel, OutError);
242 }
243
244
245 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
246   delete unwrap(EE);
247 }
248
249 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
250   unwrap(EE)->runStaticConstructorsDestructors(false);
251 }
252
253 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
254   unwrap(EE)->runStaticConstructorsDestructors(true);
255 }
256
257 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
258                           unsigned ArgC, const char * const *ArgV,
259                           const char * const *EnvP) {
260   unwrap(EE)->finalizeObject();
261   
262   std::vector<std::string> ArgVec;
263   for (unsigned I = 0; I != ArgC; ++I)
264     ArgVec.push_back(ArgV[I]);
265   
266   return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
267 }
268
269 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
270                                     unsigned NumArgs,
271                                     LLVMGenericValueRef *Args) {
272   unwrap(EE)->finalizeObject();
273   
274   std::vector<GenericValue> ArgVec;
275   ArgVec.reserve(NumArgs);
276   for (unsigned I = 0; I != NumArgs; ++I)
277     ArgVec.push_back(*unwrap(Args[I]));
278   
279   GenericValue *Result = new GenericValue();
280   *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
281   return wrap(Result);
282 }
283
284 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
285   unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
286 }
287
288 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
289   unwrap(EE)->addModule(unwrap(M));
290 }
291
292 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
293   /* The module provider is now actually a module. */
294   LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
295 }
296
297 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
298                           LLVMModuleRef *OutMod, char **OutError) {
299   Module *Mod = unwrap(M);
300   unwrap(EE)->removeModule(Mod);
301   *OutMod = wrap(Mod);
302   return 0;
303 }
304
305 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
306                                   LLVMModuleProviderRef MP,
307                                   LLVMModuleRef *OutMod, char **OutError) {
308   /* The module provider is now actually a module. */
309   return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
310                           OutError);
311 }
312
313 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
314                           LLVMValueRef *OutFn) {
315   if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
316     *OutFn = wrap(F);
317     return 0;
318   }
319   return 1;
320 }
321
322 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
323                                      LLVMValueRef Fn) {
324   return unwrap(EE)->recompileAndRelinkFunction(unwrap<Function>(Fn));
325 }
326
327 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
328   return wrap(unwrap(EE)->getDataLayout());
329 }
330
331 LLVMTargetMachineRef
332 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
333   return wrap(unwrap(EE)->getTargetMachine());
334 }
335
336 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
337                           void* Addr) {
338   unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
339 }
340
341 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
342   unwrap(EE)->finalizeObject();
343   
344   return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
345 }
346
347 /*===-- Operations on memory managers -------------------------------------===*/
348
349 namespace {
350
351 struct SimpleBindingMMFunctions {
352   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
353   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
354   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
355   LLVMMemoryManagerDestroyCallback Destroy;
356 };
357
358 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
359 public:
360   SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
361                              void *Opaque);
362   virtual ~SimpleBindingMemoryManager();
363   
364   virtual uint8_t *allocateCodeSection(
365     uintptr_t Size, unsigned Alignment, unsigned SectionID,
366     StringRef SectionName);
367
368   virtual uint8_t *allocateDataSection(
369     uintptr_t Size, unsigned Alignment, unsigned SectionID,
370     StringRef SectionName, bool isReadOnly);
371
372   virtual bool finalizeMemory(std::string *ErrMsg);
373   
374 private:
375   SimpleBindingMMFunctions Functions;
376   void *Opaque;
377 };
378
379 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
380   const SimpleBindingMMFunctions& Functions,
381   void *Opaque)
382   : Functions(Functions), Opaque(Opaque) {
383   assert(Functions.AllocateCodeSection &&
384          "No AllocateCodeSection function provided!");
385   assert(Functions.AllocateDataSection &&
386          "No AllocateDataSection function provided!");
387   assert(Functions.FinalizeMemory &&
388          "No FinalizeMemory function provided!");
389   assert(Functions.Destroy &&
390          "No Destroy function provided!");
391 }
392
393 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
394   Functions.Destroy(Opaque);
395 }
396
397 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
398   uintptr_t Size, unsigned Alignment, unsigned SectionID,
399   StringRef SectionName) {
400   return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
401                                        SectionName.str().c_str());
402 }
403
404 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
405   uintptr_t Size, unsigned Alignment, unsigned SectionID,
406   StringRef SectionName, bool isReadOnly) {
407   return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
408                                        SectionName.str().c_str(),
409                                        isReadOnly);
410 }
411
412 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
413   char *errMsgCString = 0;
414   bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
415   assert((result || !errMsgCString) &&
416          "Did not expect an error message if FinalizeMemory succeeded");
417   if (errMsgCString) {
418     if (ErrMsg)
419       *ErrMsg = errMsgCString;
420     free(errMsgCString);
421   }
422   return result;
423 }
424
425 } // anonymous namespace
426
427 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
428   void *Opaque,
429   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
430   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
431   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
432   LLVMMemoryManagerDestroyCallback Destroy) {
433   
434   if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
435       !Destroy)
436     return NULL;
437   
438   SimpleBindingMMFunctions functions;
439   functions.AllocateCodeSection = AllocateCodeSection;
440   functions.AllocateDataSection = AllocateDataSection;
441   functions.FinalizeMemory = FinalizeMemory;
442   functions.Destroy = Destroy;
443   return wrap(new SimpleBindingMemoryManager(functions, Opaque));
444 }
445
446 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
447   delete unwrap(MM);
448 }
449