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 <cstring>
22
23using namespace llvm;
24
25#define DEBUG_TYPE "jit"
26
27// Wrapping the C bindings types.
28DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
29
30inline TargetLibraryInfo *unwrap(LLVMTargetLibraryInfoRef P) {
31  return reinterpret_cast<TargetLibraryInfo*>(P);
32}
33
34inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfo *P) {
35  TargetLibraryInfo *X = const_cast<TargetLibraryInfo*>(P);
36  return reinterpret_cast<LLVMTargetLibraryInfoRef>(X);
37}
38
39inline LLVMTargetMachineRef wrap(const TargetMachine *P) {
40  return
41  reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
42}
43
44/*===-- Operations on generic values --------------------------------------===*/
45
46LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
47                                                unsigned long long N,
48                                                LLVMBool IsSigned) {
49  GenericValue *GenVal = new GenericValue();
50  GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
51  return wrap(GenVal);
52}
53
54LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
55  GenericValue *GenVal = new GenericValue();
56  GenVal->PointerVal = P;
57  return wrap(GenVal);
58}
59
60LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
61  GenericValue *GenVal = new GenericValue();
62  switch (unwrap(TyRef)->getTypeID()) {
63  case Type::FloatTyID:
64    GenVal->FloatVal = N;
65    break;
66  case Type::DoubleTyID:
67    GenVal->DoubleVal = N;
68    break;
69  default:
70    llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
71  }
72  return wrap(GenVal);
73}
74
75unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
76  return unwrap(GenValRef)->IntVal.getBitWidth();
77}
78
79unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
80                                         LLVMBool IsSigned) {
81  GenericValue *GenVal = unwrap(GenValRef);
82  if (IsSigned)
83    return GenVal->IntVal.getSExtValue();
84  else
85    return GenVal->IntVal.getZExtValue();
86}
87
88void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
89  return unwrap(GenVal)->PointerVal;
90}
91
92double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
93  switch (unwrap(TyRef)->getTypeID()) {
94  case Type::FloatTyID:
95    return unwrap(GenVal)->FloatVal;
96  case Type::DoubleTyID:
97    return unwrap(GenVal)->DoubleVal;
98  default:
99    llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
100  }
101}
102
103void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
104  delete unwrap(GenVal);
105}
106
107/*===-- Operations on execution engines -----------------------------------===*/
108
109LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
110                                            LLVMModuleRef M,
111                                            char **OutError) {
112  std::string Error;
113  EngineBuilder builder(unwrap(M));
114  builder.setEngineKind(EngineKind::Either)
115         .setErrorStr(&Error);
116  if (ExecutionEngine *EE = builder.create()){
117    *OutEE = wrap(EE);
118    return 0;
119  }
120  *OutError = strdup(Error.c_str());
121  return 1;
122}
123
124LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
125                                        LLVMModuleRef M,
126                                        char **OutError) {
127  std::string Error;
128  EngineBuilder builder(unwrap(M));
129  builder.setEngineKind(EngineKind::Interpreter)
130         .setErrorStr(&Error);
131  if (ExecutionEngine *Interp = builder.create()) {
132    *OutInterp = wrap(Interp);
133    return 0;
134  }
135  *OutError = strdup(Error.c_str());
136  return 1;
137}
138
139LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
140                                        LLVMModuleRef M,
141                                        unsigned OptLevel,
142                                        char **OutError) {
143  std::string Error;
144  EngineBuilder builder(unwrap(M));
145  builder.setEngineKind(EngineKind::JIT)
146         .setErrorStr(&Error)
147         .setOptLevel((CodeGenOpt::Level)OptLevel);
148  if (ExecutionEngine *JIT = builder.create()) {
149    *OutJIT = wrap(JIT);
150    return 0;
151  }
152  *OutError = strdup(Error.c_str());
153  return 1;
154}
155
156void 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;
161
162  memcpy(PassedOptions, &options,
163         std::min(sizeof(options), SizeOfPassedOptions));
164}
165
166LLVMBool LLVMCreateMCJITCompilerForModule(
167    LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
168    LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
169    char **OutError) {
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)) {
174    *OutError = strdup(
175      "Refusing to use options struct that is larger than my own; assuming "
176      "LLVM library mismatch.");
177    return 1;
178  }
179
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);
186
187  TargetOptions targetOptions;
188  targetOptions.NoFramePointerElim = options.NoFramePointerElim;
189  targetOptions.EnableFastISel = options.EnableFastISel;
190
191  std::string Error;
192  EngineBuilder builder(unwrap(M));
193  builder.setEngineKind(EngineKind::JIT)
194         .setErrorStr(&Error)
195         .setUseMCJIT(true)
196         .setOptLevel((CodeGenOpt::Level)options.OptLevel)
197         .setCodeModel(unwrap(options.CodeModel))
198         .setTargetOptions(targetOptions);
199  if (options.MCJMM)
200    builder.setMCJITMemoryManager(unwrap(options.MCJMM));
201  if (ExecutionEngine *JIT = builder.create()) {
202    *OutJIT = wrap(JIT);
203    return 0;
204  }
205  *OutError = strdup(Error.c_str());
206  return 1;
207}
208
209LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE,
210                                   LLVMModuleProviderRef MP,
211                                   char **OutError) {
212  /* The module provider is now actually a module. */
213  return LLVMCreateExecutionEngineForModule(OutEE,
214                                            reinterpret_cast<LLVMModuleRef>(MP),
215                                            OutError);
216}
217
218LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp,
219                               LLVMModuleProviderRef MP,
220                               char **OutError) {
221  /* The module provider is now actually a module. */
222  return LLVMCreateInterpreterForModule(OutInterp,
223                                        reinterpret_cast<LLVMModuleRef>(MP),
224                                        OutError);
225}
226
227LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT,
228                               LLVMModuleProviderRef MP,
229                               unsigned OptLevel,
230                               char **OutError) {
231  /* The module provider is now actually a module. */
232  return LLVMCreateJITCompilerForModule(OutJIT,
233                                        reinterpret_cast<LLVMModuleRef>(MP),
234                                        OptLevel, OutError);
235}
236
237
238void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
239  delete unwrap(EE);
240}
241
242void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
243  unwrap(EE)->runStaticConstructorsDestructors(false);
244}
245
246void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
247  unwrap(EE)->runStaticConstructorsDestructors(true);
248}
249
250int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
251                          unsigned ArgC, const char * const *ArgV,
252                          const char * const *EnvP) {
253  unwrap(EE)->finalizeObject();
254
255  std::vector<std::string> ArgVec;
256  for (unsigned I = 0; I != ArgC; ++I)
257    ArgVec.push_back(ArgV[I]);
258
259  return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
260}
261
262LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
263                                    unsigned NumArgs,
264                                    LLVMGenericValueRef *Args) {
265  unwrap(EE)->finalizeObject();
266
267  std::vector<GenericValue> ArgVec;
268  ArgVec.reserve(NumArgs);
269  for (unsigned I = 0; I != NumArgs; ++I)
270    ArgVec.push_back(*unwrap(Args[I]));
271
272  GenericValue *Result = new GenericValue();
273  *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
274  return wrap(Result);
275}
276
277void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
278  unwrap(EE)->freeMachineCodeForFunction(unwrap<Function>(F));
279}
280
281void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
282  unwrap(EE)->addModule(unwrap(M));
283}
284
285void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
286  /* The module provider is now actually a module. */
287  LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
288}
289
290LLVMBool 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
298LLVMBool 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
306LLVMBool 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
315void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
316                                     LLVMValueRef Fn) {
317  return unwrap(EE)->recompileAndRelinkFunction(unwrap<Function>(Fn));
318}
319
320LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
321  return wrap(unwrap(EE)->getDataLayout());
322}
323
324LLVMTargetMachineRef
325LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
326  return wrap(unwrap(EE)->getTargetMachine());
327}
328
329void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
330                          void* Addr) {
331  unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
332}
333
334void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
335  unwrap(EE)->finalizeObject();
336
337  return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
338}
339
340/*===-- Operations on memory managers -------------------------------------===*/
341
342namespace {
343
344struct SimpleBindingMMFunctions {
345  LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
346  LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
347  LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
348  LLVMMemoryManagerDestroyCallback Destroy;
349};
350
351class SimpleBindingMemoryManager : public RTDyldMemoryManager {
352public:
353  SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
354                             void *Opaque);
355  virtual ~SimpleBindingMemoryManager();
356
357  uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
358                               unsigned SectionID,
359                               StringRef SectionName) override;
360
361  uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
362                               unsigned SectionID, StringRef SectionName,
363                               bool isReadOnly) override;
364
365  bool finalizeMemory(std::string *ErrMsg) override;
366
367private:
368  SimpleBindingMMFunctions Functions;
369  void *Opaque;
370};
371
372SimpleBindingMemoryManager::SimpleBindingMemoryManager(
373  const SimpleBindingMMFunctions& Functions,
374  void *Opaque)
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!");
384}
385
386SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
387  Functions.Destroy(Opaque);
388}
389
390uint8_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());
395}
396
397uint8_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(),
402                                       isReadOnly);
403}
404
405bool 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");
410  if (errMsgCString) {
411    if (ErrMsg)
412      *ErrMsg = errMsgCString;
413    free(errMsgCString);
414  }
415  return result;
416}
417
418} // anonymous namespace
419
420LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
421  void *Opaque,
422  LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
423  LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
424  LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
425  LLVMMemoryManagerDestroyCallback Destroy) {
426
427  if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
428      !Destroy)
429    return nullptr;
430
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));
437}
438
439void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
440  delete unwrap(MM);
441}
442
443