LLVM  3.7.0
ExecutionEngineBindings.cpp
Go to the documentation of this file.
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"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Module.h"
22 #include <cstring>
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "jit"
27 
28 // Wrapping the C bindings types.
30 
31 
33  return
34  reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
35 }
36 
37 /*===-- Operations on generic values --------------------------------------===*/
38 
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 
48  GenericValue *GenVal = new GenericValue();
49  GenVal->PointerVal = P;
50  return wrap(GenVal);
51 }
52 
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 
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 
82  return unwrap(GenVal)->PointerVal;
83 }
84 
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 
97  delete unwrap(GenVal);
98 }
99 
100 /*===-- Operations on execution engines -----------------------------------===*/
101 
103  LLVMModuleRef M,
104  char **OutError) {
105  std::string Error;
106  EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
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 
118  LLVMModuleRef M,
119  char **OutError) {
120  std::string Error;
121  EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
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 
133  LLVMModuleRef M,
134  unsigned OptLevel,
135  char **OutError) {
136  std::string Error;
137  EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
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 
150  size_t SizeOfPassedOptions) {
151  LLVMMCJITCompilerOptions options;
152  memset(&options, 0, sizeof(options)); // Most fields are zero by default.
154 
155  memcpy(PassedOptions, &options,
156  std::min(sizeof(options), SizeOfPassedOptions));
157 }
158 
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));
198  .setErrorStr(&Error)
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 
215  char **OutError) {
216  /* The module provider is now actually a module. */
218  reinterpret_cast<LLVMModuleRef>(MP),
219  OutError);
220 }
221 
224  char **OutError) {
225  /* The module provider is now actually a module. */
226  return LLVMCreateInterpreterForModule(OutInterp,
227  reinterpret_cast<LLVMModuleRef>(MP),
228  OutError);
229 }
230 
233  unsigned OptLevel,
234  char **OutError) {
235  /* The module provider is now actually a module. */
236  return LLVMCreateJITCompilerForModule(OutJIT,
237  reinterpret_cast<LLVMModuleRef>(MP),
238  OptLevel, OutError);
239 }
240 
241 
243  delete unwrap(EE);
244 }
245 
247  unwrap(EE)->runStaticConstructorsDestructors(false);
248 }
249 
251  unwrap(EE)->runStaticConstructorsDestructors(true);
252 }
253 
255  unsigned ArgC, const char * const *ArgV,
256  const char * const *EnvP) {
257  unwrap(EE)->finalizeObject();
258 
259  std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
260  return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
261 }
262 
264  unsigned NumArgs,
265  LLVMGenericValueRef *Args) {
266  unwrap(EE)->finalizeObject();
267 
268  std::vector<GenericValue> ArgVec;
269  ArgVec.reserve(NumArgs);
270  for (unsigned I = 0; I != NumArgs; ++I)
271  ArgVec.push_back(*unwrap(Args[I]));
272 
273  GenericValue *Result = new GenericValue();
274  *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
275  return wrap(Result);
276 }
277 
279 }
280 
282  unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
283 }
284 
286  /* The module provider is now actually a module. */
287  LLVMAddModule(EE, reinterpret_cast<LLVMModuleRef>(MP));
288 }
289 
291  LLVMModuleRef *OutMod, char **OutError) {
292  Module *Mod = unwrap(M);
293  unwrap(EE)->removeModule(Mod);
294  *OutMod = wrap(Mod);
295  return 0;
296 }
297 
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 
307  LLVMValueRef *OutFn) {
308  if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
309  *OutFn = wrap(F);
310  return 0;
311  }
312  return 1;
313 }
314 
316  LLVMValueRef Fn) {
317  return nullptr;
318 }
319 
321  return wrap(unwrap(EE)->getDataLayout());
322 }
323 
326  return wrap(unwrap(EE)->getTargetMachine());
327 }
328 
330  void* Addr) {
331  unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
332 }
333 
335  unwrap(EE)->finalizeObject();
336 
337  return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
338 }
339 
341  return unwrap(EE)->getGlobalValueAddress(Name);
342 }
343 
345  return unwrap(EE)->getFunctionAddress(Name);
346 }
347 
348 /*===-- Operations on memory managers -------------------------------------===*/
349 
350 namespace {
351 
352 struct SimpleBindingMMFunctions {
357 };
358 
359 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
360 public:
361  SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
362  void *Opaque);
363  ~SimpleBindingMemoryManager() override;
364 
365  uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
366  unsigned SectionID,
367  StringRef SectionName) override;
368 
369  uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
370  unsigned SectionID, StringRef SectionName,
371  bool isReadOnly) override;
372 
373  bool finalizeMemory(std::string *ErrMsg) override;
374 
375 private:
376  SimpleBindingMMFunctions Functions;
377  void *Opaque;
378 };
379 
380 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
381  const SimpleBindingMMFunctions& Functions,
382  void *Opaque)
383  : Functions(Functions), Opaque(Opaque) {
384  assert(Functions.AllocateCodeSection &&
385  "No AllocateCodeSection function provided!");
386  assert(Functions.AllocateDataSection &&
387  "No AllocateDataSection function provided!");
388  assert(Functions.FinalizeMemory &&
389  "No FinalizeMemory function provided!");
390  assert(Functions.Destroy &&
391  "No Destroy function provided!");
392 }
393 
394 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
395  Functions.Destroy(Opaque);
396 }
397 
398 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
399  uintptr_t Size, unsigned Alignment, unsigned SectionID,
400  StringRef SectionName) {
401  return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
402  SectionName.str().c_str());
403 }
404 
405 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
406  uintptr_t Size, unsigned Alignment, unsigned SectionID,
407  StringRef SectionName, bool isReadOnly) {
408  return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
409  SectionName.str().c_str(),
410  isReadOnly);
411 }
412 
413 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
414  char *errMsgCString = nullptr;
415  bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
416  assert((result || !errMsgCString) &&
417  "Did not expect an error message if FinalizeMemory succeeded");
418  if (errMsgCString) {
419  if (ErrMsg)
420  *ErrMsg = errMsgCString;
421  free(errMsgCString);
422  }
423  return result;
424 }
425 
426 } // anonymous namespace
427 
429  void *Opaque,
434 
435  if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
436  !Destroy)
437  return nullptr;
438 
439  SimpleBindingMMFunctions functions;
440  functions.AllocateCodeSection = AllocateCodeSection;
441  functions.AllocateDataSection = AllocateDataSection;
442  functions.FinalizeMemory = FinalizeMemory;
443  functions.Destroy = Destroy;
444  return wrap(new SimpleBindingMemoryManager(functions, Opaque));
445 }
446 
448  delete unwrap(MM);
449 }
450 
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type (if unknown returns 0).
LLVMBool(* LLVMMemoryManagerFinalizeMemoryCallback)(void *Opaque, char **ErrMsg)
PointerTy PointerVal
Definition: GenericValue.h:34
struct LLVMOpaqueType * LLVMTypeRef
Each value in the LLVM IR has a type, an LLVMTypeRef.
Definition: Core.h:85
LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N)
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1327
void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions)
void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP)
Deprecated: Use LLVMAddModule instead.
LLVMMCJITMemoryManagerRef MCJMM
struct LLVMOpaqueExecutionEngine * LLVMExecutionEngineRef
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
2: 32-bit floating point type
Definition: Type.h:58
void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE)
void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal)
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:188
void * LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE, LLVMValueRef Fn)
F(f)
LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M, unsigned OptLevel, char **OutError)
LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP, LLVMModuleRef *OutMod, char **OutError)
Deprecated: Use LLVMRemoveModule instead.
LLVMBool LLVMCreateJITCompiler(LLVMExecutionEngineRef *OutJIT, LLVMModuleProviderRef MP, unsigned OptLevel, char **OutError)
Deprecated: Use LLVMCreateJITCompilerForModule instead.
double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal)
void * LLVMGenericValueToPointer(LLVMGenericValueRef GenVal)
struct LLVMOpaqueMCJITMemoryManager * LLVMMCJITMemoryManagerRef
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
struct LLVMOpaqueTargetMachine * LLVMTargetMachineRef
LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P)
void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global, void *Addr)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
LLVMBool LLVMCreateInterpreter(LLVMExecutionEngineRef *OutInterp, LLVMModuleProviderRef MP, char **OutError)
Deprecated: Use LLVMCreateInterpreterForModule instead.
Number of individual test Apply this number of consecutive mutations to each input exit after the first new interesting input is found the minimized corpus is saved into the first input directory Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
LLVMTargetMachineRef wrap(const TargetMachine *P)
struct LLVMOpaqueModuleProvider * LLVMModuleProviderRef
Interface used to provide a module to JIT or interpreter.
Definition: Core.h:113
LLVMTargetDataRef wrap(const DataLayout *P)
Definition: DataLayout.h:469
void(* LLVMMemoryManagerDestroyCallback)(void *Opaque)
uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name)
EngineBuilder & setCodeModel(CodeModel::Model M)
setCodeModel - Set the CodeModel that the ExecutionEngine target data is using.
LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(void *Opaque, LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection, LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection, LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory, LLVMMemoryManagerDestroyCallback Destroy)
Create a simple custom MCJIT memory manager.
int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F, unsigned ArgC, const char *const *ArgV, const char *const *EnvP)
EngineBuilder & setEngineKind(EngineKind::Kind w)
setEngineKind - Controls whether the user wants the interpreter, the JIT, or whichever engine works...
#define P(N)
always inline
DataLayout * unwrap(LLVMTargetDataRef P)
Definition: DataLayout.h:465
LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE, LLVMModuleRef M, char **OutError)
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1339
EngineBuilder & setErrorStr(std::string *e)
setErrorStr - Set the error string to write to on error.
LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty, unsigned long long N, LLVMBool IsSigned)
LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE)
void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM)
void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE)
int LLVMBool
Definition: Support.h:29
Abstract interface for implementation execution of LLVM modules, designed to support both interpreter...
struct LLVMOpaqueValue * LLVMValueRef
Represents an individual value in LLVM IR.
Definition: Core.h:92
void * LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global)
EngineBuilder & setTargetOptions(const TargetOptions &Opts)
setTargetOptions - Set the target options that the ExecutionEngine target is using.
Module.h This file contains the declarations for the Module class.
uint8_t *(* LLVMMemoryManagerAllocateDataSectionCallback)(void *Opaque, uintptr_t Size, unsigned Alignment, unsigned SectionID, const char *SectionName, LLVMBool IsReadOnly)
LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp, LLVMModuleRef M, char **OutError)
Class for arbitrary precision integers.
Definition: APInt.h:73
static char getTypeID(Type *Ty)
void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE)
void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M)
uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name)
unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef, LLVMBool IsSigned)
LLVMTargetMachineRef LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE)
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
LLVMBool LLVMCreateExecutionEngine(LLVMExecutionEngineRef *OutEE, LLVMModuleProviderRef MP, char **OutError)
Deprecated: Use LLVMCreateExecutionEngineForModule instead.
LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F, unsigned NumArgs, LLVMGenericValueRef *Args)
uint8_t *(* LLVMMemoryManagerAllocateCodeSectionCallback)(void *Opaque, uintptr_t Size, unsigned Alignment, unsigned SectionID, const char *SectionName)
Builder class for ExecutionEngines.
EngineBuilder & setMCJITMemoryManager(std::unique_ptr< RTDyldMemoryManager > mcjmm)
setMCJITMemoryManager - Sets the MCJIT memory manager to use.
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: Core.h:78
unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef)
3: 64-bit floating point type
Definition: Type.h:59
LLVMBool LLVMCreateMCJITCompilerForModule(LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M, LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions, char **OutError)
Create an MCJIT execution engine for a module, with the given options.
aarch64 promote const
LLVM Value Representation.
Definition: Value.h:69
void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F)
Primary interface to the complete machine description for the target machine.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
struct LLVMOpaqueGenericValue * LLVMGenericValueRef
always Inliner for always_inline functions
EngineBuilder & setOptLevel(CodeGenOpt::Level l)
setOptLevel - Set the optimization level for the JIT.
struct LLVMOpaqueTargetData * LLVMTargetDataRef
Definition: DataLayout.h:32
LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name, LLVMValueRef *OutFn)
LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M, LLVMModuleRef *OutMod, char **OutError)