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 "llvm/Target/TargetOptions.h" 22 #include <cstring> 23 24 using namespace llvm; 25 26 #define DEBUG_TYPE "jit" 27 28 // Wrapping the C bindings types. 29 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef) 30 31 32 static LLVMTargetMachineRef wrap(const TargetMachine *P) { 33 return 34 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P)); 35 } 36 37 /*===-- Operations on generic values --------------------------------------===*/ 38 39 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty, 40 unsigned long long N, 41 LLVMBool IsSigned) { 42 GenericValue *GenVal = new GenericValue(); 43 GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned); 44 return wrap(GenVal); 45 } 46 47 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) { 48 GenericValue *GenVal = new GenericValue(); 49 GenVal->PointerVal = P; 50 return wrap(GenVal); 51 } 52 53 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) { 54 GenericValue *GenVal = new GenericValue(); 55 switch (unwrap(TyRef)->getTypeID()) { 56 case Type::FloatTyID: 57 GenVal->FloatVal = N; 58 break; 59 case Type::DoubleTyID: 60 GenVal->DoubleVal = N; 61 break; 62 default: 63 llvm_unreachable("LLVMGenericValueToFloat supports only float and double."); 64 } 65 return wrap(GenVal); 66 } 67 68 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) { 69 return unwrap(GenValRef)->IntVal.getBitWidth(); 70 } 71 72 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef, 73 LLVMBool IsSigned) { 74 GenericValue *GenVal = unwrap(GenValRef); 75 if (IsSigned) 76 return GenVal->IntVal.getSExtValue(); 77 else 78 return GenVal->IntVal.getZExtValue(); 79 } 80 81 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) { 82 return unwrap(GenVal)->PointerVal; 83 } 84 85 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) { 86 switch (unwrap(TyRef)->getTypeID()) { 87 case Type::FloatTyID: 88 return unwrap(GenVal)->FloatVal; 89 case Type::DoubleTyID: 90 return unwrap(GenVal)->DoubleVal; 91 default: 92 llvm_unreachable("LLVMGenericValueToFloat supports only float and double."); 93 } 94 } 95 96 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) { 97 delete unwrap(GenVal); 98 } 99 100 /*===-- Operations on execution engines -----------------------------------===*/ 101 102 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE, 103 LLVMModuleRef M, 104 char **OutError) { 105 std::string Error; 106 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M))); 107 builder.setEngineKind(EngineKind::Either) 108 .setErrorStr(&Error); 109 if (ExecutionEngine *EE = builder.create()){ 110 *OutEE = wrap(EE); 111 return 0; 112 } 113 *OutError = strdup(Error.c_str()); 114 return 1; 115 } 116 117 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp, 118 LLVMModuleRef M, 119 char **OutError) { 120 std::string Error; 121 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M))); 122 builder.setEngineKind(EngineKind::Interpreter) 123 .setErrorStr(&Error); 124 if (ExecutionEngine *Interp = builder.create()) { 125 *OutInterp = wrap(Interp); 126 return 0; 127 } 128 *OutError = strdup(Error.c_str()); 129 return 1; 130 } 131 132 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT, 133 LLVMModuleRef M, 134 unsigned OptLevel, 135 char **OutError) { 136 std::string Error; 137 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M))); 138 builder.setEngineKind(EngineKind::JIT) 139 .setErrorStr(&Error) 140 .setOptLevel((CodeGenOpt::Level)OptLevel); 141 if (ExecutionEngine *JIT = builder.create()) { 142 *OutJIT = wrap(JIT); 143 return 0; 144 } 145 *OutError = strdup(Error.c_str()); 146 return 1; 147 } 148 149 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions, 150 size_t SizeOfPassedOptions) { 151 LLVMMCJITCompilerOptions options; 152 memset(&options, 0, sizeof(options)); // Most fields are zero by default. 153 options.CodeModel = LLVMCodeModelJITDefault; 154 155 memcpy(PassedOptions, &options, 156 std::min(sizeof(options), SizeOfPassedOptions)); 157 } 158 159 LLVMBool LLVMCreateMCJITCompilerForModule( 160 LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M, 161 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions, 162 char **OutError) { 163 LLVMMCJITCompilerOptions options; 164 // If the user passed a larger sized options struct, then they were compiled 165 // against a newer LLVM. Tell them that something is wrong. 166 if (SizeOfPassedOptions > sizeof(options)) { 167 *OutError = strdup( 168 "Refusing to use options struct that is larger than my own; assuming " 169 "LLVM library mismatch."); 170 return 1; 171 } 172 173 // Defend against the user having an old version of the API by ensuring that 174 // any fields they didn't see are cleared. We must defend against fields being 175 // set to the bitwise equivalent of zero, and assume that this means "do the 176 // default" as if that option hadn't been available. 177 LLVMInitializeMCJITCompilerOptions(&options, sizeof(options)); 178 memcpy(&options, PassedOptions, SizeOfPassedOptions); 179 180 TargetOptions targetOptions; 181 targetOptions.EnableFastISel = options.EnableFastISel; 182 std::unique_ptr<Module> Mod(unwrap(M)); 183 184 if (Mod) 185 // Set function attribute "no-frame-pointer-elim" based on 186 // NoFramePointerElim. 187 for (auto &F : *Mod) { 188 auto Attrs = F.getAttributes(); 189 auto Value = options.NoFramePointerElim ? "true" : "false"; 190 Attrs = Attrs.addAttribute(F.getContext(), AttributeSet::FunctionIndex, 191 "no-frame-pointer-elim", Value); 192 F.setAttributes(Attrs); 193 } 194 195 std::string Error; 196 EngineBuilder builder(std::move(Mod)); 197 builder.setEngineKind(EngineKind::JIT) 198 .setErrorStr(&Error) 199 .setOptLevel((CodeGenOpt::Level)options.OptLevel) 200 .setCodeModel(unwrap(options.CodeModel)) 201 .setTargetOptions(targetOptions); 202 if (options.MCJMM) 203 builder.setMCJITMemoryManager( 204 std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM))); 205 if (ExecutionEngine *JIT = builder.create()) { 206 *OutJIT = wrap(JIT); 207 return 0; 208 } 209 *OutError = strdup(Error.c_str()); 210 return 1; 211 } 212 213 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE, 214 LLVMModuleProviderRef MP, 215 char **OutError) { 216 /* The module provider is now actually a module. */ 217 return LLVMCreateExecutionEngineForModule(OutEE, 218 reinterpret_cast<LLVMModuleRef>(MP), 219 OutError); 220 } 221 222 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp, 223 LLVMModuleProviderRef MP, 224 char **OutError) { 225 /* The module provider is now actually a module. */ 226 return LLVMCreateInterpreterForModule(OutInterp, 227 reinterpret_cast<LLVMModuleRef>(MP), 228 OutError); 229 } 230 231 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT, 232 LLVMModuleProviderRef MP, 233 unsigned OptLevel, 234 char **OutError) { 235 /* The module provider is now actually a module. */ 236 return LLVMCreateJITCompilerForModule(OutJIT, 237 reinterpret_cast<LLVMModuleRef>(MP), 238 OptLevel, OutError); 239 } 240 241 242 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) { 243 delete unwrap(EE); 244 } 245 246 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) { 247 unwrap(EE)->runStaticConstructorsDestructors(false); 248 } 249 250 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) { 251 unwrap(EE)->runStaticConstructorsDestructors(true); 252 } 253 254 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F, 255 unsigned ArgC, const char * const *ArgV, 256 const char * const *EnvP) { 257 unwrap(EE)->finalizeObject(); 258 259 std::vector<std::string> ArgVec(ArgV, ArgV + ArgC); 260 return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP); 261 } 262 263 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F, 264 unsigned NumArgs, 265 LLVMGenericValueRef *Args) { 266 unwrap(EE)->finalizeObject(); 267 268 std::vector<GenericValue> ArgVec; 269 ArgVec.reserve(NumArgs); 270 for (unsigned I = 0; I != NumArgs; ++I) 271 ArgVec.push_back(*unwrap(Args[I])); 272 273 GenericValue *Result = new GenericValue(); 274 *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec); 275 return wrap(Result); 276 } 277 278 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) { 279 } 280 281 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){ 282 unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M))); 283 } 284 285 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){ 286 /* The module provider is now actually a module. */ 287 LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP)); 288 } 289 290 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M, 291 LLVMModuleRef *OutMod, char **OutError) { 292 Module *Mod = unwrap(M); 293 unwrap(EE)->removeModule(Mod); 294 *OutMod = wrap(Mod); 295 return 0; 296 } 297 298 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE, 299 LLVMModuleProviderRef MP, 300 LLVMModuleRef *OutMod, char **OutError) { 301 /* The module provider is now actually a module. */ 302 return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod, 303 OutError); 304 } 305 306 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name, 307 LLVMValueRef *OutFn) { 308 if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) { 309 *OutFn = wrap(F); 310 return 0; 311 } 312 return 1; 313 } 314 315 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE, 316 LLVMValueRef Fn) { 317 return nullptr; 318 } 319 320 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) { 321 return wrap(&unwrap(EE)->getDataLayout()); 322 } 323 324 LLVMTargetMachineRef 325 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) { 326 return wrap(unwrap(EE)->getTargetMachine()); 327 } 328 329 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global, 330 void* Addr) { 331 unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr); 332 } 333 334 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) { 335 unwrap(EE)->finalizeObject(); 336 337 return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global)); 338 } 339 340 uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) { 341 return unwrap(EE)->getGlobalValueAddress(Name); 342 } 343 344 uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) { 345 return unwrap(EE)->getFunctionAddress(Name); 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 ~SimpleBindingMemoryManager() override; 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