LLVM API Documentation

ExecutionEngineBindings.cpp
Go to the documentation of this file.
00001 //===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the C bindings for the ExecutionEngine library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm-c/ExecutionEngine.h"
00015 #include "llvm/ExecutionEngine/ExecutionEngine.h"
00016 #include "llvm/ExecutionEngine/GenericValue.h"
00017 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
00018 #include "llvm/IR/DerivedTypes.h"
00019 #include "llvm/IR/Module.h"
00020 #include "llvm/Support/ErrorHandling.h"
00021 #include <cstring>
00022 
00023 using namespace llvm;
00024 
00025 #define DEBUG_TYPE "jit"
00026 
00027 // Wrapping the C bindings types.
00028 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
00029 
00030 inline DataLayout *unwrap(LLVMTargetDataRef P) {
00031   return reinterpret_cast<DataLayout*>(P);
00032 }
00033   
00034 inline LLVMTargetDataRef wrap(const DataLayout *P) {
00035   return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout*>(P));
00036 }
00037 
00038 inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
00039   return reinterpret_cast<TargetLibraryInfo*>(P);
00040 }
00041 
00042 inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
00043   TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
00044   return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
00045 }
00046 
00047 inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
00048   return
00049   reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
00050 }
00051 
00052 /*===-- Operations on generic values --------------------------------------===*/
00053 
00054 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
00055                                                 unsigned long long N,
00056                                                 LLVMBool IsSigned) {
00057   GenericValue *GenVal = new GenericValue();
00058   GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
00059   return wrap(GenVal);
00060 }
00061 
00062 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
00063   GenericValue *GenVal = new GenericValue();
00064   GenVal->PointerVal = P;
00065   return wrap(GenVal);
00066 }
00067 
00068 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
00069   GenericValue *GenVal = new GenericValue();
00070   switch (unwrap(TyRef)->getTypeID()) {
00071   case Type::FloatTyID:
00072     GenVal->FloatVal = N;
00073     break;
00074   case Type::DoubleTyID:
00075     GenVal->DoubleVal = N;
00076     break;
00077   default:
00078     llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
00079   }
00080   return wrap(GenVal);
00081 }
00082 
00083 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
00084   return unwrap(GenValRef)->IntVal.getBitWidth();
00085 }
00086 
00087 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
00088                                          LLVMBool IsSigned) {
00089   GenericValue *GenVal = unwrap(GenValRef);
00090   if (IsSigned)
00091     return GenVal->IntVal.getSExtValue();
00092   else
00093     return GenVal->IntVal.getZExtValue();
00094 }
00095 
00096 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
00097   return unwrap(GenVal)->PointerVal;
00098 }
00099 
00100 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
00101   switch (unwrap(TyRef)->getTypeID()) {
00102   case Type::FloatTyID:
00103     return unwrap(GenVal)->FloatVal;
00104   case Type::DoubleTyID:
00105     return unwrap(GenVal)->DoubleVal;
00106   default:
00107     llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
00108   }
00109 }
00110 
00111 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
00112   delete unwrap(GenVal);
00113 }
00114 
00115 /*===-- Operations on execution engines -----------------------------------===*/
00116 
00117 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
00118                                             LLVMModuleRef M,
00119                                             char **OutError) {
00120   std::string Error;
00121   EngineBuilder builder(unwrap(M));
00122   builder.setEngineKind(EngineKind::Either)
00123          .setErrorStr(&Error);
00124   if (ExecutionEngine *EE = builder.create()){
00125     *OutEE = wrap(EE);
00126     return 0;
00127   }
00128   *OutError = strdup(Error.c_str());
00129   return 1;
00130 }
00131 
00132 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
00133                                         LLVMModuleRef M,
00134                                         char **OutError) {
00135   std::string Error;
00136   EngineBuilder builder(unwrap(M));
00137   builder.setEngineKind(EngineKind::Interpreter)
00138          .setErrorStr(&Error);
00139   if (ExecutionEngine *Interp = builder.create()) {
00140     *OutInterp = wrap(Interp);
00141     return 0;
00142   }
00143   *OutError = strdup(Error.c_str());
00144   return 1;
00145 }
00146 
00147 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
00148                                         LLVMModuleRef M,
00149                                         unsigned OptLevel,
00150                                         char **OutError) {
00151   std::string Error;
00152   EngineBuilder builder(unwrap(M));
00153   builder.setEngineKind(EngineKind::JIT)
00154          .setErrorStr(&Error)
00155          .setOptLevel((CodeGenOpt::Level)OptLevel);
00156   if (ExecutionEngine *JIT = builder.create()) {
00157     *OutJIT = wrap(JIT);
00158     return 0;
00159   }
00160   *OutError = strdup(Error.c_str());
00161   return 1;
00162 }
00163 
00164 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
00165                                         size_t SizeOfPassedOptions) {
00166   LLVMMCJITCompilerOptions options;
00167   memset(&options, 0, sizeof(options)); // Most fields are zero by default.
00168   options.CodeModel = LLVMCodeModelJITDefault;
00169   
00170   memcpy(PassedOptions, &options,
00171          std::min(sizeof(options), SizeOfPassedOptions));
00172 }
00173 
00174 LLVMBool LLVMCreateMCJITCompilerForModule(
00175     LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
00176     LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
00177     char **OutError) {
00178   LLVMMCJITCompilerOptions options;
00179   // If the user passed a larger sized options struct, then they were compiled
00180   // against a newer LLVM. Tell them that something is wrong.
00181   if (SizeOfPassedOptions > sizeof(options)) {
00182     *OutError = strdup(
00183       "Refusing to use options struct that is larger than my own; assuming "
00184       "LLVM library mismatch.");
00185     return 1;
00186   }
00187   
00188   // Defend against the user having an old version of the API by ensuring that
00189   // any fields they didn't see are cleared. We must defend against fields being
00190   // set to the bitwise equivalent of zero, and assume that this means "do the
00191   // default" as if that option hadn't been available.
00192   LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
00193   memcpy(&options, PassedOptions, SizeOfPassedOptions);
00194   
00195   TargetOptions targetOptions;
00196   targetOptions.NoFramePointerElim = options.NoFramePointerElim;
00197   targetOptions.EnableFastISel = options.EnableFastISel;
00198 
00199   std::string Error;
00200   EngineBuilder builder(unwrap(M));
00201   builder.setEngineKind(EngineKind::JIT)
00202          .setErrorStr(&Error)
00203          .setUseMCJIT(true)
00204          .setOptLevel((CodeGenOpt::Level)options.OptLevel)
00205          .setCodeModel(unwrap(options.CodeModel))
00206          .setTargetOptions(targetOptions);
00207   if (options.MCJMM)
00208     builder.setMCJITMemoryManager(unwrap(options.MCJMM));
00209   if (ExecutionEngine *JIT = builder.create()) {
00210     *OutJIT = wrap(JIT);
00211     return 0;
00212   }
00213   *OutError = strdup(Error.c_str());
00214   return 1;
00215 }
00216 
00217 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
00218                                    LLVMModuleProviderRef MP,
00219                                    char **OutError) {
00220   /* The module provider is now actually a module. */
00221   return LLVMCreateExecutionEngineForModule(OutEE,
00222                                             reinterpret_cast<LLVMModuleRef>(MP),
00223                                             OutError);
00224 }
00225 
00226 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
00227                                LLVMModuleProviderRef MP,
00228                                char **OutError) {
00229   /* The module provider is now actually a module. */
00230   return LLVMCreateInterpreterForModule(OutInterp,
00231                                         reinterpret_cast<LLVMModuleRef>(MP),
00232                                         OutError);
00233 }
00234 
00235 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
00236                                LLVMModuleProviderRef MP,
00237                                unsigned OptLevel,
00238                                char **OutError) {
00239   /* The module provider is now actually a module. */
00240   return LLVMCreateJITCompilerForModule(OutJIT,
00241                                         reinterpret_cast<LLVMModuleRef>(MP),
00242                                         OptLevel, OutError);
00243 }
00244 
00245 
00246 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
00247   delete unwrap(EE);
00248 }
00249 
00250 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
00251   unwrap(EE)->runStaticConstructorsDestructors(false);
00252 }
00253 
00254 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
00255   unwrap(EE)->runStaticConstructorsDestructors(true);
00256 }
00257 
00258 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
00259                           unsigned ArgC, const char * const *ArgV,
00260                           const char * const *EnvP) {
00261   unwrap(EE)->finalizeObject();
00262   
00263   std::vector<std::string> ArgVec;
00264   for (unsigned I = 0; I != ArgC; ++I)
00265     ArgVec.push_back(ArgV[I]);
00266   
00267   return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
00268 }
00269 
00270 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
00271                                     unsigned NumArgs,
00272                                     LLVMGenericValueRef *Args) {
00273   unwrap(EE)->finalizeObject();
00274   
00275   std::vector<GenericValue> ArgVec;
00276   ArgVec.reserve(NumArgs);
00277   for (unsigned I = 0; I != NumArgs; ++I)
00278     ArgVec.push_back(*unwrap(Args[I]));
00279   
00280   GenericValue *Result = new GenericValue();
00281   *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
00282   return wrap(Result);
00283 }
00284 
00285 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
00286   unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
00287 }
00288 
00289 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
00290   unwrap(EE)->addModule(unwrap(M));
00291 }
00292 
00293 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
00294   /* The module provider is now actually a module. */
00295   LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
00296 }
00297 
00298 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
00299                           LLVMModuleRef *OutMod, char **OutError) {
00300   Module *Mod = unwrap(M);
00301   unwrap(EE)->removeModule(Mod);
00302   *OutMod = wrap(Mod);
00303   return 0;
00304 }
00305 
00306 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
00307                                   LLVMModuleProviderRef MP,
00308                                   LLVMModuleRef *OutMod, char **OutError) {
00309   /* The module provider is now actually a module. */
00310   return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
00311                           OutError);
00312 }
00313 
00314 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
00315                           LLVMValueRef *OutFn) {
00316   if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
00317     *OutFn = wrap(F);
00318     return 0;
00319   }
00320   return 1;
00321 }
00322 
00323 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
00324                                      LLVMValueRef Fn) {
00325   return unwrap(EE)->recompileAndRelinkFunction(unwrap<Function>(Fn));
00326 }
00327 
00328 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
00329   return wrap(unwrap(EE)->getDataLayout());
00330 }
00331 
00332 LLVMTargetMachineRef
00333 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
00334   return wrap(unwrap(EE)->getTargetMachine());
00335 }
00336 
00337 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
00338                           void* Addr) {
00339   unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
00340 }
00341 
00342 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
00343   unwrap(EE)->finalizeObject();
00344   
00345   return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
00346 }
00347 
00348 /*===-- Operations on memory managers -------------------------------------===*/
00349 
00350 namespace {
00351 
00352 struct SimpleBindingMMFunctions {
00353   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
00354   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
00355   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
00356   LLVMMemoryManagerDestroyCallback Destroy;
00357 };
00358 
00359 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
00360 public:
00361   SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
00362                              void *Opaque);
00363   virtual ~SimpleBindingMemoryManager();
00364 
00365   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
00366                                unsigned SectionID,
00367                                StringRef SectionName) override;
00368 
00369   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
00370                                unsigned SectionID, StringRef SectionName,
00371                                bool isReadOnly) override;
00372 
00373   bool finalizeMemory(std::string *ErrMsg) override;
00374 
00375 private:
00376   SimpleBindingMMFunctions Functions;
00377   void *Opaque;
00378 };
00379 
00380 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
00381   const SimpleBindingMMFunctions& Functions,
00382   void *Opaque)
00383   : Functions(Functions), Opaque(Opaque) {
00384   assert(Functions.AllocateCodeSection &&
00385          "No AllocateCodeSection function provided!");
00386   assert(Functions.AllocateDataSection &&
00387          "No AllocateDataSection function provided!");
00388   assert(Functions.FinalizeMemory &&
00389          "No FinalizeMemory function provided!");
00390   assert(Functions.Destroy &&
00391          "No Destroy function provided!");
00392 }
00393 
00394 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
00395   Functions.Destroy(Opaque);
00396 }
00397 
00398 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
00399   uintptr_t Size, unsigned Alignment, unsigned SectionID,
00400   StringRef SectionName) {
00401   return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
00402                                        SectionName.str().c_str());
00403 }
00404 
00405 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
00406   uintptr_t Size, unsigned Alignment, unsigned SectionID,
00407   StringRef SectionName, bool isReadOnly) {
00408   return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
00409                                        SectionName.str().c_str(),
00410                                        isReadOnly);
00411 }
00412 
00413 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
00414   char *errMsgCString = nullptr;
00415   bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
00416   assert((result || !errMsgCString) &&
00417          "Did not expect an error message if FinalizeMemory succeeded");
00418   if (errMsgCString) {
00419     if (ErrMsg)
00420       *ErrMsg = errMsgCString;
00421     free(errMsgCString);
00422   }
00423   return result;
00424 }
00425 
00426 } // anonymous namespace
00427 
00428 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
00429   void *Opaque,
00430   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
00431   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
00432   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
00433   LLVMMemoryManagerDestroyCallback Destroy) {
00434   
00435   if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
00436       !Destroy)
00437     return nullptr;
00438   
00439   SimpleBindingMMFunctions functions;
00440   functions.AllocateCodeSection = AllocateCodeSection;
00441   functions.AllocateDataSection = AllocateDataSection;
00442   functions.FinalizeMemory = FinalizeMemory;
00443   functions.Destroy = Destroy;
00444   return wrap(new SimpleBindingMemoryManager(functions, Opaque));
00445 }
00446 
00447 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
00448   delete unwrap(MM);
00449 }
00450