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 "RuntimeDyld.h"
19 #include "llvm-c/ExecutionEngine.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/ValueHandle.h"
24 #include "llvm/IR/ValueMap.h"
25 #include "llvm/MC/MCCodeGenInfo.h"
26 #include "llvm/Object/Binary.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Mutex.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
41 class ExecutionEngine;
45 class JITEventListener;
46 class MachineCodeInfo;
47 class MCJITMemoryManager;
50 class RTDyldMemoryManager;
59 /// \brief Helper class for helping synchronize access to the global address map
60 /// table. Access to this class should be serialized under a mutex.
61 class ExecutionEngineState {
63 typedef StringMap<uint64_t> GlobalAddressMapTy;
67 /// GlobalAddressMap - A mapping between LLVM global symbol names values and
68 /// their actualized version...
69 GlobalAddressMapTy GlobalAddressMap;
71 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
72 /// used to convert raw addresses into the LLVM global value that is emitted
73 /// at the address. This map is not computed unless getGlobalValueAtAddress
74 /// is called at some point.
75 std::map<uint64_t, std::string> GlobalAddressReverseMap;
79 GlobalAddressMapTy &getGlobalAddressMap() {
80 return GlobalAddressMap;
83 std::map<uint64_t, std::string> &getGlobalAddressReverseMap() {
84 return GlobalAddressReverseMap;
87 /// \brief Erase an entry from the mapping table.
89 /// \returns The address that \p ToUnmap was happed to.
90 uint64_t RemoveMapping(StringRef Name);
93 using FunctionCreator = std::function<void *(const std::string &)>;
95 /// \brief Abstract interface for implementation execution of LLVM modules,
96 /// designed to support both interpreter and just-in-time (JIT) compiler
98 class ExecutionEngine {
99 /// The state object holding the global address mapping, which must be
100 /// accessed synchronously.
102 // FIXME: There is no particular need the entire map needs to be
103 // synchronized. Wouldn't a reader-writer design be better here?
104 ExecutionEngineState EEState;
106 /// The target data for the platform for which execution is being performed.
107 const DataLayout *DL;
109 /// Whether lazy JIT compilation is enabled.
110 bool CompilingLazily;
112 /// Whether JIT compilation of external global variables is allowed.
113 bool GVCompilationDisabled;
115 /// Whether the JIT should perform lookups of external symbols (e.g.,
117 bool SymbolSearchingDisabled;
119 /// Whether the JIT should verify IR modules during compilation.
122 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
125 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
126 /// optimize for the case where there is only one module.
127 SmallVector<std::unique_ptr<Module>, 1> Modules;
129 void setDataLayout(const DataLayout *Val) { DL = Val; }
131 /// getMemoryforGV - Allocate memory for a global variable.
132 virtual char *getMemoryForGV(const GlobalVariable *GV);
134 static ExecutionEngine *(*MCJITCtor)(
135 std::unique_ptr<Module> M,
136 std::string *ErrorStr,
137 std::shared_ptr<MCJITMemoryManager> MM,
138 std::shared_ptr<RuntimeDyld::SymbolResolver> SR,
139 std::unique_ptr<TargetMachine> TM);
141 static ExecutionEngine *(*OrcMCJITReplacementCtor)(
142 std::string *ErrorStr,
143 std::shared_ptr<MCJITMemoryManager> MM,
144 std::shared_ptr<RuntimeDyld::SymbolResolver> SR,
145 std::unique_ptr<TargetMachine> TM);
147 static ExecutionEngine *(*InterpCtor)(std::unique_ptr<Module> M,
148 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 FunctionCreator LazyFunctionCreator;
155 /// getMangledName - Get mangled name.
156 std::string getMangledName(const GlobalValue *GV);
159 /// lock - This lock protects the ExecutionEngine and MCJIT classes. It must
160 /// be held while changing the internal state of any of those classes.
163 //===--------------------------------------------------------------------===//
164 // ExecutionEngine Startup
165 //===--------------------------------------------------------------------===//
167 virtual ~ExecutionEngine();
169 /// Add a Module to the list of modules that we can JIT from.
170 virtual void addModule(std::unique_ptr<Module> M) {
171 Modules.push_back(std::move(M));
174 /// addObjectFile - Add an ObjectFile to the execution engine.
176 /// This method is only supported by MCJIT. MCJIT will immediately load the
177 /// object into memory and adds its symbols to the list used to resolve
178 /// external symbols while preparing other objects for execution.
180 /// Objects added using this function will not be made executable until
181 /// needed by another object.
183 /// MCJIT will take ownership of the ObjectFile.
184 virtual void addObjectFile(std::unique_ptr<object::ObjectFile> O);
185 virtual void addObjectFile(object::OwningBinary<object::ObjectFile> O);
187 /// addArchive - Add an Archive to the execution engine.
189 /// This method is only supported by MCJIT. MCJIT will use the archive to
190 /// resolve external symbols in objects it is loading. If a symbol is found
191 /// in the Archive the contained object file will be extracted (in memory)
192 /// and loaded for possible execution.
193 virtual void addArchive(object::OwningBinary<object::Archive> A);
195 //===--------------------------------------------------------------------===//
197 const DataLayout *getDataLayout() const { return DL; }
199 /// removeModule - Remove a Module from the list of modules. Returns true if
201 virtual bool removeModule(Module *M);
203 /// FindFunctionNamed - Search all of the active modules to find the function that
204 /// defines FnName. This is very slow operation and shouldn't be used for
206 virtual Function *FindFunctionNamed(const char *FnName);
208 /// FindGlobalVariableNamed - Search all of the active modules to find the global variable
209 /// that defines Name. This is very slow operation and shouldn't be used for
211 virtual GlobalVariable *FindGlobalVariableNamed(const char *Name, bool AllowInternal = false);
213 /// runFunction - Execute the specified function with the specified arguments,
214 /// and return the result.
215 virtual GenericValue runFunction(Function *F,
216 ArrayRef<GenericValue> ArgValues) = 0;
218 /// getPointerToNamedFunction - This method returns the address of the
219 /// specified function by using the dlsym function call. As such it is only
220 /// useful for resolving library symbols, not code generated symbols.
222 /// If AbortOnFailure is false and no function with the given name is
223 /// found, this function silently returns a null pointer. Otherwise,
224 /// it prints a message to stderr and aborts.
226 /// This function is deprecated for the MCJIT execution engine.
227 virtual void *getPointerToNamedFunction(StringRef Name,
228 bool AbortOnFailure = true) = 0;
230 /// mapSectionAddress - map a section to its target address space value.
231 /// Map the address of a JIT section as returned from the memory manager
232 /// to the address in the target process as the running code will see it.
233 /// This is the address which will be used for relocation resolution.
234 virtual void mapSectionAddress(const void *LocalAddress,
235 uint64_t TargetAddress) {
236 llvm_unreachable("Re-mapping of section addresses not supported with this "
240 /// generateCodeForModule - Run code generation for the specified module and
241 /// load it into memory.
243 /// When this function has completed, all code and data for the specified
244 /// module, and any module on which this module depends, will be generated
245 /// and loaded into memory, but relocations will not yet have been applied
246 /// and all memory will be readable and writable but not executable.
248 /// This function is primarily useful when generating code for an external
249 /// target, allowing the client an opportunity to remap section addresses
250 /// before relocations are applied. Clients that intend to execute code
251 /// locally can use the getFunctionAddress call, which will generate code
252 /// and apply final preparations all in one step.
254 /// This method has no effect for the interpeter.
255 virtual void generateCodeForModule(Module *M) {}
257 /// finalizeObject - ensure the module is fully processed and is usable.
259 /// It is the user-level function for completing the process of making the
260 /// object usable for execution. It should be called after sections within an
261 /// object have been relocated using mapSectionAddress. When this method is
262 /// called the MCJIT execution engine will reapply relocations for a loaded
263 /// object. This method has no effect for the interpeter.
264 virtual void finalizeObject() {}
266 /// runStaticConstructorsDestructors - This method is used to execute all of
267 /// the static constructors or destructors for a program.
269 /// \param isDtors - Run the destructors instead of constructors.
270 virtual void runStaticConstructorsDestructors(bool isDtors);
272 /// This method is used to execute all of the static constructors or
273 /// destructors for a particular module.
275 /// \param isDtors - Run the destructors instead of constructors.
276 void runStaticConstructorsDestructors(Module &module, bool isDtors);
279 /// runFunctionAsMain - This is a helper function which wraps runFunction to
280 /// handle the common task of starting up main with the specified argc, argv,
281 /// and envp parameters.
282 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
283 const char * const * envp);
286 /// addGlobalMapping - Tell the execution engine that the specified global is
287 /// at the specified location. This is used internally as functions are JIT'd
288 /// and as global variables are laid out in memory. It can and should also be
289 /// used by clients of the EE that want to have an LLVM global overlay
290 /// existing data in memory. Mappings are automatically removed when their
291 /// GlobalValue is destroyed.
292 void addGlobalMapping(const GlobalValue *GV, void *Addr);
293 void addGlobalMapping(StringRef Name, uint64_t Addr);
295 /// clearAllGlobalMappings - Clear all global mappings and start over again,
296 /// for use in dynamic compilation scenarios to move globals.
297 void clearAllGlobalMappings();
299 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
300 /// particular module, because it has been removed from the JIT.
301 void clearGlobalMappingsFromModule(Module *M);
303 /// updateGlobalMapping - Replace an existing mapping for GV with a new
304 /// address. This updates both maps as required. If "Addr" is null, the
305 /// entry for the global is removed from the mappings. This returns the old
306 /// value of the pointer, or null if it was not in the map.
307 uint64_t updateGlobalMapping(const GlobalValue *GV, void *Addr);
308 uint64_t updateGlobalMapping(StringRef Name, uint64_t Addr);
310 /// getAddressToGlobalIfAvailable - This returns the address of the specified
312 uint64_t getAddressToGlobalIfAvailable(StringRef S);
314 /// getPointerToGlobalIfAvailable - This returns the address of the specified
315 /// global value if it is has already been codegen'd, otherwise it returns
317 void *getPointerToGlobalIfAvailable(StringRef S);
318 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
320 /// getPointerToGlobal - This returns the address of the specified global
321 /// value. This may involve code generation if it's a function.
323 /// This function is deprecated for the MCJIT execution engine. Use
324 /// getGlobalValueAddress instead.
325 void *getPointerToGlobal(const GlobalValue *GV);
327 /// getPointerToFunction - The different EE's represent function bodies in
328 /// different ways. They should each implement this to say what a function
329 /// pointer should look like. When F is destroyed, the ExecutionEngine will
330 /// remove its global mapping and free any machine code. Be sure no threads
331 /// are running inside F when that happens.
333 /// This function is deprecated for the MCJIT execution engine. Use
334 /// getFunctionAddress instead.
335 virtual void *getPointerToFunction(Function *F) = 0;
337 /// getPointerToFunctionOrStub - If the specified function has been
338 /// code-gen'd, return a pointer to the function. If not, compile it, or use
339 /// a stub to implement lazy compilation if available. See
340 /// getPointerToFunction for the requirements on destroying F.
342 /// This function is deprecated for the MCJIT execution engine. Use
343 /// getFunctionAddress instead.
344 virtual void *getPointerToFunctionOrStub(Function *F) {
345 // Default implementation, just codegen the function.
346 return getPointerToFunction(F);
349 /// getGlobalValueAddress - Return the address of the specified global
350 /// value. This may involve code generation.
352 /// This function should not be called with the interpreter engine.
353 virtual uint64_t getGlobalValueAddress(const std::string &Name) {
354 // Default implementation for the interpreter. MCJIT will override this.
355 // JIT and interpreter clients should use getPointerToGlobal instead.
359 /// getFunctionAddress - Return the address of the specified function.
360 /// This may involve code generation.
361 virtual uint64_t getFunctionAddress(const std::string &Name) {
362 // Default implementation for the interpreter. MCJIT will override this.
363 // Interpreter clients should use getPointerToFunction instead.
367 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
368 /// at the specified address.
370 const GlobalValue *getGlobalValueAtAddress(void *Addr);
372 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
373 /// Ptr is the address of the memory at which to store Val, cast to
374 /// GenericValue *. It is not a pointer to a GenericValue containing the
375 /// address at which to store Val.
376 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
379 void InitializeMemory(const Constant *Init, void *Addr);
381 /// getOrEmitGlobalVariable - Return the address of the specified global
382 /// variable, possibly emitting it to memory if needed. This is used by the
385 /// This function is deprecated for the MCJIT execution engine. Use
386 /// getGlobalValueAddress instead.
387 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
388 return getPointerToGlobal((const GlobalValue *)GV);
391 /// Registers a listener to be called back on various events within
392 /// the JIT. See JITEventListener.h for more details. Does not
393 /// take ownership of the argument. The argument may be NULL, in
394 /// which case these functions do nothing.
395 virtual void RegisterJITEventListener(JITEventListener *) {}
396 virtual void UnregisterJITEventListener(JITEventListener *) {}
398 /// Sets the pre-compiled object cache. The ownership of the ObjectCache is
399 /// not changed. Supported by MCJIT but not the interpreter.
400 virtual void setObjectCache(ObjectCache *) {
401 llvm_unreachable("No support for an object cache");
404 /// setProcessAllSections (MCJIT Only): By default, only sections that are
405 /// "required for execution" are passed to the RTDyldMemoryManager, and other
406 /// sections are discarded. Passing 'true' to this method will cause
407 /// RuntimeDyld to pass all sections to its RTDyldMemoryManager regardless
408 /// of whether they are "required to execute" in the usual sense.
410 /// Rationale: Some MCJIT clients want to be able to inspect metadata
411 /// sections (e.g. Dwarf, Stack-maps) to enable functionality or analyze
412 /// performance. Passing these sections to the memory manager allows the
413 /// client to make policy about the relevant sections, rather than having
415 virtual void setProcessAllSections(bool ProcessAllSections) {
416 llvm_unreachable("No support for ProcessAllSections option");
419 /// Return the target machine (if available).
420 virtual TargetMachine *getTargetMachine() { return nullptr; }
422 /// DisableLazyCompilation - When lazy compilation is off (the default), the
423 /// JIT will eagerly compile every function reachable from the argument to
424 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
425 /// compile the one function and emit stubs to compile the rest when they're
426 /// first called. If lazy compilation is turned off again while some lazy
427 /// stubs are still around, and one of those stubs is called, the program will
430 /// In order to safely compile lazily in a threaded program, the user must
431 /// ensure that 1) only one thread at a time can call any particular lazy
432 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
433 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
434 /// lazy stub. See http://llvm.org/PR5184 for details.
435 void DisableLazyCompilation(bool Disabled = true) {
436 CompilingLazily = !Disabled;
438 bool isCompilingLazily() const {
439 return CompilingLazily;
442 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
443 /// allocate space and populate a GlobalVariable that is not internal to
445 void DisableGVCompilation(bool Disabled = true) {
446 GVCompilationDisabled = Disabled;
448 bool isGVCompilationDisabled() const {
449 return GVCompilationDisabled;
452 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
453 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
454 /// resolve symbols in a custom way.
455 void DisableSymbolSearching(bool Disabled = true) {
456 SymbolSearchingDisabled = Disabled;
458 bool isSymbolSearchingDisabled() const {
459 return SymbolSearchingDisabled;
462 /// Enable/Disable IR module verification.
464 /// Note: Module verification is enabled by default in Debug builds, and
465 /// disabled by default in Release. Use this method to override the default.
466 void setVerifyModules(bool Verify) {
467 VerifyModules = Verify;
469 bool getVerifyModules() const {
470 return VerifyModules;
473 /// InstallLazyFunctionCreator - If an unknown function is needed, the
474 /// specified function pointer is invoked to create it. If it returns null,
475 /// the JIT will abort.
476 void InstallLazyFunctionCreator(FunctionCreator C) {
477 LazyFunctionCreator = C;
482 explicit ExecutionEngine(std::unique_ptr<Module> M);
486 void EmitGlobalVariable(const GlobalVariable *GV);
488 GenericValue getConstantValue(const Constant *C);
489 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
493 namespace EngineKind {
494 // These are actually bitmasks that get or-ed together.
499 const static Kind Either = (Kind)(JIT | Interpreter);
502 /// Builder class for ExecutionEngines. Use this by stack-allocating a builder,
503 /// chaining the various set* methods, and terminating it with a .create()
505 class EngineBuilder {
507 std::unique_ptr<Module> M;
508 EngineKind::Kind WhichEngine;
509 std::string *ErrorStr;
510 CodeGenOpt::Level OptLevel;
511 std::shared_ptr<MCJITMemoryManager> MemMgr;
512 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver;
513 TargetOptions Options;
514 Reloc::Model RelocModel;
515 CodeModel::Model CMModel;
518 SmallVector<std::string, 4> MAttrs;
520 bool UseOrcMCJITReplacement;
523 /// Default constructor for EngineBuilder.
526 /// Constructor for EngineBuilder.
527 EngineBuilder(std::unique_ptr<Module> M);
529 // Out-of-line since we don't have the def'n of RTDyldMemoryManager here.
532 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
533 /// or whichever engine works. This option defaults to EngineKind::Either.
534 EngineBuilder &setEngineKind(EngineKind::Kind w) {
539 /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
540 /// clients to customize their memory allocation policies for the MCJIT. This
541 /// is only appropriate for the MCJIT; setting this and configuring the builder
542 /// to create anything other than MCJIT will cause a runtime error. If create()
543 /// is called and is successful, the created engine takes ownership of the
544 /// memory manager. This option defaults to NULL.
545 EngineBuilder &setMCJITMemoryManager(std::unique_ptr<RTDyldMemoryManager> mcjmm);
548 setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM);
551 setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR);
553 /// setErrorStr - Set the error string to write to on error. This option
554 /// defaults to NULL.
555 EngineBuilder &setErrorStr(std::string *e) {
560 /// setOptLevel - Set the optimization level for the JIT. This option
561 /// defaults to CodeGenOpt::Default.
562 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
567 /// setTargetOptions - Set the target options that the ExecutionEngine
568 /// target is using. Defaults to TargetOptions().
569 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
574 /// setRelocationModel - Set the relocation model that the ExecutionEngine
575 /// target is using. Defaults to target specific default "Reloc::Default".
576 EngineBuilder &setRelocationModel(Reloc::Model RM) {
581 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
582 /// data is using. Defaults to target specific default
583 /// "CodeModel::JITDefault".
584 EngineBuilder &setCodeModel(CodeModel::Model M) {
589 /// setMArch - Override the architecture set by the Module's triple.
590 EngineBuilder &setMArch(StringRef march) {
591 MArch.assign(march.begin(), march.end());
595 /// setMCPU - Target a specific cpu type.
596 EngineBuilder &setMCPU(StringRef mcpu) {
597 MCPU.assign(mcpu.begin(), mcpu.end());
601 /// setVerifyModules - Set whether the JIT implementation should verify
602 /// IR modules during compilation.
603 EngineBuilder &setVerifyModules(bool Verify) {
604 VerifyModules = Verify;
608 /// setMAttrs - Set cpu-specific attributes.
609 template<typename StringSequence>
610 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
612 MAttrs.append(mattrs.begin(), mattrs.end());
616 // \brief Use OrcMCJITReplacement instead of MCJIT. Off by default.
617 void setUseOrcMCJITReplacement(bool UseOrcMCJITReplacement) {
618 this->UseOrcMCJITReplacement = UseOrcMCJITReplacement;
621 TargetMachine *selectTarget();
623 /// selectTarget - Pick a target either via -march or by guessing the native
624 /// arch. Add any CPU features specified via -mcpu or -mattr.
625 TargetMachine *selectTarget(const Triple &TargetTriple,
628 const SmallVectorImpl<std::string>& MAttrs);
630 ExecutionEngine *create() {
631 return create(selectTarget());
634 ExecutionEngine *create(TargetMachine *TM);
637 // Create wrappers for C Binding types (see CBindingWrapping.h).
638 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
640 } // End llvm namespace