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 #define DEBUG_TYPE "jit"
15 #include "llvm-c/ExecutionEngine.h"
16 #include "llvm/ExecutionEngine/ExecutionEngine.h"
17 #include "llvm/ExecutionEngine/GenericValue.h"
18 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/ErrorHandling.h"
26 // Wrapping the C bindings types.
27 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
29 inline DataLayout *unwrap(LLVMTargetDataRef P) {
30 return reinterpret_cast<DataLayout*>(P);
33 inline LLVMTargetDataRef wrap(const DataLayout *P) {
34 return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout*>(P));
37 inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
38 return reinterpret_cast<TargetLibraryInfo*>(P);
41 inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
42 TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
43 return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
46 inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
48 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
51 /*===-- Operations on generic values --------------------------------------===*/
53 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
56 GenericValue *GenVal = new GenericValue();
57 GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
61 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
62 GenericValue *GenVal = new GenericValue();
63 GenVal->PointerVal = P;
67 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
68 GenericValue *GenVal = new GenericValue();
69 switch (unwrap(TyRef)->getTypeID()) {
73 case Type::DoubleTyID:
74 GenVal->DoubleVal = N;
77 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
82 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
83 return unwrap(GenValRef)->IntVal.getBitWidth();
86 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
88 GenericValue *GenVal = unwrap(GenValRef);
90 return GenVal->IntVal.getSExtValue();
92 return GenVal->IntVal.getZExtValue();
95 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
96 return unwrap(GenVal)->PointerVal;
99 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
100 switch (unwrap(TyRef)->getTypeID()) {
101 case Type::FloatTyID:
102 return unwrap(GenVal)->FloatVal;
103 case Type::DoubleTyID:
104 return unwrap(GenVal)->DoubleVal;
106 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
110 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
111 delete unwrap(GenVal);
114 /*===-- Operations on execution engines -----------------------------------===*/
116 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
120 EngineBuilder builder(unwrap(M));
121 builder.setEngineKind(EngineKind::Either)
122 .setErrorStr(&Error);
123 if (ExecutionEngine *EE = builder.create()){
127 *OutError = strdup(Error.c_str());
131 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
135 EngineBuilder builder(unwrap(M));
136 builder.setEngineKind(EngineKind::Interpreter)
137 .setErrorStr(&Error);
138 if (ExecutionEngine *Interp = builder.create()) {
139 *OutInterp = wrap(Interp);
142 *OutError = strdup(Error.c_str());
146 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
151 EngineBuilder builder(unwrap(M));
152 builder.setEngineKind(EngineKind::JIT)
154 .setOptLevel((CodeGenOpt::Level)OptLevel);
155 if (ExecutionEngine *JIT = builder.create()) {
159 *OutError = strdup(Error.c_str());
163 void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
164 size_t SizeOfPassedOptions) {
165 LLVMMCJITCompilerOptions options;
166 memset(&options, 0, sizeof(options)); // Most fields are zero by default.
167 options.CodeModel = LLVMCodeModelJITDefault;
169 memcpy(PassedOptions, &options,
170 std::min(sizeof(options), SizeOfPassedOptions));
173 LLVMBool LLVMCreateMCJITCompilerForModule(
174 LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
175 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
177 LLVMMCJITCompilerOptions options;
178 // If the user passed a larger sized options struct, then they were compiled
179 // against a newer LLVM. Tell them that something is wrong.
180 if (SizeOfPassedOptions > sizeof(options)) {
182 "Refusing to use options struct that is larger than my own; assuming "
183 "LLVM library mismatch.");
187 // Defend against the user having an old version of the API by ensuring that
188 // any fields they didn't see are cleared. We must defend against fields being
189 // set to the bitwise equivalent of zero, and assume that this means "do the
190 // default" as if that option hadn't been available.
191 LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
192 memcpy(&options, PassedOptions, SizeOfPassedOptions);
194 TargetOptions targetOptions;
195 targetOptions.NoFramePointerElim = options.NoFramePointerElim;
196 targetOptions.EnableFastISel = options.EnableFastISel;
199 EngineBuilder builder(unwrap(M));
200 builder.setEngineKind(EngineKind::JIT)
203 .setOptLevel((CodeGenOpt::Level)options.OptLevel)
204 .setCodeModel(unwrap(options.CodeModel))
205 .setTargetOptions(targetOptions);
207 builder.setMCJITMemoryManager(unwrap(options.MCJMM));
208 if (ExecutionEngine *JIT = builder.create()) {
212 *OutError = strdup(Error.c_str());
216 LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
217 LLVMModuleProviderRef MP,
219 /* The module provider is now actually a module. */
220 return LLVMCreateExecutionEngineForModule(OutEE,
221 reinterpret_cast<LLVMModuleRef>(MP),
225 LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
226 LLVMModuleProviderRef MP,
228 /* The module provider is now actually a module. */
229 return LLVMCreateInterpreterForModule(OutInterp,
230 reinterpret_cast<LLVMModuleRef>(MP),
234 LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
235 LLVMModuleProviderRef MP,
238 /* The module provider is now actually a module. */
239 return LLVMCreateJITCompilerForModule(OutJIT,
240 reinterpret_cast<LLVMModuleRef>(MP),
245 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
249 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
250 unwrap(EE)->runStaticConstructorsDestructors(false);
253 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
254 unwrap(EE)->runStaticConstructorsDestructors(true);
257 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
258 unsigned ArgC, const char * const *ArgV,
259 const char * const *EnvP) {
260 unwrap(EE)->finalizeObject();
262 std::vector<std::string> ArgVec;
263 for (unsigned I = 0; I != ArgC; ++I)
264 ArgVec.push_back(ArgV[I]);
266 return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
269 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
271 LLVMGenericValueRef *Args) {
272 unwrap(EE)->finalizeObject();
274 std::vector<GenericValue> ArgVec;
275 ArgVec.reserve(NumArgs);
276 for (unsigned I = 0; I != NumArgs; ++I)
277 ArgVec.push_back(*unwrap(Args[I]));
279 GenericValue *Result = new GenericValue();
280 *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
284 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
285 unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
288 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
289 unwrap(EE)->addModule(unwrap(M));
292 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
293 /* The module provider is now actually a module. */
294 LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
297 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
298 LLVMModuleRef *OutMod, char **OutError) {
299 Module *Mod = unwrap(M);
300 unwrap(EE)->removeModule(Mod);
305 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
306 LLVMModuleProviderRef MP,
307 LLVMModuleRef *OutMod, char **OutError) {
308 /* The module provider is now actually a module. */
309 return LLVMRemoveModule(EE, reinterpret_cast<LLVMModuleRef>(MP), OutMod,
313 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
314 LLVMValueRef *OutFn) {
315 if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
322 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
324 return unwrap(EE)->recompileAndRelinkFunction(unwrap<Function>(Fn));
327 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
328 return wrap(unwrap(EE)->getDataLayout());
332 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
333 return wrap(unwrap(EE)->getTargetMachine());
336 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
338 unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
341 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
342 unwrap(EE)->finalizeObject();
344 return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
347 /*===-- Operations on memory managers -------------------------------------===*/
351 struct SimpleBindingMMFunctions {
352 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
353 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
354 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
355 LLVMMemoryManagerDestroyCallback Destroy;
358 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
360 SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
362 virtual ~SimpleBindingMemoryManager();
364 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
366 StringRef SectionName) override;
368 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
369 unsigned SectionID, StringRef SectionName,
370 bool isReadOnly) override;
372 bool finalizeMemory(std::string *ErrMsg) override;
375 SimpleBindingMMFunctions Functions;
379 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
380 const SimpleBindingMMFunctions& Functions,
382 : Functions(Functions), Opaque(Opaque) {
383 assert(Functions.AllocateCodeSection &&
384 "No AllocateCodeSection function provided!");
385 assert(Functions.AllocateDataSection &&
386 "No AllocateDataSection function provided!");
387 assert(Functions.FinalizeMemory &&
388 "No FinalizeMemory function provided!");
389 assert(Functions.Destroy &&
390 "No Destroy function provided!");
393 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
394 Functions.Destroy(Opaque);
397 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
398 uintptr_t Size, unsigned Alignment, unsigned SectionID,
399 StringRef SectionName) {
400 return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
401 SectionName.str().c_str());
404 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
405 uintptr_t Size, unsigned Alignment, unsigned SectionID,
406 StringRef SectionName, bool isReadOnly) {
407 return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
408 SectionName.str().c_str(),
412 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
413 char *errMsgCString = 0;
414 bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
415 assert((result || !errMsgCString) &&
416 "Did not expect an error message if FinalizeMemory succeeded");
419 *ErrMsg = errMsgCString;
425 } // anonymous namespace
427 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
429 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
430 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
431 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
432 LLVMMemoryManagerDestroyCallback Destroy) {
434 if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
438 SimpleBindingMMFunctions functions;
439 functions.AllocateCodeSection = AllocateCodeSection;
440 functions.AllocateDataSection = AllocateDataSection;
441 functions.FinalizeMemory = FinalizeMemory;
442 functions.Destroy = Destroy;
443 return wrap(new SimpleBindingMemoryManager(functions, Opaque));
446 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {