1 //===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the C bindings for the ExecutionEngine library.
12 //===----------------------------------------------------------------------===//
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"
25 #define DEBUG_TYPE "jit"
27 // Wrapping the C bindings types.
28 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
30 inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
31 return reinterpret_cast<TargetLibraryInfo*>(P);
34 inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
35 TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
36 return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
39 inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
41 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
44 /*===-- Operations on generic values --------------------------------------===*/
46 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
49 GenericValue *GenVal = new GenericValue();
50 GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
54 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
55 GenericValue *GenVal = new GenericValue();
56 GenVal->PointerVal = P;
60 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
61 GenericValue *GenVal = new GenericValue();
62 switch (unwrap(TyRef)->getTypeID()) {
66 case Type::DoubleTyID:
67 GenVal->DoubleVal = N;
70 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
75 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
76 return unwrap(GenValRef)->IntVal.getBitWidth();
79 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
81 GenericValue *GenVal = unwrap(GenValRef);
83 return GenVal->IntVal.getSExtValue();
85 return GenVal->IntVal.getZExtValue();
88 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
89 return unwrap(GenVal)->PointerVal;
92 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
93 switch (unwrap(TyRef)->getTypeID()) {
95 return unwrap(GenVal)->FloatVal;
96 case Type::DoubleTyID:
97 return unwrap(GenVal)->DoubleVal;
99 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
103 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
104 delete unwrap(GenVal);
107 /*===-- Operations on execution engines -----------------------------------===*/
109 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
113 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
114 builder.setEngineKind(EngineKind::Either)
115 .setErrorStr(&Error);
116 if (ExecutionEngine *EE = builder.create()){
120 *OutError = strdup(Error.c_str());
124 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
128 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
129 builder.setEngineKind(EngineKind::Interpreter)
130 .setErrorStr(&Error);
131 if (ExecutionEngine *Interp = builder.create()) {
132 *OutInterp = wrap(Interp);
135 *OutError = strdup(Error.c_str());
139 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
144 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
145 builder.setEngineKind(EngineKind::JIT)
147 .setOptLevel((CodeGenOpt::Level)OptLevel);
148 if (ExecutionEngine *JIT = builder.create()) {
152 *OutError = strdup(Error.c_str());
156 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
157 size_t SizeOfPassedOptions) {
158 LLVMMCJITCompilerOptions options;
159 memset(&options, 0, sizeof(options)); // Most fields are zero by default.
160 options.CodeModel = LLVMCodeModelJITDefault;
162 memcpy(PassedOptions, &options,
163 std::min(sizeof(options), SizeOfPassedOptions));
166 LLVMBool LLVMCreateMCJITCompilerForModule(
167 LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
168 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
170 LLVMMCJITCompilerOptions options;
171 // If the user passed a larger sized options struct, then they were compiled
172 // against a newer LLVM. Tell them that something is wrong.
173 if (SizeOfPassedOptions > sizeof(options)) {
175 "Refusing to use options struct that is larger than my own; assuming "
176 "LLVM library mismatch.");
180 // Defend against the user having an old version of the API by ensuring that
181 // any fields they didn't see are cleared. We must defend against fields being
182 // set to the bitwise equivalent of zero, and assume that this means "do the
183 // default" as if that option hadn't been available.
184 LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
185 memcpy(&options, PassedOptions, SizeOfPassedOptions);
187 TargetOptions targetOptions;
188 targetOptions.NoFramePointerElim = options.NoFramePointerElim;
189 targetOptions.EnableFastISel = options.EnableFastISel;
192 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
193 builder.setEngineKind(EngineKind::JIT)
196 .setOptLevel((CodeGenOpt::Level)options.OptLevel)
197 .setCodeModel(unwrap(options.CodeModel))
198 .setTargetOptions(targetOptions);
200 builder.setMCJITMemoryManager(unwrap(options.MCJMM));
201 if (ExecutionEngine *JIT = builder.create()) {
205 *OutError = strdup(Error.c_str());
209 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
210 LLVMModuleProviderRef MP,
212 /* The module provider is now actually a module. */
213 return LLVMCreateExecutionEngineForModule(OutEE,
214 reinterpret_cast<LLVMModuleRef>(MP),
218 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
219 LLVMModuleProviderRef MP,
221 /* The module provider is now actually a module. */
222 return LLVMCreateInterpreterForModule(OutInterp,
223 reinterpret_cast<LLVMModuleRef>(MP),
227 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
228 LLVMModuleProviderRef MP,
231 /* The module provider is now actually a module. */
232 return LLVMCreateJITCompilerForModule(OutJIT,
233 reinterpret_cast<LLVMModuleRef>(MP),
238 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
242 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
243 unwrap(EE)->runStaticConstructorsDestructors(false);
246 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
247 unwrap(EE)->runStaticConstructorsDestructors(true);
250 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
251 unsigned ArgC, const char * const *ArgV,
252 const char * const *EnvP) {
253 unwrap(EE)->finalizeObject();
255 std::vector<std::string> ArgVec;
256 for (unsigned I = 0; I != ArgC; ++I)
257 ArgVec.push_back(ArgV[I]);
259 return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
262 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
264 LLVMGenericValueRef *Args) {
265 unwrap(EE)->finalizeObject();
267 std::vector<GenericValue> ArgVec;
268 ArgVec.reserve(NumArgs);
269 for (unsigned I = 0; I != NumArgs; ++I)
270 ArgVec.push_back(*unwrap(Args[I]));
272 GenericValue *Result = new GenericValue();
273 *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
277 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
278 unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
281 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
282 unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
285 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
286 /* The module provider is now actually a module. */
287 LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
290 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
291 LLVMModuleRef *OutMod, char **OutError) {
292 Module *Mod = unwrap(M);
293 unwrap(EE)->removeModule(Mod);
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,
306 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
307 LLVMValueRef *OutFn) {
308 if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
315 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
317 return unwrap(EE)->recompileAndRelinkFunction(unwrap<Function>(Fn));
320 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
321 return wrap(unwrap(EE)->getDataLayout());
325 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
326 return wrap(unwrap(EE)->getTargetMachine());
329 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
331 unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
334 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
335 unwrap(EE)->finalizeObject();
337 return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
340 /*===-- Operations on memory managers -------------------------------------===*/
344 struct SimpleBindingMMFunctions {
345 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
346 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
347 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
348 LLVMMemoryManagerDestroyCallback Destroy;
351 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
353 SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
355 virtual ~SimpleBindingMemoryManager();
357 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
359 StringRef SectionName) override;
361 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
362 unsigned SectionID, StringRef SectionName,
363 bool isReadOnly) override;
365 bool finalizeMemory(std::string *ErrMsg) override;
368 SimpleBindingMMFunctions Functions;
372 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
373 const SimpleBindingMMFunctions& Functions,
375 : Functions(Functions), Opaque(Opaque) {
376 assert(Functions.AllocateCodeSection &&
377 "No AllocateCodeSection function provided!");
378 assert(Functions.AllocateDataSection &&
379 "No AllocateDataSection function provided!");
380 assert(Functions.FinalizeMemory &&
381 "No FinalizeMemory function provided!");
382 assert(Functions.Destroy &&
383 "No Destroy function provided!");
386 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
387 Functions.Destroy(Opaque);
390 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
391 uintptr_t Size, unsigned Alignment, unsigned SectionID,
392 StringRef SectionName) {
393 return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
394 SectionName.str().c_str());
397 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
398 uintptr_t Size, unsigned Alignment, unsigned SectionID,
399 StringRef SectionName, bool isReadOnly) {
400 return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
401 SectionName.str().c_str(),
405 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
406 char *errMsgCString = nullptr;
407 bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
408 assert((result || !errMsgCString) &&
409 "Did not expect an error message if FinalizeMemory succeeded");
412 *ErrMsg = errMsgCString;
418 } // anonymous namespace
420 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
422 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
423 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
424 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
425 LLVMMemoryManagerDestroyCallback Destroy) {
427 if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
431 SimpleBindingMMFunctions functions;
432 functions.AllocateCodeSection = AllocateCodeSection;
433 functions.AllocateDataSection = AllocateDataSection;
434 functions.FinalizeMemory = FinalizeMemory;
435 functions.Destroy = Destroy;
436 return wrap(new SimpleBindingMemoryManager(functions, Opaque));
439 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {