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 void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
214   delete unwrap(EE);
215 }
216 
217 void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
218   unwrap(EE)->finalizeObject();
219   unwrap(EE)->runStaticConstructorsDestructors(false);
220 }
221 
222 void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
223   unwrap(EE)->finalizeObject();
224   unwrap(EE)->runStaticConstructorsDestructors(true);
225 }
226 
227 int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
228                           unsigned ArgC, const char * const *ArgV,
229                           const char * const *EnvP) {
230   unwrap(EE)->finalizeObject();
231 
232   std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
233   return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
234 }
235 
236 LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
237                                     unsigned NumArgs,
238                                     LLVMGenericValueRef *Args) {
239   unwrap(EE)->finalizeObject();
240 
241   std::vector<GenericValue> ArgVec;
242   ArgVec.reserve(NumArgs);
243   for (unsigned I = 0; I != NumArgs; ++I)
244     ArgVec.push_back(*unwrap(Args[I]));
245 
246   GenericValue *Result = new GenericValue();
247   *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
248   return wrap(Result);
249 }
250 
251 void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
252 }
253 
254 void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
255   unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
256 }
257 
258 LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
259                           LLVMModuleRef *OutMod, char **OutError) {
260   Module *Mod = unwrap(M);
261   unwrap(EE)->removeModule(Mod);
262   *OutMod = wrap(Mod);
263   return 0;
264 }
265 
266 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
267                           LLVMValueRef *OutFn) {
268   if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
269     *OutFn = wrap(F);
270     return 0;
271   }
272   return 1;
273 }
274 
275 void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
276                                      LLVMValueRef Fn) {
277   return nullptr;
278 }
279 
280 LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
281   return wrap(&unwrap(EE)->getDataLayout());
282 }
283 
284 LLVMTargetMachineRef
285 LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
286   return wrap(unwrap(EE)->getTargetMachine());
287 }
288 
289 void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
290                           void* Addr) {
291   unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
292 }
293 
294 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
295   unwrap(EE)->finalizeObject();
296 
297   return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
298 }
299 
300 uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) {
301   return unwrap(EE)->getGlobalValueAddress(Name);
302 }
303 
304 uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) {
305   return unwrap(EE)->getFunctionAddress(Name);
306 }
307 
308 /*===-- Operations on memory managers -------------------------------------===*/
309 
310 namespace {
311 
312 struct SimpleBindingMMFunctions {
313   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
314   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
315   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
316   LLVMMemoryManagerDestroyCallback Destroy;
317 };
318 
319 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
320 public:
321   SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
322                              void *Opaque);
323   ~SimpleBindingMemoryManager() override;
324 
325   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
326                                unsigned SectionID,
327                                StringRef SectionName) override;
328 
329   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
330                                unsigned SectionID, StringRef SectionName,
331                                bool isReadOnly) override;
332 
333   bool finalizeMemory(std::string *ErrMsg) override;
334 
335 private:
336   SimpleBindingMMFunctions Functions;
337   void *Opaque;
338 };
339 
340 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
341   const SimpleBindingMMFunctions& Functions,
342   void *Opaque)
343   : Functions(Functions), Opaque(Opaque) {
344   assert(Functions.AllocateCodeSection &&
345          "No AllocateCodeSection function provided!");
346   assert(Functions.AllocateDataSection &&
347          "No AllocateDataSection function provided!");
348   assert(Functions.FinalizeMemory &&
349          "No FinalizeMemory function provided!");
350   assert(Functions.Destroy &&
351          "No Destroy function provided!");
352 }
353 
354 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
355   Functions.Destroy(Opaque);
356 }
357 
358 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
359   uintptr_t Size, unsigned Alignment, unsigned SectionID,
360   StringRef SectionName) {
361   return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
362                                        SectionName.str().c_str());
363 }
364 
365 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
366   uintptr_t Size, unsigned Alignment, unsigned SectionID,
367   StringRef SectionName, bool isReadOnly) {
368   return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
369                                        SectionName.str().c_str(),
370                                        isReadOnly);
371 }
372 
373 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
374   char *errMsgCString = nullptr;
375   bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
376   assert((result || !errMsgCString) &&
377          "Did not expect an error message if FinalizeMemory succeeded");
378   if (errMsgCString) {
379     if (ErrMsg)
380       *ErrMsg = errMsgCString;
381     free(errMsgCString);
382   }
383   return result;
384 }
385 
386 } // anonymous namespace
387 
388 LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
389   void *Opaque,
390   LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
391   LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
392   LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
393   LLVMMemoryManagerDestroyCallback Destroy) {
394 
395   if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
396       !Destroy)
397     return nullptr;
398 
399   SimpleBindingMMFunctions functions;
400   functions.AllocateCodeSection = AllocateCodeSection;
401   functions.AllocateDataSection = AllocateDataSection;
402   functions.FinalizeMemory = FinalizeMemory;
403   functions.Destroy = Destroy;
404   return wrap(new SimpleBindingMemoryManager(functions, Opaque));
405 }
406 
407 void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
408   delete unwrap(MM);
409 }
410 
411