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/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/IR/ValueHandle.h"
22 #include "llvm/IR/ValueMap.h"
23 #include "llvm/MC/MCCodeGenInfo.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetOptions.h"
37 class ExecutionEngine;
41 class JITEventListener;
42 class JITMemoryManager;
43 class MachineCodeInfo;
47 class RTDyldMemoryManager;
56 /// \brief Helper class for helping synchronize access to the global address map
57 /// table. Access to this class should be serialized under a mutex.
58 class ExecutionEngineState {
60 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
61 typedef ExecutionEngineState *ExtraData;
62 static sys::Mutex *getMutex(ExecutionEngineState *EES);
63 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
64 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
68 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
74 /// GlobalAddressMap - A mapping between LLVM global values and their
75 /// actualized version...
76 GlobalAddressMapTy GlobalAddressMap;
78 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
79 /// used to convert raw addresses into the LLVM global value that is emitted
80 /// at the address. This map is not computed unless getGlobalValueAtAddress
81 /// is called at some point.
82 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
85 ExecutionEngineState(ExecutionEngine &EE);
87 GlobalAddressMapTy &getGlobalAddressMap() {
88 return GlobalAddressMap;
91 std::map<void*, AssertingVH<const GlobalValue> > &
92 getGlobalAddressReverseMap() {
93 return GlobalAddressReverseMap;
96 /// \brief Erase an entry from the mapping table.
98 /// \returns The address that \p ToUnmap was happed to.
99 void *RemoveMapping(const GlobalValue *ToUnmap);
102 /// \brief Abstract interface for implementation execution of LLVM modules,
103 /// designed to support both interpreter and just-in-time (JIT) compiler
105 class ExecutionEngine {
106 /// The state object holding the global address mapping, which must be
107 /// accessed synchronously.
109 // FIXME: There is no particular need the entire map needs to be
110 // synchronized. Wouldn't a reader-writer design be better here?
111 ExecutionEngineState EEState;
113 /// The target data for the platform for which execution is being performed.
114 const DataLayout *DL;
116 /// Whether lazy JIT compilation is enabled.
117 bool CompilingLazily;
119 /// Whether JIT compilation of external global variables is allowed.
120 bool GVCompilationDisabled;
122 /// Whether the JIT should perform lookups of external symbols (e.g.,
124 bool SymbolSearchingDisabled;
126 /// Whether the JIT should verify IR modules during compilation.
129 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
132 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
133 /// optimize for the case where there is only one module.
134 SmallVector<Module*, 1> Modules;
136 void setDataLayout(const DataLayout *Val) { DL = Val; }
138 /// getMemoryforGV - Allocate memory for a global variable.
139 virtual char *getMemoryForGV(const GlobalVariable *GV);
141 // To avoid having libexecutionengine depend on the JIT and interpreter
142 // libraries, the execution engine implementations set these functions to ctor
143 // pointers at startup time if they are linked in.
144 static ExecutionEngine *(*JITCtor)(
146 std::string *ErrorStr,
147 JITMemoryManager *JMM,
150 static ExecutionEngine *(*MCJITCtor)(
152 std::string *ErrorStr,
153 RTDyldMemoryManager *MCJMM,
155 static ExecutionEngine *(*InterpCtor)(Module *M, std::string *ErrorStr);
157 /// LazyFunctionCreator - If an unknown function is needed, this function
158 /// pointer is invoked to create it. If this returns null, the JIT will
160 void *(*LazyFunctionCreator)(const std::string &);
163 /// lock - This lock protects the ExecutionEngine, MCJIT, JIT, JITResolver and
164 /// JITEmitter classes. It must be held while changing the internal state of
165 /// any of those classes.
168 //===--------------------------------------------------------------------===//
169 // ExecutionEngine Startup
170 //===--------------------------------------------------------------------===//
172 virtual ~ExecutionEngine();
174 /// addModule - Add a Module to the list of modules that we can JIT from.
175 /// Note that this takes ownership of the Module: when the ExecutionEngine is
176 /// destroyed, it destroys the Module as well.
177 virtual void addModule(Module *M) {
178 Modules.push_back(M);
181 /// addObjectFile - Add an ObjectFile to the execution engine.
183 /// This method is only supported by MCJIT. MCJIT will immediately load the
184 /// object into memory and adds its symbols to the list used to resolve
185 /// external symbols while preparing other objects for execution.
187 /// Objects added using this function will not be made executable until
188 /// needed by another object.
190 /// MCJIT will take ownership of the ObjectFile.
191 virtual void addObjectFile(std::unique_ptr<object::ObjectFile> O);
193 /// addArchive - Add an Archive to the execution engine.
195 /// This method is only supported by MCJIT. MCJIT will use the archive to
196 /// resolve external symbols in objects it is loading. If a symbol is found
197 /// in the Archive the contained object file will be extracted (in memory)
198 /// and loaded for possible execution.
200 /// MCJIT will take ownership of the Archive.
201 virtual void addArchive(object::Archive *A) {
202 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
205 //===--------------------------------------------------------------------===//
207 const DataLayout *getDataLayout() const { return DL; }
209 /// removeModule - Remove a Module from the list of modules. Returns true if
211 virtual bool removeModule(Module *M);
213 /// FindFunctionNamed - Search all of the active modules to find the one that
214 /// defines FnName. This is very slow operation and shouldn't be used for
216 virtual Function *FindFunctionNamed(const char *FnName);
218 /// runFunction - Execute the specified function with the specified arguments,
219 /// and return the result.
220 virtual GenericValue runFunction(Function *F,
221 const std::vector<GenericValue> &ArgValues) = 0;
223 /// getPointerToNamedFunction - This method returns the address of the
224 /// specified function by using the dlsym function call. As such it is only
225 /// useful for resolving library symbols, not code generated symbols.
227 /// If AbortOnFailure is false and no function with the given name is
228 /// found, this function silently returns a null pointer. Otherwise,
229 /// it prints a message to stderr and aborts.
231 /// This function is deprecated for the MCJIT execution engine.
233 /// FIXME: the JIT and MCJIT interfaces should be disentangled or united
234 /// again, if possible.
236 virtual void *getPointerToNamedFunction(const std::string &Name,
237 bool AbortOnFailure = true) = 0;
239 /// mapSectionAddress - map a section to its target address space value.
240 /// Map the address of a JIT section as returned from the memory manager
241 /// to the address in the target process as the running code will see it.
242 /// This is the address which will be used for relocation resolution.
243 virtual void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
244 llvm_unreachable("Re-mapping of section addresses not supported with this "
248 /// generateCodeForModule - Run code generationen for the specified module and
249 /// load it into memory.
251 /// When this function has completed, all code and data for the specified
252 /// module, and any module on which this module depends, will be generated
253 /// and loaded into memory, but relocations will not yet have been applied
254 /// and all memory will be readable and writable but not executable.
256 /// This function is primarily useful when generating code for an external
257 /// target, allowing the client an opportunity to remap section addresses
258 /// before relocations are applied. Clients that intend to execute code
259 /// locally can use the getFunctionAddress call, which will generate code
260 /// and apply final preparations all in one step.
262 /// This method has no effect for the legacy JIT engine or the interpeter.
263 virtual void generateCodeForModule(Module *M) {}
265 /// finalizeObject - ensure the module is fully processed and is usable.
267 /// It is the user-level function for completing the process of making the
268 /// object usable for execution. It should be called after sections within an
269 /// object have been relocated using mapSectionAddress. When this method is
270 /// called the MCJIT execution engine will reapply relocations for a loaded
271 /// object. This method has no effect for the legacy JIT engine or the
273 virtual void finalizeObject() {}
275 /// runStaticConstructorsDestructors - This method is used to execute all of
276 /// the static constructors or destructors for a program.
278 /// \param isDtors - Run the destructors instead of constructors.
279 virtual void runStaticConstructorsDestructors(bool isDtors);
281 /// runStaticConstructorsDestructors - This method is used to execute all of
282 /// the static constructors or destructors for a particular module.
284 /// \param isDtors - Run the destructors instead of constructors.
285 void runStaticConstructorsDestructors(Module *module, bool isDtors);
288 /// runFunctionAsMain - This is a helper function which wraps runFunction to
289 /// handle the common task of starting up main with the specified argc, argv,
290 /// and envp parameters.
291 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
292 const char * const * envp);
295 /// addGlobalMapping - Tell the execution engine that the specified global is
296 /// at the specified location. This is used internally as functions are JIT'd
297 /// and as global variables are laid out in memory. It can and should also be
298 /// used by clients of the EE that want to have an LLVM global overlay
299 /// existing data in memory. Mappings are automatically removed when their
300 /// GlobalValue is destroyed.
301 void addGlobalMapping(const GlobalValue *GV, void *Addr);
303 /// clearAllGlobalMappings - Clear all global mappings and start over again,
304 /// for use in dynamic compilation scenarios to move globals.
305 void clearAllGlobalMappings();
307 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
308 /// particular module, because it has been removed from the JIT.
309 void clearGlobalMappingsFromModule(Module *M);
311 /// updateGlobalMapping - Replace an existing mapping for GV with a new
312 /// address. This updates both maps as required. If "Addr" is null, the
313 /// entry for the global is removed from the mappings. This returns the old
314 /// value of the pointer, or null if it was not in the map.
315 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
317 /// getPointerToGlobalIfAvailable - This returns the address of the specified
318 /// global value if it is has already been codegen'd, otherwise it returns
321 /// This function is deprecated for the MCJIT execution engine. It doesn't
322 /// seem to be needed in that case, but an equivalent can be added if it is.
323 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
325 /// getPointerToGlobal - This returns the address of the specified global
326 /// value. This may involve code generation if it's a function.
328 /// This function is deprecated for the MCJIT execution engine. Use
329 /// getGlobalValueAddress instead.
330 void *getPointerToGlobal(const GlobalValue *GV);
332 /// getPointerToFunction - The different EE's represent function bodies in
333 /// different ways. They should each implement this to say what a function
334 /// pointer should look like. When F is destroyed, the ExecutionEngine will
335 /// remove its global mapping and free any machine code. Be sure no threads
336 /// are running inside F when that happens.
338 /// This function is deprecated for the MCJIT execution engine. Use
339 /// getFunctionAddress instead.
340 virtual void *getPointerToFunction(Function *F) = 0;
342 /// getPointerToBasicBlock - The different EE's represent basic blocks in
343 /// different ways. Return the representation for a blockaddress of the
346 /// This function will not be implemented for the MCJIT execution engine.
347 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
349 /// getPointerToFunctionOrStub - If the specified function has been
350 /// code-gen'd, return a pointer to the function. If not, compile it, or use
351 /// a stub to implement lazy compilation if available. See
352 /// getPointerToFunction for the requirements on destroying F.
354 /// This function is deprecated for the MCJIT execution engine. Use
355 /// getFunctionAddress instead.
356 virtual void *getPointerToFunctionOrStub(Function *F) {
357 // Default implementation, just codegen the function.
358 return getPointerToFunction(F);
361 /// getGlobalValueAddress - Return the address of the specified global
362 /// value. This may involve code generation.
364 /// This function should not be called with the JIT or interpreter engines.
365 virtual uint64_t getGlobalValueAddress(const std::string &Name) {
366 // Default implementation for JIT and interpreter. MCJIT will override this.
367 // JIT and interpreter clients should use getPointerToGlobal instead.
371 /// getFunctionAddress - Return the address of the specified function.
372 /// This may involve code generation.
373 virtual uint64_t getFunctionAddress(const std::string &Name) {
374 // Default implementation for JIT and interpreter. MCJIT will override this.
375 // JIT and interpreter clients should use getPointerToFunction instead.
379 // The JIT overrides a version that actually does this.
380 virtual void runJITOnFunction(Function *, MachineCodeInfo * = nullptr) { }
382 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
383 /// at the specified address.
385 const GlobalValue *getGlobalValueAtAddress(void *Addr);
387 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
388 /// Ptr is the address of the memory at which to store Val, cast to
389 /// GenericValue *. It is not a pointer to a GenericValue containing the
390 /// address at which to store Val.
391 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
394 void InitializeMemory(const Constant *Init, void *Addr);
396 /// recompileAndRelinkFunction - This method is used to force a function which
397 /// has already been compiled to be compiled again, possibly after it has been
398 /// modified. Then the entry to the old copy is overwritten with a branch to
399 /// the new copy. If there was no old copy, this acts just like
400 /// VM::getPointerToFunction().
401 virtual void *recompileAndRelinkFunction(Function *F) = 0;
403 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
404 /// corresponding to the machine code emitted to execute this function, useful
405 /// for garbage-collecting generated code.
406 virtual void freeMachineCodeForFunction(Function *F) = 0;
408 /// getOrEmitGlobalVariable - Return the address of the specified global
409 /// variable, possibly emitting it to memory if needed. This is used by the
412 /// This function is deprecated for the MCJIT execution engine. Use
413 /// getGlobalValueAddress instead.
414 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
415 return getPointerToGlobal((const GlobalValue *)GV);
418 /// Registers a listener to be called back on various events within
419 /// the JIT. See JITEventListener.h for more details. Does not
420 /// take ownership of the argument. The argument may be NULL, in
421 /// which case these functions do nothing.
422 virtual void RegisterJITEventListener(JITEventListener *) {}
423 virtual void UnregisterJITEventListener(JITEventListener *) {}
425 /// Sets the pre-compiled object cache. The ownership of the ObjectCache is
426 /// not changed. Supported by MCJIT but not JIT.
427 virtual void setObjectCache(ObjectCache *) {
428 llvm_unreachable("No support for an object cache");
431 /// setProcessAllSections (MCJIT Only): By default, only sections that are
432 /// "required for execution" are passed to the RTDyldMemoryManager, and other
433 /// sections are discarded. Passing 'true' to this method will cause
434 /// RuntimeDyld to pass all sections to its RTDyldMemoryManager regardless
435 /// of whether they are "required to execute" in the usual sense.
437 /// Rationale: Some MCJIT clients want to be able to inspect metadata
438 /// sections (e.g. Dwarf, Stack-maps) to enable functionality or analyze
439 /// performance. Passing these sections to the memory manager allows the
440 /// client to make policy about the relevant sections, rather than having
442 virtual void setProcessAllSections(bool ProcessAllSections) {
443 llvm_unreachable("No support for ProcessAllSections option");
446 /// Return the target machine (if available).
447 virtual TargetMachine *getTargetMachine() { return nullptr; }
449 /// DisableLazyCompilation - When lazy compilation is off (the default), the
450 /// JIT will eagerly compile every function reachable from the argument to
451 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
452 /// compile the one function and emit stubs to compile the rest when they're
453 /// first called. If lazy compilation is turned off again while some lazy
454 /// stubs are still around, and one of those stubs is called, the program will
457 /// In order to safely compile lazily in a threaded program, the user must
458 /// ensure that 1) only one thread at a time can call any particular lazy
459 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
460 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
461 /// lazy stub. See http://llvm.org/PR5184 for details.
462 void DisableLazyCompilation(bool Disabled = true) {
463 CompilingLazily = !Disabled;
465 bool isCompilingLazily() const {
466 return CompilingLazily;
468 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
469 // Remove this in LLVM 2.8.
470 bool isLazyCompilationDisabled() const {
471 return !CompilingLazily;
474 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
475 /// allocate space and populate a GlobalVariable that is not internal to
477 void DisableGVCompilation(bool Disabled = true) {
478 GVCompilationDisabled = Disabled;
480 bool isGVCompilationDisabled() const {
481 return GVCompilationDisabled;
484 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
485 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
486 /// resolve symbols in a custom way.
487 void DisableSymbolSearching(bool Disabled = true) {
488 SymbolSearchingDisabled = Disabled;
490 bool isSymbolSearchingDisabled() const {
491 return SymbolSearchingDisabled;
494 /// Enable/Disable IR module verification.
496 /// Note: Module verification is enabled by default in Debug builds, and
497 /// disabled by default in Release. Use this method to override the default.
498 void setVerifyModules(bool Verify) {
499 VerifyModules = Verify;
501 bool getVerifyModules() const {
502 return VerifyModules;
505 /// InstallLazyFunctionCreator - If an unknown function is needed, the
506 /// specified function pointer is invoked to create it. If it returns null,
507 /// the JIT will abort.
508 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
509 LazyFunctionCreator = P;
513 explicit ExecutionEngine(Module *M);
517 void EmitGlobalVariable(const GlobalVariable *GV);
519 GenericValue getConstantValue(const Constant *C);
520 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
524 namespace EngineKind {
525 // These are actually bitmasks that get or-ed together.
530 const static Kind Either = (Kind)(JIT | Interpreter);
533 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
534 /// stack-allocating a builder, chaining the various set* methods, and
535 /// terminating it with a .create() call.
536 class EngineBuilder {
539 EngineKind::Kind WhichEngine;
540 std::string *ErrorStr;
541 CodeGenOpt::Level OptLevel;
542 RTDyldMemoryManager *MCJMM;
543 JITMemoryManager *JMM;
544 bool AllocateGVsWithCode;
545 TargetOptions Options;
546 Reloc::Model RelocModel;
547 CodeModel::Model CMModel;
550 SmallVector<std::string, 4> MAttrs;
554 /// InitEngine - Does the common initialization of default options.
558 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
559 /// is successful, the created engine takes ownership of the module.
560 EngineBuilder(Module *m) : M(m) {
564 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
565 /// or whichever engine works. This option defaults to EngineKind::Either.
566 EngineBuilder &setEngineKind(EngineKind::Kind w) {
571 /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
572 /// clients to customize their memory allocation policies for the MCJIT. This
573 /// is only appropriate for the MCJIT; setting this and configuring the builder
574 /// to create anything other than MCJIT will cause a runtime error. If create()
575 /// is called and is successful, the created engine takes ownership of the
576 /// memory manager. This option defaults to NULL. Using this option nullifies
577 /// the setJITMemoryManager() option.
578 EngineBuilder &setMCJITMemoryManager(RTDyldMemoryManager *mcjmm) {
584 /// setJITMemoryManager - Sets the JIT memory manager to use. This allows
585 /// clients to customize their memory allocation policies. This is only
586 /// appropriate for either JIT or MCJIT; setting this and configuring the
587 /// builder to create an interpreter will cause a runtime error. If create()
588 /// is called and is successful, the created engine takes ownership of the
589 /// memory manager. This option defaults to NULL. This option overrides
590 /// setMCJITMemoryManager() as well.
591 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
597 /// setErrorStr - Set the error string to write to on error. This option
598 /// defaults to NULL.
599 EngineBuilder &setErrorStr(std::string *e) {
604 /// setOptLevel - Set the optimization level for the JIT. This option
605 /// defaults to CodeGenOpt::Default.
606 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
611 /// setTargetOptions - Set the target options that the ExecutionEngine
612 /// target is using. Defaults to TargetOptions().
613 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
618 /// setRelocationModel - Set the relocation model that the ExecutionEngine
619 /// target is using. Defaults to target specific default "Reloc::Default".
620 EngineBuilder &setRelocationModel(Reloc::Model RM) {
625 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
626 /// data is using. Defaults to target specific default
627 /// "CodeModel::JITDefault".
628 EngineBuilder &setCodeModel(CodeModel::Model M) {
633 /// setAllocateGVsWithCode - Sets whether global values should be allocated
634 /// into the same buffer as code. For most applications this should be set
635 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
636 /// and is probably unsafe and bad for performance. However, we have clients
637 /// who depend on this behavior, so we must support it. This option defaults
638 /// to false so that users of the new API can safely use the new memory
639 /// manager and free machine code.
640 EngineBuilder &setAllocateGVsWithCode(bool a) {
641 AllocateGVsWithCode = a;
645 /// setMArch - Override the architecture set by the Module's triple.
646 EngineBuilder &setMArch(StringRef march) {
647 MArch.assign(march.begin(), march.end());
651 /// setMCPU - Target a specific cpu type.
652 EngineBuilder &setMCPU(StringRef mcpu) {
653 MCPU.assign(mcpu.begin(), mcpu.end());
657 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
659 EngineBuilder &setUseMCJIT(bool Value) {
664 /// setVerifyModules - Set whether the JIT implementation should verify
665 /// IR modules during compilation.
666 EngineBuilder &setVerifyModules(bool Verify) {
667 VerifyModules = Verify;
671 /// setMAttrs - Set cpu-specific attributes.
672 template<typename StringSequence>
673 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
675 MAttrs.append(mattrs.begin(), mattrs.end());
679 TargetMachine *selectTarget();
681 /// selectTarget - Pick a target either via -march or by guessing the native
682 /// arch. Add any CPU features specified via -mcpu or -mattr.
683 TargetMachine *selectTarget(const Triple &TargetTriple,
686 const SmallVectorImpl<std::string>& MAttrs);
688 ExecutionEngine *create() {
689 return create(selectTarget());
692 ExecutionEngine *create(TargetMachine *TM);
695 // Create wrappers for C Binding types (see CBindingWrapping.h).
696 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
698 } // End llvm namespace