1 //===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
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 abstract interface that implements execution support
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
16 #define LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
18 #include "llvm-c/ExecutionEngine.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/ValueMap.h"
23 #include "llvm/MC/MCCodeGenInfo.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
37 class ExecutionEngine;
41 class JITEventListener;
42 class JITMemoryManager;
43 class MachineCodeInfo;
51 /// \brief Helper class for helping synchronize access to the global address map
53 class ExecutionEngineState {
55 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
56 typedef ExecutionEngineState *ExtraData;
57 static sys::Mutex *getMutex(ExecutionEngineState *EES);
58 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
59 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
63 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
69 /// GlobalAddressMap - A mapping between LLVM global values and their
70 /// actualized version...
71 GlobalAddressMapTy GlobalAddressMap;
73 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
74 /// used to convert raw addresses into the LLVM global value that is emitted
75 /// at the address. This map is not computed unless getGlobalValueAtAddress
76 /// is called at some point.
77 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
80 ExecutionEngineState(ExecutionEngine &EE);
82 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
83 return GlobalAddressMap;
86 std::map<void*, AssertingVH<const GlobalValue> > &
87 getGlobalAddressReverseMap(const MutexGuard &) {
88 return GlobalAddressReverseMap;
91 /// \brief Erase an entry from the mapping table.
93 /// \returns The address that \p ToUnmap was happed to.
94 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
97 /// \brief Abstract interface for implementation execution of LLVM modules,
98 /// designed to support both interpreter and just-in-time (JIT) compiler
100 class ExecutionEngine {
101 /// The state object holding the global address mapping, which must be
102 /// accessed synchronously.
104 // FIXME: There is no particular need the entire map needs to be
105 // synchronized. Wouldn't a reader-writer design be better here?
106 ExecutionEngineState EEState;
108 /// The target data for the platform for which execution is being performed.
109 const DataLayout *TD;
111 /// Whether lazy JIT compilation is enabled.
112 bool CompilingLazily;
114 /// Whether JIT compilation of external global variables is allowed.
115 bool GVCompilationDisabled;
117 /// Whether the JIT should perform lookups of external symbols (e.g.,
119 bool SymbolSearchingDisabled;
121 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
124 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
125 /// optimize for the case where there is only one module.
126 SmallVector<Module*, 1> Modules;
128 void setDataLayout(const DataLayout *td) { TD = td; }
130 /// getMemoryforGV - Allocate memory for a global variable.
131 virtual char *getMemoryForGV(const GlobalVariable *GV);
133 // To avoid having libexecutionengine depend on the JIT and interpreter
134 // libraries, the execution engine implementations set these functions to ctor
135 // pointers at startup time if they are linked in.
136 static ExecutionEngine *(*JITCtor)(
138 std::string *ErrorStr,
139 JITMemoryManager *JMM,
142 static ExecutionEngine *(*MCJITCtor)(
144 std::string *ErrorStr,
145 JITMemoryManager *JMM,
148 static ExecutionEngine *(*InterpCtor)(Module *M, std::string *ErrorStr);
150 /// LazyFunctionCreator - If an unknown function is needed, this function
151 /// pointer is invoked to create it. If this returns null, the JIT will
153 void *(*LazyFunctionCreator)(const std::string &);
155 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
156 /// register dwarf tables with this function.
157 typedef void (*EERegisterFn)(void*);
158 EERegisterFn ExceptionTableRegister;
159 EERegisterFn ExceptionTableDeregister;
160 /// This maps functions to their exception tables frames.
161 DenseMap<const Function*, void*> AllExceptionTables;
165 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
166 /// JITEmitter classes. It must be held while changing the internal state of
167 /// any of those classes.
170 //===--------------------------------------------------------------------===//
171 // ExecutionEngine Startup
172 //===--------------------------------------------------------------------===//
174 virtual ~ExecutionEngine();
176 /// create - This is the factory method for creating an execution engine which
177 /// is appropriate for the current machine. This takes ownership of the
180 /// \param GVsWithCode - Allocating globals with code breaks
181 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
182 /// However, we have clients who depend on this behavior, so we must support
183 /// it. Eventually, when we're willing to break some backwards compatibility,
184 /// this flag should be flipped to false, so that by default
185 /// freeMachineCodeForFunction works.
186 static ExecutionEngine *create(Module *M,
187 bool ForceInterpreter = false,
188 std::string *ErrorStr = 0,
189 CodeGenOpt::Level OptLevel =
191 bool GVsWithCode = true);
193 /// createJIT - This is the factory method for creating a JIT for the current
194 /// machine, it does not fall back to the interpreter. This takes ownership
195 /// of the Module and JITMemoryManager if successful.
197 /// Clients should make sure to initialize targets prior to calling this
199 static ExecutionEngine *createJIT(Module *M,
200 std::string *ErrorStr = 0,
201 JITMemoryManager *JMM = 0,
202 CodeGenOpt::Level OptLevel =
204 bool GVsWithCode = true,
205 Reloc::Model RM = Reloc::Default,
206 CodeModel::Model CMM =
207 CodeModel::JITDefault);
209 /// addModule - Add a Module to the list of modules that we can JIT from.
210 /// Note that this takes ownership of the Module: when the ExecutionEngine is
211 /// destroyed, it destroys the Module as well.
212 virtual void addModule(Module *M) {
213 Modules.push_back(M);
216 //===--------------------------------------------------------------------===//
218 const DataLayout *getDataLayout() const { return TD; }
220 /// removeModule - Remove a Module from the list of modules. Returns true if
222 virtual bool removeModule(Module *M);
224 /// FindFunctionNamed - Search all of the active modules to find the one that
225 /// defines FnName. This is very slow operation and shouldn't be used for
227 Function *FindFunctionNamed(const char *FnName);
229 /// runFunction - Execute the specified function with the specified arguments,
230 /// and return the result.
231 virtual GenericValue runFunction(Function *F,
232 const std::vector<GenericValue> &ArgValues) = 0;
234 /// getPointerToNamedFunction - This method returns the address of the
235 /// specified function by using the dlsym function call. As such it is only
236 /// useful for resolving library symbols, not code generated symbols.
238 /// If AbortOnFailure is false and no function with the given name is
239 /// found, this function silently returns a null pointer. Otherwise,
240 /// it prints a message to stderr and aborts.
242 virtual void *getPointerToNamedFunction(const std::string &Name,
243 bool AbortOnFailure = true) = 0;
245 /// mapSectionAddress - map a section to its target address space value.
246 /// Map the address of a JIT section as returned from the memory manager
247 /// to the address in the target process as the running code will see it.
248 /// This is the address which will be used for relocation resolution.
249 virtual void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
250 llvm_unreachable("Re-mapping of section addresses not supported with this "
254 // finalizeObject - This method should be called after sections within an
255 // object have been relocated using mapSectionAddress. When this method is
256 // called the MCJIT execution engine will reapply relocations for a loaded
257 // object. This method has no effect for the legacy JIT engine or the
259 virtual void finalizeObject() {}
261 /// runStaticConstructorsDestructors - This method is used to execute all of
262 /// the static constructors or destructors for a program.
264 /// \param isDtors - Run the destructors instead of constructors.
265 void runStaticConstructorsDestructors(bool isDtors);
267 /// runStaticConstructorsDestructors - This method is used to execute all of
268 /// the static constructors or destructors for a particular module.
270 /// \param isDtors - Run the destructors instead of constructors.
271 void runStaticConstructorsDestructors(Module *module, bool isDtors);
274 /// runFunctionAsMain - This is a helper function which wraps runFunction to
275 /// handle the common task of starting up main with the specified argc, argv,
276 /// and envp parameters.
277 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
278 const char * const * envp);
281 /// addGlobalMapping - Tell the execution engine that the specified global is
282 /// at the specified location. This is used internally as functions are JIT'd
283 /// and as global variables are laid out in memory. It can and should also be
284 /// used by clients of the EE that want to have an LLVM global overlay
285 /// existing data in memory. Mappings are automatically removed when their
286 /// GlobalValue is destroyed.
287 void addGlobalMapping(const GlobalValue *GV, void *Addr);
289 /// clearAllGlobalMappings - Clear all global mappings and start over again,
290 /// for use in dynamic compilation scenarios to move globals.
291 void clearAllGlobalMappings();
293 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
294 /// particular module, because it has been removed from the JIT.
295 void clearGlobalMappingsFromModule(Module *M);
297 /// updateGlobalMapping - Replace an existing mapping for GV with a new
298 /// address. This updates both maps as required. If "Addr" is null, the
299 /// entry for the global is removed from the mappings. This returns the old
300 /// value of the pointer, or null if it was not in the map.
301 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
303 /// getPointerToGlobalIfAvailable - This returns the address of the specified
304 /// global value if it is has already been codegen'd, otherwise it returns
306 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
308 /// getPointerToGlobal - This returns the address of the specified global
309 /// value. This may involve code generation if it's a function.
310 void *getPointerToGlobal(const GlobalValue *GV);
312 /// getPointerToFunction - The different EE's represent function bodies in
313 /// different ways. They should each implement this to say what a function
314 /// pointer should look like. When F is destroyed, the ExecutionEngine will
315 /// remove its global mapping and free any machine code. Be sure no threads
316 /// are running inside F when that happens.
317 virtual void *getPointerToFunction(Function *F) = 0;
319 /// getPointerToBasicBlock - The different EE's represent basic blocks in
320 /// different ways. Return the representation for a blockaddress of the
322 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
324 /// getPointerToFunctionOrStub - If the specified function has been
325 /// code-gen'd, return a pointer to the function. If not, compile it, or use
326 /// a stub to implement lazy compilation if available. See
327 /// getPointerToFunction for the requirements on destroying F.
328 virtual void *getPointerToFunctionOrStub(Function *F) {
329 // Default implementation, just codegen the function.
330 return getPointerToFunction(F);
333 // The JIT overrides a version that actually does this.
334 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
336 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
337 /// at the specified address.
339 const GlobalValue *getGlobalValueAtAddress(void *Addr);
341 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
342 /// Ptr is the address of the memory at which to store Val, cast to
343 /// GenericValue *. It is not a pointer to a GenericValue containing the
344 /// address at which to store Val.
345 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
348 void InitializeMemory(const Constant *Init, void *Addr);
350 /// recompileAndRelinkFunction - This method is used to force a function which
351 /// has already been compiled to be compiled again, possibly after it has been
352 /// modified. Then the entry to the old copy is overwritten with a branch to
353 /// the new copy. If there was no old copy, this acts just like
354 /// VM::getPointerToFunction().
355 virtual void *recompileAndRelinkFunction(Function *F) = 0;
357 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
358 /// corresponding to the machine code emitted to execute this function, useful
359 /// for garbage-collecting generated code.
360 virtual void freeMachineCodeForFunction(Function *F) = 0;
362 /// getOrEmitGlobalVariable - Return the address of the specified global
363 /// variable, possibly emitting it to memory if needed. This is used by the
365 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
366 return getPointerToGlobal((const GlobalValue *)GV);
369 /// Registers a listener to be called back on various events within
370 /// the JIT. See JITEventListener.h for more details. Does not
371 /// take ownership of the argument. The argument may be NULL, in
372 /// which case these functions do nothing.
373 virtual void RegisterJITEventListener(JITEventListener *) {}
374 virtual void UnregisterJITEventListener(JITEventListener *) {}
376 /// Sets the pre-compiled object cache. The ownership of the ObjectCache is
377 /// not changed. Supported by MCJIT but not JIT.
378 virtual void setObjectCache(ObjectCache *) {
379 llvm_unreachable("No support for an object cache");
382 /// DisableLazyCompilation - When lazy compilation is off (the default), the
383 /// JIT will eagerly compile every function reachable from the argument to
384 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
385 /// compile the one function and emit stubs to compile the rest when they're
386 /// first called. If lazy compilation is turned off again while some lazy
387 /// stubs are still around, and one of those stubs is called, the program will
390 /// In order to safely compile lazily in a threaded program, the user must
391 /// ensure that 1) only one thread at a time can call any particular lazy
392 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
393 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
394 /// lazy stub. See http://llvm.org/PR5184 for details.
395 void DisableLazyCompilation(bool Disabled = true) {
396 CompilingLazily = !Disabled;
398 bool isCompilingLazily() const {
399 return CompilingLazily;
401 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
402 // Remove this in LLVM 2.8.
403 bool isLazyCompilationDisabled() const {
404 return !CompilingLazily;
407 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
408 /// allocate space and populate a GlobalVariable that is not internal to
410 void DisableGVCompilation(bool Disabled = true) {
411 GVCompilationDisabled = Disabled;
413 bool isGVCompilationDisabled() const {
414 return GVCompilationDisabled;
417 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
418 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
419 /// resolve symbols in a custom way.
420 void DisableSymbolSearching(bool Disabled = true) {
421 SymbolSearchingDisabled = Disabled;
423 bool isSymbolSearchingDisabled() const {
424 return SymbolSearchingDisabled;
427 /// InstallLazyFunctionCreator - If an unknown function is needed, the
428 /// specified function pointer is invoked to create it. If it returns null,
429 /// the JIT will abort.
430 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
431 LazyFunctionCreator = P;
434 /// InstallExceptionTableRegister - The JIT will use the given function
435 /// to register the exception tables it generates.
436 void InstallExceptionTableRegister(EERegisterFn F) {
437 ExceptionTableRegister = F;
439 void InstallExceptionTableDeregister(EERegisterFn F) {
440 ExceptionTableDeregister = F;
443 /// RegisterTable - Registers the given pointer as an exception table. It
444 /// uses the ExceptionTableRegister function.
445 void RegisterTable(const Function *fn, void* res) {
446 if (ExceptionTableRegister) {
447 ExceptionTableRegister(res);
448 AllExceptionTables[fn] = res;
452 /// DeregisterTable - Deregisters the exception frame previously registered
453 /// for the given function.
454 void DeregisterTable(const Function *Fn) {
455 if (ExceptionTableDeregister) {
456 DenseMap<const Function*, void*>::iterator frame =
457 AllExceptionTables.find(Fn);
458 if(frame != AllExceptionTables.end()) {
459 ExceptionTableDeregister(frame->second);
460 AllExceptionTables.erase(frame);
465 /// DeregisterAllTables - Deregisters all previously registered pointers to an
466 /// exception tables. It uses the ExceptionTableoDeregister function.
467 void DeregisterAllTables();
470 explicit ExecutionEngine(Module *M);
474 void EmitGlobalVariable(const GlobalVariable *GV);
476 GenericValue getConstantValue(const Constant *C);
477 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
481 namespace EngineKind {
482 // These are actually bitmasks that get or-ed together.
487 const static Kind Either = (Kind)(JIT | Interpreter);
490 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
491 /// stack-allocating a builder, chaining the various set* methods, and
492 /// terminating it with a .create() call.
493 class EngineBuilder {
496 EngineKind::Kind WhichEngine;
497 std::string *ErrorStr;
498 CodeGenOpt::Level OptLevel;
499 JITMemoryManager *JMM;
500 bool AllocateGVsWithCode;
501 TargetOptions Options;
502 Reloc::Model RelocModel;
503 CodeModel::Model CMModel;
506 SmallVector<std::string, 4> MAttrs;
509 /// InitEngine - Does the common initialization of default options.
511 WhichEngine = EngineKind::Either;
513 OptLevel = CodeGenOpt::Default;
515 Options = TargetOptions();
516 AllocateGVsWithCode = false;
517 RelocModel = Reloc::Default;
518 CMModel = CodeModel::JITDefault;
523 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
524 /// is successful, the created engine takes ownership of the module.
525 EngineBuilder(Module *m) : M(m) {
529 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
530 /// or whichever engine works. This option defaults to EngineKind::Either.
531 EngineBuilder &setEngineKind(EngineKind::Kind w) {
536 /// setJITMemoryManager - Sets the memory manager to use. This allows
537 /// clients to customize their memory allocation policies. If create() is
538 /// called and is successful, the created engine takes ownership of the
539 /// memory manager. This option defaults to NULL.
540 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
545 /// setErrorStr - Set the error string to write to on error. This option
546 /// defaults to NULL.
547 EngineBuilder &setErrorStr(std::string *e) {
552 /// setOptLevel - Set the optimization level for the JIT. This option
553 /// defaults to CodeGenOpt::Default.
554 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
559 /// setTargetOptions - Set the target options that the ExecutionEngine
560 /// target is using. Defaults to TargetOptions().
561 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
566 /// setRelocationModel - Set the relocation model that the ExecutionEngine
567 /// target is using. Defaults to target specific default "Reloc::Default".
568 EngineBuilder &setRelocationModel(Reloc::Model RM) {
573 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
574 /// data is using. Defaults to target specific default
575 /// "CodeModel::JITDefault".
576 EngineBuilder &setCodeModel(CodeModel::Model M) {
581 /// setAllocateGVsWithCode - Sets whether global values should be allocated
582 /// into the same buffer as code. For most applications this should be set
583 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
584 /// and is probably unsafe and bad for performance. However, we have clients
585 /// who depend on this behavior, so we must support it. This option defaults
586 /// to false so that users of the new API can safely use the new memory
587 /// manager and free machine code.
588 EngineBuilder &setAllocateGVsWithCode(bool a) {
589 AllocateGVsWithCode = a;
593 /// setMArch - Override the architecture set by the Module's triple.
594 EngineBuilder &setMArch(StringRef march) {
595 MArch.assign(march.begin(), march.end());
599 /// setMCPU - Target a specific cpu type.
600 EngineBuilder &setMCPU(StringRef mcpu) {
601 MCPU.assign(mcpu.begin(), mcpu.end());
605 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
607 EngineBuilder &setUseMCJIT(bool Value) {
612 /// setMAttrs - Set cpu-specific attributes.
613 template<typename StringSequence>
614 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
616 MAttrs.append(mattrs.begin(), mattrs.end());
620 TargetMachine *selectTarget();
622 /// selectTarget - Pick a target either via -march or by guessing the native
623 /// arch. Add any CPU features specified via -mcpu or -mattr.
624 TargetMachine *selectTarget(const Triple &TargetTriple,
627 const SmallVectorImpl<std::string>& MAttrs);
629 ExecutionEngine *create() {
630 return create(selectTarget());
633 ExecutionEngine *create(TargetMachine *TM);
636 // Create wrappers for C Binding types (see CBindingWrapping.h).
637 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
639 } // End llvm namespace