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