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