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"
21 #include "llvm/Target/TargetOptions.h"
26 #define DEBUG_TYPE "jit"
28 // Wrapping the C bindings types.
29 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
32 static LLVMTargetMachineRef wrap(const TargetMachine *P) {
34 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
37 /*===-- Operations on generic values --------------------------------------===*/
39 LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
42 GenericValue *GenVal = new GenericValue();
43 GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
47 LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
48 GenericValue *GenVal = new GenericValue();
49 GenVal->PointerVal = P;
53 LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
54 GenericValue *GenVal = new GenericValue();
55 switch (unwrap(TyRef)->getTypeID()) {
59 case Type::DoubleTyID:
60 GenVal->DoubleVal = N;
63 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
68 unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
69 return unwrap(GenValRef)->IntVal.getBitWidth();
72 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
74 GenericValue *GenVal = unwrap(GenValRef);
76 return GenVal->IntVal.getSExtValue();
78 return GenVal->IntVal.getZExtValue();
81 void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
82 return unwrap(GenVal)->PointerVal;
85 double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
86 switch (unwrap(TyRef)->getTypeID()) {
88 return unwrap(GenVal)->FloatVal;
89 case Type::DoubleTyID:
90 return unwrap(GenVal)->DoubleVal;
92 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
96 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
97 delete unwrap(GenVal);
100 /*===-- Operations on execution engines -----------------------------------===*/
102 LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
106 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
107 builder.setEngineKind(EngineKind::Either)
108 .setErrorStr(&Error);
109 if (ExecutionEngine *EE = builder.create()){
113 *OutError = strdup(Error.c_str());
117 LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
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);
128 *OutError = strdup(Error.c_str());
132 LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
137 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
138 builder.setEngineKind(EngineKind::JIT)
140 .setOptLevel((CodeGenOpt::Level)OptLevel);
141 if (ExecutionEngine *JIT = builder.create()) {
145 *OutError = strdup(Error.c_str());
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;
155 memcpy(PassedOptions, &options,
156 std::min(sizeof(options), SizeOfPassedOptions));
159 LLVMBool LLVMCreateMCJITCompilerForModule(
160 LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
161 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
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)) {
168 "Refusing to use options struct that is larger than my own; assuming "
169 "LLVM library mismatch.");
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);
180 TargetOptions targetOptions;
181 targetOptions.EnableFastISel = options.EnableFastISel;
182 std::unique_ptr<Module> Mod(unwrap(M));
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);
196 EngineBuilder builder(std::move(Mod));
197 builder.setEngineKind(EngineKind::JIT)
199 .setOptLevel((CodeGenOpt::Level)options.OptLevel)
200 .setCodeModel(unwrap(options.CodeModel))
201 .setTargetOptions(targetOptions);
203 builder.setMCJITMemoryManager(
204 std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
205 if (ExecutionEngine *JIT = builder.create()) {
209 *OutError = strdup(Error.c_str());
213 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
217 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
218 unwrap(EE)->runStaticConstructorsDestructors(false);
221 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
222 unwrap(EE)->runStaticConstructorsDestructors(true);
225 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
226 unsigned ArgC, const char * const *ArgV,
227 const char * const *EnvP) {
228 unwrap(EE)->finalizeObject();
230 std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
231 return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
234 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
236 LLVMGenericValueRef *Args) {
237 unwrap(EE)->finalizeObject();
239 std::vector<GenericValue> ArgVec;
240 ArgVec.reserve(NumArgs);
241 for (unsigned I = 0; I != NumArgs; ++I)
242 ArgVec.push_back(*unwrap(Args[I]));
244 GenericValue *Result = new GenericValue();
245 *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
249 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
252 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
253 unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
256 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
257 LLVMModuleRef *OutMod, char **OutError) {
258 Module *Mod = unwrap(M);
259 unwrap(EE)->removeModule(Mod);
264 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
265 LLVMValueRef *OutFn) {
266 if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
273 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
278 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
279 return wrap(&unwrap(EE)->getDataLayout());
283 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
284 return wrap(unwrap(EE)->getTargetMachine());
287 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
289 unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
292 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
293 unwrap(EE)->finalizeObject();
295 return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
298 uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) {
299 return unwrap(EE)->getGlobalValueAddress(Name);
302 uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) {
303 return unwrap(EE)->getFunctionAddress(Name);
306 /*===-- Operations on memory managers -------------------------------------===*/
310 struct SimpleBindingMMFunctions {
311 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
312 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
313 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
314 LLVMMemoryManagerDestroyCallback Destroy;
317 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
319 SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
321 ~SimpleBindingMemoryManager() override;
323 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
325 StringRef SectionName) override;
327 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
328 unsigned SectionID, StringRef SectionName,
329 bool isReadOnly) override;
331 bool finalizeMemory(std::string *ErrMsg) override;
334 SimpleBindingMMFunctions Functions;
338 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
339 const SimpleBindingMMFunctions& Functions,
341 : Functions(Functions), Opaque(Opaque) {
342 assert(Functions.AllocateCodeSection &&
343 "No AllocateCodeSection function provided!");
344 assert(Functions.AllocateDataSection &&
345 "No AllocateDataSection function provided!");
346 assert(Functions.FinalizeMemory &&
347 "No FinalizeMemory function provided!");
348 assert(Functions.Destroy &&
349 "No Destroy function provided!");
352 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
353 Functions.Destroy(Opaque);
356 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
357 uintptr_t Size, unsigned Alignment, unsigned SectionID,
358 StringRef SectionName) {
359 return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
360 SectionName.str().c_str());
363 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
364 uintptr_t Size, unsigned Alignment, unsigned SectionID,
365 StringRef SectionName, bool isReadOnly) {
366 return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
367 SectionName.str().c_str(),
371 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
372 char *errMsgCString = nullptr;
373 bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
374 assert((result || !errMsgCString) &&
375 "Did not expect an error message if FinalizeMemory succeeded");
378 *ErrMsg = errMsgCString;
384 } // anonymous namespace
386 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
388 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
389 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
390 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
391 LLVMMemoryManagerDestroyCallback Destroy) {
393 if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
397 SimpleBindingMMFunctions functions;
398 functions.AllocateCodeSection = AllocateCodeSection;
399 functions.AllocateDataSection = AllocateDataSection;
400 functions.FinalizeMemory = FinalizeMemory;
401 functions.Destroy = Destroy;
402 return wrap(new SimpleBindingMemoryManager(functions, Opaque));
405 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {