LLVM  4.0.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"
23 #include <cstring>
24 
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "jit"
28 
29 // Wrapping the C bindings types.
31 
32 
34  return
35  reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
36 }
37 
38 /*===-- Operations on generic values --------------------------------------===*/
39 
41  unsigned long long N,
42  LLVMBool IsSigned) {
43  GenericValue *GenVal = new GenericValue();
44  GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
45  return wrap(GenVal);
46 }
47 
49  GenericValue *GenVal = new GenericValue();
50  GenVal->PointerVal = P;
51  return wrap(GenVal);
52 }
53 
55  GenericValue *GenVal = new GenericValue();
56  switch (unwrap(TyRef)->getTypeID()) {
57  case Type::FloatTyID:
58  GenVal->FloatVal = N;
59  break;
60  case Type::DoubleTyID:
61  GenVal->DoubleVal = N;
62  break;
63  default:
64  llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
65  }
66  return wrap(GenVal);
67 }
68 
70  return unwrap(GenValRef)->IntVal.getBitWidth();
71 }
72 
73 unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
74  LLVMBool IsSigned) {
75  GenericValue *GenVal = unwrap(GenValRef);
76  if (IsSigned)
77  return GenVal->IntVal.getSExtValue();
78  else
79  return GenVal->IntVal.getZExtValue();
80 }
81 
83  return unwrap(GenVal)->PointerVal;
84 }
85 
87  switch (unwrap(TyRef)->getTypeID()) {
88  case Type::FloatTyID:
89  return unwrap(GenVal)->FloatVal;
90  case Type::DoubleTyID:
91  return unwrap(GenVal)->DoubleVal;
92  default:
93  llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
94  }
95 }
96 
98  delete unwrap(GenVal);
99 }
100 
101 /*===-- Operations on execution engines -----------------------------------===*/
102 
104  LLVMModuleRef M,
105  char **OutError) {
106  std::string Error;
107  EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
109  .setErrorStr(&Error);
110  if (ExecutionEngine *EE = builder.create()){
111  *OutEE = wrap(EE);
112  return 0;
113  }
114  *OutError = strdup(Error.c_str());
115  return 1;
116 }
117 
119  LLVMModuleRef M,
120  char **OutError) {
121  std::string Error;
122  EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
124  .setErrorStr(&Error);
125  if (ExecutionEngine *Interp = builder.create()) {
126  *OutInterp = wrap(Interp);
127  return 0;
128  }
129  *OutError = strdup(Error.c_str());
130  return 1;
131 }
132 
134  LLVMModuleRef M,
135  unsigned OptLevel,
136  char **OutError) {
137  std::string Error;
138  EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
140  .setErrorStr(&Error)
141  .setOptLevel((CodeGenOpt::Level)OptLevel);
142  if (ExecutionEngine *JIT = builder.create()) {
143  *OutJIT = wrap(JIT);
144  return 0;
145  }
146  *OutError = strdup(Error.c_str());
147  return 1;
148 }
149 
151  size_t SizeOfPassedOptions) {
152  LLVMMCJITCompilerOptions options;
153  memset(&options, 0, sizeof(options)); // Most fields are zero by default.
155 
156  memcpy(PassedOptions, &options,
157  std::min(sizeof(options), SizeOfPassedOptions));
158 }
159 
162  LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
163  char **OutError) {
164  LLVMMCJITCompilerOptions options;
165  // If the user passed a larger sized options struct, then they were compiled
166  // against a newer LLVM. Tell them that something is wrong.
167  if (SizeOfPassedOptions > sizeof(options)) {
168  *OutError = strdup(
169  "Refusing to use options struct that is larger than my own; assuming "
170  "LLVM library mismatch.");
171  return 1;
172  }
173 
174  // Defend against the user having an old version of the API by ensuring that
175  // any fields they didn't see are cleared. We must defend against fields being
176  // set to the bitwise equivalent of zero, and assume that this means "do the
177  // default" as if that option hadn't been available.
178  LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
179  memcpy(&options, PassedOptions, SizeOfPassedOptions);
180 
181  TargetOptions targetOptions;
182  targetOptions.EnableFastISel = options.EnableFastISel;
183  std::unique_ptr<Module> Mod(unwrap(M));
184 
185  if (Mod)
186  // Set function attribute "no-frame-pointer-elim" based on
187  // NoFramePointerElim.
188  for (auto &F : *Mod) {
189  auto Attrs = F.getAttributes();
190  StringRef Value(options.NoFramePointerElim ? "true" : "false");
191  Attrs = Attrs.addAttribute(F.getContext(), AttributeSet::FunctionIndex,
192  "no-frame-pointer-elim", Value);
193  F.setAttributes(Attrs);
194  }
195 
196  std::string Error;
197  EngineBuilder builder(std::move(Mod));
199  .setErrorStr(&Error)
201  .setCodeModel(unwrap(options.CodeModel))
202  .setTargetOptions(targetOptions);
203  if (options.MCJMM)
204  builder.setMCJITMemoryManager(
205  std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
206  if (ExecutionEngine *JIT = builder.create()) {
207  *OutJIT = wrap(JIT);
208  return 0;
209  }
210  *OutError = strdup(Error.c_str());
211  return 1;
212 }
213 
215  delete unwrap(EE);
216 }
217 
219  unwrap(EE)->finalizeObject();
220  unwrap(EE)->runStaticConstructorsDestructors(false);
221 }
222 
224  unwrap(EE)->finalizeObject();
225  unwrap(EE)->runStaticConstructorsDestructors(true);
226 }
227 
229  unsigned ArgC, const char * const *ArgV,
230  const char * const *EnvP) {
231  unwrap(EE)->finalizeObject();
232 
233  std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
234  return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
235 }
236 
238  unsigned NumArgs,
240  unwrap(EE)->finalizeObject();
241 
242  std::vector<GenericValue> ArgVec;
243  ArgVec.reserve(NumArgs);
244  for (unsigned I = 0; I != NumArgs; ++I)
245  ArgVec.push_back(*unwrap(Args[I]));
246 
247  GenericValue *Result = new GenericValue();
248  *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
249  return wrap(Result);
250 }
251 
253 }
254 
256  unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
257 }
258 
260  LLVMModuleRef *OutMod, char **OutError) {
261  Module *Mod = unwrap(M);
262  unwrap(EE)->removeModule(Mod);
263  *OutMod = wrap(Mod);
264  return 0;
265 }
266 
268  LLVMValueRef *OutFn) {
269  if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
270  *OutFn = wrap(F);
271  return 0;
272  }
273  return 1;
274 }
275 
277  LLVMValueRef Fn) {
278  return nullptr;
279 }
280 
282  return wrap(&unwrap(EE)->getDataLayout());
283 }
284 
287  return wrap(unwrap(EE)->getTargetMachine());
288 }
289 
291  void* Addr) {
292  unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
293 }
294 
296  unwrap(EE)->finalizeObject();
297 
298  return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
299 }
300 
302  return unwrap(EE)->getGlobalValueAddress(Name);
303 }
304 
306  return unwrap(EE)->getFunctionAddress(Name);
307 }
308 
309 /*===-- Operations on memory managers -------------------------------------===*/
310 
311 namespace {
312 
313 struct SimpleBindingMMFunctions {
318 };
319 
320 class SimpleBindingMemoryManager : public RTDyldMemoryManager {
321 public:
322  SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
323  void *Opaque);
324  ~SimpleBindingMemoryManager() override;
325 
326  uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
327  unsigned SectionID,
328  StringRef SectionName) override;
329 
330  uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
331  unsigned SectionID, StringRef SectionName,
332  bool isReadOnly) override;
333 
334  bool finalizeMemory(std::string *ErrMsg) override;
335 
336 private:
337  SimpleBindingMMFunctions Functions;
338  void *Opaque;
339 };
340 
341 SimpleBindingMemoryManager::SimpleBindingMemoryManager(
342  const SimpleBindingMMFunctions& Functions,
343  void *Opaque)
344  : Functions(Functions), Opaque(Opaque) {
345  assert(Functions.AllocateCodeSection &&
346  "No AllocateCodeSection function provided!");
347  assert(Functions.AllocateDataSection &&
348  "No AllocateDataSection function provided!");
349  assert(Functions.FinalizeMemory &&
350  "No FinalizeMemory function provided!");
351  assert(Functions.Destroy &&
352  "No Destroy function provided!");
353 }
354 
355 SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
356  Functions.Destroy(Opaque);
357 }
358 
359 uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
360  uintptr_t Size, unsigned Alignment, unsigned SectionID,
362  return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
363  SectionName.str().c_str());
364 }
365 
366 uint8_t *SimpleBindingMemoryManager::allocateDataSection(
367  uintptr_t Size, unsigned Alignment, unsigned SectionID,
368  StringRef SectionName, bool isReadOnly) {
369  return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
370  SectionName.str().c_str(),
371  isReadOnly);
372 }
373 
374 bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
375  char *errMsgCString = nullptr;
376  bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
377  assert((result || !errMsgCString) &&
378  "Did not expect an error message if FinalizeMemory succeeded");
379  if (errMsgCString) {
380  if (ErrMsg)
381  *ErrMsg = errMsgCString;
382  free(errMsgCString);
383  }
384  return result;
385 }
386 
387 } // anonymous namespace
388 
390  void *Opaque,
395 
396  if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
397  !Destroy)
398  return nullptr;
399 
400  SimpleBindingMMFunctions functions;
401  functions.AllocateCodeSection = AllocateCodeSection;
402  functions.AllocateDataSection = AllocateDataSection;
403  functions.FinalizeMemory = FinalizeMemory;
404  functions.Destroy = Destroy;
405  return wrap(new SimpleBindingMemoryManager(functions, Opaque));
406 }
407 
409  delete unwrap(MM);
410 }
411 
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:35
LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N)
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1309
void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions)
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: c/Types.h:62
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:52
2: 32-bit floating point type
Definition: Type.h:58
void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE)
void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal)
void * LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE, LLVMValueRef Fn)
LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M, unsigned OptLevel, char **OutError)
double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal)
void * LLVMGenericValueToPointer(LLVMGenericValueRef GenVal)
struct LLVMOpaqueMCJITMemoryManager * LLVMMCJITMemoryManagerRef
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
struct LLVMOpaqueTargetMachine * LLVMTargetMachineRef
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:191
LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P)
void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global, void *Addr)
always Inliner for always_inline functions
struct LLVMOpaqueType * LLVMTypeRef
Each value in the LLVM IR has a type, an LLVMTypeRef.
Definition: c/Types.h:69
#define F(x, y, z)
Definition: MD5.cpp:51
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.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with etc Experimental Use value profile to guide fuzzing Number of simultaneous worker processes to run the jobs If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
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)
LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE, LLVMModuleRef M, char **OutError)
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1321
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)
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:225
int LLVMBool
Definition: c/Types.h:29
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract interface for implementation execution of LLVM modules, designed to support both interpreter...
void * LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global)
EngineBuilder & setTargetOptions(const TargetOptions &Opts)
setTargetOptions - Set the target options that the ExecutionEngine target is using.
static bool isReadOnly(const GlobalValue *GV)
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:77
static char getTypeID(Type *Ty)
static LLVMTargetMachineRef wrap(const TargetMachine *P)
void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE)
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:186
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
const char SectionName[]
Definition: AMDGPUPTNote.h:24
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.
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.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
aarch64 promote const
LLVM Value Representation.
Definition: Value.h:71
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:47
struct LLVMOpaqueGenericValue * LLVMGenericValueRef
EngineBuilder & setOptLevel(CodeGenOpt::Level l)
setOptLevel - Set the optimization level for the JIT.
struct LLVMOpaqueValue * LLVMValueRef
Represents an individual value in LLVM IR.
Definition: c/Types.h:76
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)