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/ADT/ValueMap.h"
22 #include "llvm/MC/MCCodeGenInfo.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/ValueHandle.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;
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 RTDyldMemoryManager *MCJMM,
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 &);
156 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
157 /// JITEmitter classes. It must be held while changing the internal state of
158 /// any of those classes.
161 //===--------------------------------------------------------------------===//
162 // ExecutionEngine Startup
163 //===--------------------------------------------------------------------===//
165 virtual ~ExecutionEngine();
167 /// create - This is the factory method for creating an execution engine which
168 /// is appropriate for the current machine. This takes ownership of the
171 /// \param GVsWithCode - Allocating globals with code breaks
172 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
173 /// However, we have clients who depend on this behavior, so we must support
174 /// it. Eventually, when we're willing to break some backwards compatibility,
175 /// this flag should be flipped to false, so that by default
176 /// freeMachineCodeForFunction works.
177 static ExecutionEngine *create(Module *M,
178 bool ForceInterpreter = false,
179 std::string *ErrorStr = 0,
180 CodeGenOpt::Level OptLevel =
182 bool GVsWithCode = true);
184 /// createJIT - This is the factory method for creating a JIT for the current
185 /// machine, it does not fall back to the interpreter. This takes ownership
186 /// of the Module and JITMemoryManager if successful.
188 /// Clients should make sure to initialize targets prior to calling this
190 static ExecutionEngine *createJIT(Module *M,
191 std::string *ErrorStr = 0,
192 JITMemoryManager *JMM = 0,
193 CodeGenOpt::Level OptLevel =
195 bool GVsWithCode = true,
196 Reloc::Model RM = Reloc::Default,
197 CodeModel::Model CMM =
198 CodeModel::JITDefault);
200 /// addModule - Add a Module to the list of modules that we can JIT from.
201 /// Note that this takes ownership of the Module: when the ExecutionEngine is
202 /// destroyed, it destroys the Module as well.
203 virtual void addModule(Module *M) {
204 Modules.push_back(M);
207 //===--------------------------------------------------------------------===//
209 const DataLayout *getDataLayout() const { return TD; }
211 /// removeModule - Remove a Module from the list of modules. Returns true if
213 virtual bool removeModule(Module *M);
215 /// FindFunctionNamed - Search all of the active modules to find the one that
216 /// defines FnName. This is very slow operation and shouldn't be used for
218 Function *FindFunctionNamed(const char *FnName);
220 /// runFunction - Execute the specified function with the specified arguments,
221 /// and return the result.
222 virtual GenericValue runFunction(Function *F,
223 const std::vector<GenericValue> &ArgValues) = 0;
225 /// getPointerToNamedFunction - This method returns the address of the
226 /// specified function by using the dlsym function call. As such it is only
227 /// useful for resolving library symbols, not code generated symbols.
229 /// If AbortOnFailure is false and no function with the given name is
230 /// found, this function silently returns a null pointer. Otherwise,
231 /// it prints a message to stderr and aborts.
233 /// This function is deprecated for the MCJIT execution engine.
235 virtual void *getPointerToNamedFunction(const std::string &Name,
236 bool AbortOnFailure = true) = 0;
238 /// mapSectionAddress - map a section to its target address space value.
239 /// Map the address of a JIT section as returned from the memory manager
240 /// to the address in the target process as the running code will see it.
241 /// This is the address which will be used for relocation resolution.
242 virtual void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
243 llvm_unreachable("Re-mapping of section addresses not supported with this "
247 /// generateCodeForModule - Run code generationen for the specified module and
248 /// load it into memory.
250 /// When this function has completed, all code and data for the specified
251 /// module, and any module on which this module depends, will be generated
252 /// and loaded into memory, but relocations will not yet have been applied
253 /// and all memory will be readable and writable but not executable.
255 /// This function is primarily useful when generating code for an external
256 /// target, allowing the client an opportunity to remap section addresses
257 /// before relocations are applied. Clients that intend to execute code
258 /// locally can use the getFunctionAddress call, which will generate code
259 /// and apply final preparations all in one step.
261 /// This method has no effect for the legacy JIT engine or the interpeter.
262 virtual void generateCodeForModule(Module *M) {}
264 /// finalizeObject - ensure the module is fully processed and is usable.
266 /// It is the user-level function for completing the process of making the
267 /// object usable for execution. It should be called after sections within an
268 /// object have been relocated using mapSectionAddress. When this method is
269 /// called the MCJIT execution engine will reapply relocations for a loaded
270 /// object. This method has no effect for the legacy JIT engine or the
272 virtual void finalizeObject() {}
274 /// runStaticConstructorsDestructors - This method is used to execute all of
275 /// the static constructors or destructors for a program.
277 /// \param isDtors - Run the destructors instead of constructors.
278 void runStaticConstructorsDestructors(bool isDtors);
280 /// runStaticConstructorsDestructors - This method is used to execute all of
281 /// the static constructors or destructors for a particular module.
283 /// \param isDtors - Run the destructors instead of constructors.
284 void runStaticConstructorsDestructors(Module *module, bool isDtors);
287 /// runFunctionAsMain - This is a helper function which wraps runFunction to
288 /// handle the common task of starting up main with the specified argc, argv,
289 /// and envp parameters.
290 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
291 const char * const * envp);
294 /// addGlobalMapping - Tell the execution engine that the specified global is
295 /// at the specified location. This is used internally as functions are JIT'd
296 /// and as global variables are laid out in memory. It can and should also be
297 /// used by clients of the EE that want to have an LLVM global overlay
298 /// existing data in memory. Mappings are automatically removed when their
299 /// GlobalValue is destroyed.
300 void addGlobalMapping(const GlobalValue *GV, void *Addr);
302 /// clearAllGlobalMappings - Clear all global mappings and start over again,
303 /// for use in dynamic compilation scenarios to move globals.
304 void clearAllGlobalMappings();
306 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
307 /// particular module, because it has been removed from the JIT.
308 void clearGlobalMappingsFromModule(Module *M);
310 /// updateGlobalMapping - Replace an existing mapping for GV with a new
311 /// address. This updates both maps as required. If "Addr" is null, the
312 /// entry for the global is removed from the mappings. This returns the old
313 /// value of the pointer, or null if it was not in the map.
314 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
316 /// getPointerToGlobalIfAvailable - This returns the address of the specified
317 /// global value if it is has already been codegen'd, otherwise it returns
320 /// This function is deprecated for the MCJIT execution engine. It doesn't
321 /// seem to be needed in that case, but an equivalent can be added if it is.
322 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
324 /// getPointerToGlobal - This returns the address of the specified global
325 /// value. This may involve code generation if it's a function.
327 /// This function is deprecated for the MCJIT execution engine. Use
328 /// getGlobalValueAddress instead.
329 void *getPointerToGlobal(const GlobalValue *GV);
331 /// getPointerToFunction - The different EE's represent function bodies in
332 /// different ways. They should each implement this to say what a function
333 /// pointer should look like. When F is destroyed, the ExecutionEngine will
334 /// remove its global mapping and free any machine code. Be sure no threads
335 /// are running inside F when that happens.
337 /// This function is deprecated for the MCJIT execution engine. Use
338 /// getFunctionAddress instead.
339 virtual void *getPointerToFunction(Function *F) = 0;
341 /// getPointerToBasicBlock - The different EE's represent basic blocks in
342 /// different ways. Return the representation for a blockaddress of the
345 /// This function will not be implemented for the MCJIT execution engine.
346 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
348 /// getPointerToFunctionOrStub - If the specified function has been
349 /// code-gen'd, return a pointer to the function. If not, compile it, or use
350 /// a stub to implement lazy compilation if available. See
351 /// getPointerToFunction for the requirements on destroying F.
353 /// This function is deprecated for the MCJIT execution engine. Use
354 /// getFunctionAddress instead.
355 virtual void *getPointerToFunctionOrStub(Function *F) {
356 // Default implementation, just codegen the function.
357 return getPointerToFunction(F);
360 /// getGlobalValueAddress - Return the address of the specified global
361 /// value. This may involve code generation.
363 /// This function should not be called with the JIT or interpreter engines.
364 virtual uint64_t getGlobalValueAddress(const std::string &Name) {
365 // Default implementation for JIT and interpreter. MCJIT will override this.
366 // JIT and interpreter clients should use getPointerToGlobal instead.
370 /// getFunctionAddress - Return the address of the specified function.
371 /// This may involve code generation.
372 virtual uint64_t getFunctionAddress(const std::string &Name) {
373 // Default implementation for JIT and interpreter. MCJIT will override this.
374 // JIT and interpreter clients should use getPointerToFunction instead.
378 // The JIT overrides a version that actually does this.
379 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
381 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
382 /// at the specified address.
384 const GlobalValue *getGlobalValueAtAddress(void *Addr);
386 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
387 /// Ptr is the address of the memory at which to store Val, cast to
388 /// GenericValue *. It is not a pointer to a GenericValue containing the
389 /// address at which to store Val.
390 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
393 void InitializeMemory(const Constant *Init, void *Addr);
395 /// recompileAndRelinkFunction - This method is used to force a function which
396 /// has already been compiled to be compiled again, possibly after it has been
397 /// modified. Then the entry to the old copy is overwritten with a branch to
398 /// the new copy. If there was no old copy, this acts just like
399 /// VM::getPointerToFunction().
400 virtual void *recompileAndRelinkFunction(Function *F) = 0;
402 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
403 /// corresponding to the machine code emitted to execute this function, useful
404 /// for garbage-collecting generated code.
405 virtual void freeMachineCodeForFunction(Function *F) = 0;
407 /// getOrEmitGlobalVariable - Return the address of the specified global
408 /// variable, possibly emitting it to memory if needed. This is used by the
411 /// This function is deprecated for the MCJIT execution engine. Use
412 /// getGlobalValueAddress instead.
413 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
414 return getPointerToGlobal((const GlobalValue *)GV);
417 /// Registers a listener to be called back on various events within
418 /// the JIT. See JITEventListener.h for more details. Does not
419 /// take ownership of the argument. The argument may be NULL, in
420 /// which case these functions do nothing.
421 virtual void RegisterJITEventListener(JITEventListener *) {}
422 virtual void UnregisterJITEventListener(JITEventListener *) {}
424 /// Sets the pre-compiled object cache. The ownership of the ObjectCache is
425 /// not changed. Supported by MCJIT but not JIT.
426 virtual void setObjectCache(ObjectCache *) {
427 llvm_unreachable("No support for an object cache");
430 /// DisableLazyCompilation - When lazy compilation is off (the default), the
431 /// JIT will eagerly compile every function reachable from the argument to
432 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
433 /// compile the one function and emit stubs to compile the rest when they're
434 /// first called. If lazy compilation is turned off again while some lazy
435 /// stubs are still around, and one of those stubs is called, the program will
438 /// In order to safely compile lazily in a threaded program, the user must
439 /// ensure that 1) only one thread at a time can call any particular lazy
440 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
441 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
442 /// lazy stub. See http://llvm.org/PR5184 for details.
443 void DisableLazyCompilation(bool Disabled = true) {
444 CompilingLazily = !Disabled;
446 bool isCompilingLazily() const {
447 return CompilingLazily;
449 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
450 // Remove this in LLVM 2.8.
451 bool isLazyCompilationDisabled() const {
452 return !CompilingLazily;
455 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
456 /// allocate space and populate a GlobalVariable that is not internal to
458 void DisableGVCompilation(bool Disabled = true) {
459 GVCompilationDisabled = Disabled;
461 bool isGVCompilationDisabled() const {
462 return GVCompilationDisabled;
465 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
466 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
467 /// resolve symbols in a custom way.
468 void DisableSymbolSearching(bool Disabled = true) {
469 SymbolSearchingDisabled = Disabled;
471 bool isSymbolSearchingDisabled() const {
472 return SymbolSearchingDisabled;
475 /// InstallLazyFunctionCreator - If an unknown function is needed, the
476 /// specified function pointer is invoked to create it. If it returns null,
477 /// the JIT will abort.
478 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
479 LazyFunctionCreator = P;
483 explicit ExecutionEngine(Module *M);
487 void EmitGlobalVariable(const GlobalVariable *GV);
489 GenericValue getConstantValue(const Constant *C);
490 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
494 namespace EngineKind {
495 // These are actually bitmasks that get or-ed together.
500 const static Kind Either = (Kind)(JIT | Interpreter);
503 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
504 /// stack-allocating a builder, chaining the various set* methods, and
505 /// terminating it with a .create() call.
506 class EngineBuilder {
509 EngineKind::Kind WhichEngine;
510 std::string *ErrorStr;
511 CodeGenOpt::Level OptLevel;
512 RTDyldMemoryManager *MCJMM;
513 JITMemoryManager *JMM;
514 bool AllocateGVsWithCode;
515 TargetOptions Options;
516 Reloc::Model RelocModel;
517 CodeModel::Model CMModel;
520 SmallVector<std::string, 4> MAttrs;
523 /// InitEngine - Does the common initialization of default options.
525 WhichEngine = EngineKind::Either;
527 OptLevel = CodeGenOpt::Default;
530 Options = TargetOptions();
531 AllocateGVsWithCode = false;
532 RelocModel = Reloc::Default;
533 CMModel = CodeModel::JITDefault;
538 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
539 /// is successful, the created engine takes ownership of the module.
540 EngineBuilder(Module *m) : M(m) {
544 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
545 /// or whichever engine works. This option defaults to EngineKind::Either.
546 EngineBuilder &setEngineKind(EngineKind::Kind w) {
551 /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
552 /// clients to customize their memory allocation policies for the MCJIT. This
553 /// is only appropriate for the MCJIT; setting this and configuring the builder
554 /// to create anything other than MCJIT will cause a runtime error. If create()
555 /// is called and is successful, the created engine takes ownership of the
556 /// memory manager. This option defaults to NULL. Using this option nullifies
557 /// the setJITMemoryManager() option.
558 EngineBuilder &setMCJITMemoryManager(RTDyldMemoryManager *mcjmm) {
564 /// setJITMemoryManager - Sets the JIT memory manager to use. This allows
565 /// clients to customize their memory allocation policies. This is only
566 /// appropriate for either JIT or MCJIT; setting this and configuring the
567 /// builder to create an interpreter will cause a runtime error. If create()
568 /// is called and is successful, the created engine takes ownership of the
569 /// memory manager. This option defaults to NULL. This option overrides
570 /// setMCJITMemoryManager() as well.
571 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
577 /// setErrorStr - Set the error string to write to on error. This option
578 /// defaults to NULL.
579 EngineBuilder &setErrorStr(std::string *e) {
584 /// setOptLevel - Set the optimization level for the JIT. This option
585 /// defaults to CodeGenOpt::Default.
586 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
591 /// setTargetOptions - Set the target options that the ExecutionEngine
592 /// target is using. Defaults to TargetOptions().
593 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
598 /// setRelocationModel - Set the relocation model that the ExecutionEngine
599 /// target is using. Defaults to target specific default "Reloc::Default".
600 EngineBuilder &setRelocationModel(Reloc::Model RM) {
605 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
606 /// data is using. Defaults to target specific default
607 /// "CodeModel::JITDefault".
608 EngineBuilder &setCodeModel(CodeModel::Model M) {
613 /// setAllocateGVsWithCode - Sets whether global values should be allocated
614 /// into the same buffer as code. For most applications this should be set
615 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
616 /// and is probably unsafe and bad for performance. However, we have clients
617 /// who depend on this behavior, so we must support it. This option defaults
618 /// to false so that users of the new API can safely use the new memory
619 /// manager and free machine code.
620 EngineBuilder &setAllocateGVsWithCode(bool a) {
621 AllocateGVsWithCode = a;
625 /// setMArch - Override the architecture set by the Module's triple.
626 EngineBuilder &setMArch(StringRef march) {
627 MArch.assign(march.begin(), march.end());
631 /// setMCPU - Target a specific cpu type.
632 EngineBuilder &setMCPU(StringRef mcpu) {
633 MCPU.assign(mcpu.begin(), mcpu.end());
637 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
639 EngineBuilder &setUseMCJIT(bool Value) {
644 /// setMAttrs - Set cpu-specific attributes.
645 template<typename StringSequence>
646 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
648 MAttrs.append(mattrs.begin(), mattrs.end());
652 TargetMachine *selectTarget();
654 /// selectTarget - Pick a target either via -march or by guessing the native
655 /// arch. Add any CPU features specified via -mcpu or -mattr.
656 TargetMachine *selectTarget(const Triple &TargetTriple,
659 const SmallVectorImpl<std::string>& MAttrs);
661 ExecutionEngine *create() {
662 return create(selectTarget());
665 ExecutionEngine *create(TargetMachine *TM);
668 // Create wrappers for C Binding types (see CBindingWrapping.h).
669 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
671 } // End llvm namespace