LLVM  mainline
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   std::unique_ptr<Module> Mod(unwrap(M));
00183 
00184   if (Mod)
00185     // Set function attribute "no-frame-pointer-elim" based on
00186     // NoFramePointerElim.
00187     setFunctionAttributes(/* CPU */ "", /* Features */ "", targetOptions, *Mod,
00188                           /* AlwaysRecordAttrs */ true);
00189 
00190   std::string Error;
00191   EngineBuilder builder(std::move(Mod));
00192   builder.setEngineKind(EngineKind::JIT)
00193          .setErrorStr(&Error)
00194          .setOptLevel((CodeGenOpt::Level)options.OptLevel)
00195          .setCodeModel(unwrap(options.CodeModel))
00196          .setTargetOptions(targetOptions);
00197   if (options.MCJMM)
00198     builder.setMCJITMemoryManager(
00199       std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
00200   if (ExecutionEngine *JIT = builder.create()) {
00201     *OutJIT = wrap(JIT);
00202     return 0;
00203   }
00204   *OutError = strdup(Error.c_str());
00205   return 1;
00206 }
00207 
00208 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
00209                                    LLVMModuleProviderRef MP,
00210                                    char **OutError) {
00211   /* The module provider is now actually a module. */
00212   return LLVMCreateExecutionEngineForModule(OutEE,
00213                                             reinterpret_cast<LLVMModuleRef>(MP),
00214                                             OutError);
00215 }
00216 
00217 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
00218                                LLVMModuleProviderRef MP,
00219                                char **OutError) {
00220   /* The module provider is now actually a module. */
00221   return LLVMCreateInterpreterForModule(OutInterp,
00222                                         reinterpret_cast<LLVMModuleRef>(MP),
00223                                         OutError);
00224 }
00225 
00226 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
00227                                LLVMModuleProviderRef MP,
00228                                unsigned OptLevel,
00229                                char **OutError) {
00230   /* The module provider is now actually a module. */
00231   return LLVMCreateJITCompilerForModule(OutJIT,
00232                                         reinterpret_cast<LLVMModuleRef>(MP),
00233                                         OptLevel, OutError);
00234 }
00235 
00236 
00237 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
00238   delete unwrap(EE);
00239 }
00240 
00241 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
00242   unwrap(EE)->runStaticConstructorsDestructors(false);
00243 }
00244 
00245 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
00246   unwrap(EE)->runStaticConstructorsDestructors(true);
00247 }
00248 
00249 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
00250                           unsigned ArgC, const char * const *ArgV,
00251                           const char * const *EnvP) {
00252   unwrap(EE)->finalizeObject();
00253   
00254   std::vector<std::string> ArgVec;
00255   for (unsigned I = 0; I != ArgC; ++I)
00256     ArgVec.push_back(ArgV[I]);
00257   
00258   return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
00259 }
00260 
00261 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
00262                                     unsigned NumArgs,
00263                                     LLVMGenericValueRef *Args) {
00264   unwrap(EE)->finalizeObject();
00265   
00266   std::vector<GenericValue> ArgVec;
00267   ArgVec.reserve(NumArgs);
00268   for (unsigned I = 0; I != NumArgs; ++I)
00269     ArgVec.push_back(*unwrap(Args[I]));
00270   
00271   GenericValue *Result = new GenericValue();
00272   *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
00273   return wrap(Result);
00274 }
00275 
00276 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
00277 }
00278 
00279 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
00280   unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
00281 }
00282 
00283 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
00284   /* The module provider is now actually a module. */
00285   LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
00286 }
00287 
00288 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
00289                           LLVMModuleRef *OutMod, char **OutError) {
00290   Module *Mod = unwrap(M);
00291   unwrap(EE)->removeModule(Mod);
00292   *OutMod = wrap(Mod);
00293   return 0;
00294 }
00295 
00296 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
00297                                   LLVMModuleProviderRef MP,
00298                                   LLVMModuleRef *OutMod, char **OutError) {
00299   /* The module provider is now actually a module. */
00300   return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
00301                           OutError);
00302 }
00303 
00304 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
00305                           LLVMValueRef *OutFn) {
00306   if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
00307     *OutFn = wrap(F);
00308     return 0;
00309   }
00310   return 1;
00311 }
00312 
00313 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
00314                                      LLVMValueRef Fn) {
00315   return nullptr;
00316 }
00317 
00318 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
00319   return wrap(unwrap(EE)->getDataLayout());
00320 }
00321 
00322 LLVMTargetMachineRef
00323 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
00324   return wrap(unwrap(EE)->getTargetMachine());
00325 }
00326 
00327 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
00328                           void* Addr) {
00329   unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
00330 }
00331 
00332 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
00333   unwrap(EE)->finalizeObject();
00334   
00335   return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
00336 }
00337 
00338 uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) {
00339   return unwrap(EE)->getGlobalValueAddress(Name);
00340 }
00341 
00342 uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) {
00343   return unwrap(EE)->getFunctionAddress(Name);
00344 }
00345 
00346 /*===-- Operations on memory managers -------------------------------------===*/
00347 
00348 namespace {
00349 
00350 struct SimpleBindingMMFunctions {
00351   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
00352   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
00353   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
00354   LLVMMemoryManagerDestroyCallback Destroy;
00355 };
00356 
00357 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
00358 public:
00359   SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
00360                              void *Opaque);
00361   ~SimpleBindingMemoryManager() override;
00362 
00363   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
00364                                unsigned SectionID,
00365                                StringRef SectionName) override;
00366 
00367   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
00368                                unsigned SectionID, StringRef SectionName,
00369                                bool isReadOnly) override;
00370 
00371   bool finalizeMemory(std::string *ErrMsg) override;
00372 
00373 private:
00374   SimpleBindingMMFunctions Functions;
00375   void *Opaque;
00376 };
00377 
00378 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
00379   const SimpleBindingMMFunctions& Functions,
00380   void *Opaque)
00381   : Functions(Functions), Opaque(Opaque) {
00382   assert(Functions.AllocateCodeSection &&
00383          "No AllocateCodeSection function provided!");
00384   assert(Functions.AllocateDataSection &&
00385          "No AllocateDataSection function provided!");
00386   assert(Functions.FinalizeMemory &&
00387          "No FinalizeMemory function provided!");
00388   assert(Functions.Destroy &&
00389          "No Destroy function provided!");
00390 }
00391 
00392 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
00393   Functions.Destroy(Opaque);
00394 }
00395 
00396 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
00397   uintptr_t Size, unsigned Alignment, unsigned SectionID,
00398   StringRef SectionName) {
00399   return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
00400                                        SectionName.str().c_str());
00401 }
00402 
00403 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
00404   uintptr_t Size, unsigned Alignment, unsigned SectionID,
00405   StringRef SectionName, bool isReadOnly) {
00406   return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
00407                                        SectionName.str().c_str(),
00408                                        isReadOnly);
00409 }
00410 
00411 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
00412   char *errMsgCString = nullptr;
00413   bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
00414   assert((result || !errMsgCString) &&
00415          "Did not expect an error message if FinalizeMemory succeeded");
00416   if (errMsgCString) {
00417     if (ErrMsg)
00418       *ErrMsg = errMsgCString;
00419     free(errMsgCString);
00420   }
00421   return result;
00422 }
00423 
00424 } // anonymous namespace
00425 
00426 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
00427   void *Opaque,
00428   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
00429   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
00430   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
00431   LLVMMemoryManagerDestroyCallback Destroy) {
00432   
00433   if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
00434       !Destroy)
00435     return nullptr;
00436   
00437   SimpleBindingMMFunctions functions;
00438   functions.AllocateCodeSection = AllocateCodeSection;
00439   functions.AllocateDataSection = AllocateDataSection;
00440   functions.FinalizeMemory = FinalizeMemory;
00441   functions.Destroy = Destroy;
00442   return wrap(new SimpleBindingMemoryManager(functions, Opaque));
00443 }
00444 
00445 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
00446   delete unwrap(MM);
00447 }
00448