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, MCJIT, 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 virtual 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 /// FIXME: the JIT and MCJIT interfaces should be disentangled or united
236 /// again, if possible.
238 virtual void *getPointerToNamedFunction(const std::string &Name,
239 bool AbortOnFailure = true) = 0;
241 /// mapSectionAddress - map a section to its target address space value.
242 /// Map the address of a JIT section as returned from the memory manager
243 /// to the address in the target process as the running code will see it.
244 /// This is the address which will be used for relocation resolution.
245 virtual void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
246 llvm_unreachable("Re-mapping of section addresses not supported with this "
250 /// generateCodeForModule - Run code generationen for the specified module and
251 /// load it into memory.
253 /// When this function has completed, all code and data for the specified
254 /// module, and any module on which this module depends, will be generated
255 /// and loaded into memory, but relocations will not yet have been applied
256 /// and all memory will be readable and writable but not executable.
258 /// This function is primarily useful when generating code for an external
259 /// target, allowing the client an opportunity to remap section addresses
260 /// before relocations are applied. Clients that intend to execute code
261 /// locally can use the getFunctionAddress call, which will generate code
262 /// and apply final preparations all in one step.
264 /// This method has no effect for the legacy JIT engine or the interpeter.
265 virtual void generateCodeForModule(Module *M) {}
267 /// finalizeObject - ensure the module is fully processed and is usable.
269 /// It is the user-level function for completing the process of making the
270 /// object usable for execution. It should be called after sections within an
271 /// object have been relocated using mapSectionAddress. When this method is
272 /// called the MCJIT execution engine will reapply relocations for a loaded
273 /// object. This method has no effect for the legacy JIT engine or the
275 virtual void finalizeObject() {}
277 /// runStaticConstructorsDestructors - This method is used to execute all of
278 /// the static constructors or destructors for a program.
280 /// \param isDtors - Run the destructors instead of constructors.
281 virtual void runStaticConstructorsDestructors(bool isDtors);
283 /// runStaticConstructorsDestructors - This method is used to execute all of
284 /// the static constructors or destructors for a particular module.
286 /// \param isDtors - Run the destructors instead of constructors.
287 void runStaticConstructorsDestructors(Module *module, bool isDtors);
290 /// runFunctionAsMain - This is a helper function which wraps runFunction to
291 /// handle the common task of starting up main with the specified argc, argv,
292 /// and envp parameters.
293 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
294 const char * const * envp);
297 /// addGlobalMapping - Tell the execution engine that the specified global is
298 /// at the specified location. This is used internally as functions are JIT'd
299 /// and as global variables are laid out in memory. It can and should also be
300 /// used by clients of the EE that want to have an LLVM global overlay
301 /// existing data in memory. Mappings are automatically removed when their
302 /// GlobalValue is destroyed.
303 void addGlobalMapping(const GlobalValue *GV, void *Addr);
305 /// clearAllGlobalMappings - Clear all global mappings and start over again,
306 /// for use in dynamic compilation scenarios to move globals.
307 void clearAllGlobalMappings();
309 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
310 /// particular module, because it has been removed from the JIT.
311 void clearGlobalMappingsFromModule(Module *M);
313 /// updateGlobalMapping - Replace an existing mapping for GV with a new
314 /// address. This updates both maps as required. If "Addr" is null, the
315 /// entry for the global is removed from the mappings. This returns the old
316 /// value of the pointer, or null if it was not in the map.
317 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
319 /// getPointerToGlobalIfAvailable - This returns the address of the specified
320 /// global value if it is has already been codegen'd, otherwise it returns
323 /// This function is deprecated for the MCJIT execution engine. It doesn't
324 /// seem to be needed in that case, but an equivalent can be added if it is.
325 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
327 /// getPointerToGlobal - This returns the address of the specified global
328 /// value. This may involve code generation if it's a function.
330 /// This function is deprecated for the MCJIT execution engine. Use
331 /// getGlobalValueAddress instead.
332 void *getPointerToGlobal(const GlobalValue *GV);
334 /// getPointerToFunction - The different EE's represent function bodies in
335 /// different ways. They should each implement this to say what a function
336 /// pointer should look like. When F is destroyed, the ExecutionEngine will
337 /// remove its global mapping and free any machine code. Be sure no threads
338 /// are running inside F when that happens.
340 /// This function is deprecated for the MCJIT execution engine. Use
341 /// getFunctionAddress instead.
342 virtual void *getPointerToFunction(Function *F) = 0;
344 /// getPointerToBasicBlock - The different EE's represent basic blocks in
345 /// different ways. Return the representation for a blockaddress of the
348 /// This function will not be implemented for the MCJIT execution engine.
349 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
351 /// getPointerToFunctionOrStub - If the specified function has been
352 /// code-gen'd, return a pointer to the function. If not, compile it, or use
353 /// a stub to implement lazy compilation if available. See
354 /// getPointerToFunction for the requirements on destroying F.
356 /// This function is deprecated for the MCJIT execution engine. Use
357 /// getFunctionAddress instead.
358 virtual void *getPointerToFunctionOrStub(Function *F) {
359 // Default implementation, just codegen the function.
360 return getPointerToFunction(F);
363 /// getGlobalValueAddress - Return the address of the specified global
364 /// value. This may involve code generation.
366 /// This function should not be called with the JIT or interpreter engines.
367 virtual uint64_t getGlobalValueAddress(const std::string &Name) {
368 // Default implementation for JIT and interpreter. MCJIT will override this.
369 // JIT and interpreter clients should use getPointerToGlobal instead.
373 /// getFunctionAddress - Return the address of the specified function.
374 /// This may involve code generation.
375 virtual uint64_t getFunctionAddress(const std::string &Name) {
376 // Default implementation for JIT and interpreter. MCJIT will override this.
377 // JIT and interpreter clients should use getPointerToFunction instead.
381 // The JIT overrides a version that actually does this.
382 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
384 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
385 /// at the specified address.
387 const GlobalValue *getGlobalValueAtAddress(void *Addr);
389 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
390 /// Ptr is the address of the memory at which to store Val, cast to
391 /// GenericValue *. It is not a pointer to a GenericValue containing the
392 /// address at which to store Val.
393 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
396 void InitializeMemory(const Constant *Init, void *Addr);
398 /// recompileAndRelinkFunction - This method is used to force a function which
399 /// has already been compiled to be compiled again, possibly after it has been
400 /// modified. Then the entry to the old copy is overwritten with a branch to
401 /// the new copy. If there was no old copy, this acts just like
402 /// VM::getPointerToFunction().
403 virtual void *recompileAndRelinkFunction(Function *F) = 0;
405 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
406 /// corresponding to the machine code emitted to execute this function, useful
407 /// for garbage-collecting generated code.
408 virtual void freeMachineCodeForFunction(Function *F) = 0;
410 /// getOrEmitGlobalVariable - Return the address of the specified global
411 /// variable, possibly emitting it to memory if needed. This is used by the
414 /// This function is deprecated for the MCJIT execution engine. Use
415 /// getGlobalValueAddress instead.
416 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
417 return getPointerToGlobal((const GlobalValue *)GV);
420 /// Registers a listener to be called back on various events within
421 /// the JIT. See JITEventListener.h for more details. Does not
422 /// take ownership of the argument. The argument may be NULL, in
423 /// which case these functions do nothing.
424 virtual void RegisterJITEventListener(JITEventListener *) {}
425 virtual void UnregisterJITEventListener(JITEventListener *) {}
427 /// Sets the pre-compiled object cache. The ownership of the ObjectCache is
428 /// not changed. Supported by MCJIT but not JIT.
429 virtual void setObjectCache(ObjectCache *) {
430 llvm_unreachable("No support for an object cache");
433 /// DisableLazyCompilation - When lazy compilation is off (the default), the
434 /// JIT will eagerly compile every function reachable from the argument to
435 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
436 /// compile the one function and emit stubs to compile the rest when they're
437 /// first called. If lazy compilation is turned off again while some lazy
438 /// stubs are still around, and one of those stubs is called, the program will
441 /// In order to safely compile lazily in a threaded program, the user must
442 /// ensure that 1) only one thread at a time can call any particular lazy
443 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
444 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
445 /// lazy stub. See http://llvm.org/PR5184 for details.
446 void DisableLazyCompilation(bool Disabled = true) {
447 CompilingLazily = !Disabled;
449 bool isCompilingLazily() const {
450 return CompilingLazily;
452 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
453 // Remove this in LLVM 2.8.
454 bool isLazyCompilationDisabled() const {
455 return !CompilingLazily;
458 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
459 /// allocate space and populate a GlobalVariable that is not internal to
461 void DisableGVCompilation(bool Disabled = true) {
462 GVCompilationDisabled = Disabled;
464 bool isGVCompilationDisabled() const {
465 return GVCompilationDisabled;
468 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
469 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
470 /// resolve symbols in a custom way.
471 void DisableSymbolSearching(bool Disabled = true) {
472 SymbolSearchingDisabled = Disabled;
474 bool isSymbolSearchingDisabled() const {
475 return SymbolSearchingDisabled;
478 /// InstallLazyFunctionCreator - If an unknown function is needed, the
479 /// specified function pointer is invoked to create it. If it returns null,
480 /// the JIT will abort.
481 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
482 LazyFunctionCreator = P;
486 explicit ExecutionEngine(Module *M);
490 void EmitGlobalVariable(const GlobalVariable *GV);
492 GenericValue getConstantValue(const Constant *C);
493 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
497 namespace EngineKind {
498 // These are actually bitmasks that get or-ed together.
503 const static Kind Either = (Kind)(JIT | Interpreter);
506 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
507 /// stack-allocating a builder, chaining the various set* methods, and
508 /// terminating it with a .create() call.
509 class EngineBuilder {
512 EngineKind::Kind WhichEngine;
513 std::string *ErrorStr;
514 CodeGenOpt::Level OptLevel;
515 RTDyldMemoryManager *MCJMM;
516 JITMemoryManager *JMM;
517 bool AllocateGVsWithCode;
518 TargetOptions Options;
519 Reloc::Model RelocModel;
520 CodeModel::Model CMModel;
523 SmallVector<std::string, 4> MAttrs;
526 /// InitEngine - Does the common initialization of default options.
528 WhichEngine = EngineKind::Either;
530 OptLevel = CodeGenOpt::Default;
533 Options = TargetOptions();
534 AllocateGVsWithCode = false;
535 RelocModel = Reloc::Default;
536 CMModel = CodeModel::JITDefault;
541 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
542 /// is successful, the created engine takes ownership of the module.
543 EngineBuilder(Module *m) : M(m) {
547 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
548 /// or whichever engine works. This option defaults to EngineKind::Either.
549 EngineBuilder &setEngineKind(EngineKind::Kind w) {
554 /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
555 /// clients to customize their memory allocation policies for the MCJIT. This
556 /// is only appropriate for the MCJIT; setting this and configuring the builder
557 /// to create anything other than MCJIT will cause a runtime error. If create()
558 /// is called and is successful, the created engine takes ownership of the
559 /// memory manager. This option defaults to NULL. Using this option nullifies
560 /// the setJITMemoryManager() option.
561 EngineBuilder &setMCJITMemoryManager(RTDyldMemoryManager *mcjmm) {
567 /// setJITMemoryManager - Sets the JIT memory manager to use. This allows
568 /// clients to customize their memory allocation policies. This is only
569 /// appropriate for either JIT or MCJIT; setting this and configuring the
570 /// builder to create an interpreter will cause a runtime error. If create()
571 /// is called and is successful, the created engine takes ownership of the
572 /// memory manager. This option defaults to NULL. This option overrides
573 /// setMCJITMemoryManager() as well.
574 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
580 /// setErrorStr - Set the error string to write to on error. This option
581 /// defaults to NULL.
582 EngineBuilder &setErrorStr(std::string *e) {
587 /// setOptLevel - Set the optimization level for the JIT. This option
588 /// defaults to CodeGenOpt::Default.
589 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
594 /// setTargetOptions - Set the target options that the ExecutionEngine
595 /// target is using. Defaults to TargetOptions().
596 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
601 /// setRelocationModel - Set the relocation model that the ExecutionEngine
602 /// target is using. Defaults to target specific default "Reloc::Default".
603 EngineBuilder &setRelocationModel(Reloc::Model RM) {
608 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
609 /// data is using. Defaults to target specific default
610 /// "CodeModel::JITDefault".
611 EngineBuilder &setCodeModel(CodeModel::Model M) {
616 /// setAllocateGVsWithCode - Sets whether global values should be allocated
617 /// into the same buffer as code. For most applications this should be set
618 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
619 /// and is probably unsafe and bad for performance. However, we have clients
620 /// who depend on this behavior, so we must support it. This option defaults
621 /// to false so that users of the new API can safely use the new memory
622 /// manager and free machine code.
623 EngineBuilder &setAllocateGVsWithCode(bool a) {
624 AllocateGVsWithCode = a;
628 /// setMArch - Override the architecture set by the Module's triple.
629 EngineBuilder &setMArch(StringRef march) {
630 MArch.assign(march.begin(), march.end());
634 /// setMCPU - Target a specific cpu type.
635 EngineBuilder &setMCPU(StringRef mcpu) {
636 MCPU.assign(mcpu.begin(), mcpu.end());
640 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
642 EngineBuilder &setUseMCJIT(bool Value) {
647 /// setMAttrs - Set cpu-specific attributes.
648 template<typename StringSequence>
649 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
651 MAttrs.append(mattrs.begin(), mattrs.end());
655 TargetMachine *selectTarget();
657 /// selectTarget - Pick a target either via -march or by guessing the native
658 /// arch. Add any CPU features specified via -mcpu or -mattr.
659 TargetMachine *selectTarget(const Triple &TargetTriple,
662 const SmallVectorImpl<std::string>& MAttrs);
664 ExecutionEngine *create() {
665 return create(selectTarget());
668 ExecutionEngine *create(TargetMachine *TM);
671 // Create wrappers for C Binding types (see CBindingWrapping.h).
672 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
674 } // End llvm namespace