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_EXECUTION_ENGINE_H
16 #define LLVM_EXECUTION_ENGINE_H
18 #include "llvm/MC/MCCodeGenInfo.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/ValueMap.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ValueHandle.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetOptions.h"
36 class ExecutionEngine;
40 class JITEventListener;
41 class JITMemoryManager;
42 class MachineCodeInfo;
49 /// \brief Helper class for helping synchronize access to the global address map
51 class ExecutionEngineState {
53 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
54 typedef ExecutionEngineState *ExtraData;
55 static sys::Mutex *getMutex(ExecutionEngineState *EES);
56 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
57 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
61 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
67 /// GlobalAddressMap - A mapping between LLVM global values and their
68 /// 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<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
78 ExecutionEngineState(ExecutionEngine &EE);
80 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
81 return GlobalAddressMap;
84 std::map<void*, AssertingVH<const GlobalValue> > &
85 getGlobalAddressReverseMap(const MutexGuard &) {
86 return GlobalAddressReverseMap;
89 /// \brief Erase an entry from the mapping table.
91 /// \returns The address that \p ToUnmap was happed to.
92 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
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 *TD;
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 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
122 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
123 /// optimize for the case where there is only one module.
124 SmallVector<Module*, 1> Modules;
126 void setDataLayout(const DataLayout *td) { TD = td; }
128 /// getMemoryforGV - Allocate memory for a global variable.
129 virtual char *getMemoryForGV(const GlobalVariable *GV);
131 // To avoid having libexecutionengine depend on the JIT and interpreter
132 // libraries, the execution engine implementations set these functions to ctor
133 // pointers at startup time if they are linked in.
134 static ExecutionEngine *(*JITCtor)(
136 std::string *ErrorStr,
137 JITMemoryManager *JMM,
140 static ExecutionEngine *(*MCJITCtor)(
142 std::string *ErrorStr,
143 JITMemoryManager *JMM,
146 static ExecutionEngine *(*InterpCtor)(Module *M, std::string *ErrorStr);
148 /// LazyFunctionCreator - If an unknown function is needed, this function
149 /// pointer is invoked to create it. If this returns null, the JIT will
151 void *(*LazyFunctionCreator)(const std::string &);
153 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
154 /// register dwarf tables with this function.
155 typedef void (*EERegisterFn)(void*);
156 EERegisterFn ExceptionTableRegister;
157 EERegisterFn ExceptionTableDeregister;
158 /// This maps functions to their exception tables frames.
159 DenseMap<const Function*, void*> AllExceptionTables;
163 /// lock - This lock protects the ExecutionEngine, 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 /// create - This is the factory method for creating an execution engine which
175 /// is appropriate for the current machine. This takes ownership of the
178 /// \param GVsWithCode - Allocating globals with code breaks
179 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
180 /// However, we have clients who depend on this behavior, so we must support
181 /// it. Eventually, when we're willing to break some backwards compatibility,
182 /// this flag should be flipped to false, so that by default
183 /// freeMachineCodeForFunction works.
184 static ExecutionEngine *create(Module *M,
185 bool ForceInterpreter = false,
186 std::string *ErrorStr = 0,
187 CodeGenOpt::Level OptLevel =
189 bool GVsWithCode = true);
191 /// createJIT - This is the factory method for creating a JIT for the current
192 /// machine, it does not fall back to the interpreter. This takes ownership
193 /// of the Module and JITMemoryManager if successful.
195 /// Clients should make sure to initialize targets prior to calling this
197 static ExecutionEngine *createJIT(Module *M,
198 std::string *ErrorStr = 0,
199 JITMemoryManager *JMM = 0,
200 CodeGenOpt::Level OptLevel =
202 bool GVsWithCode = true,
203 Reloc::Model RM = Reloc::Default,
204 CodeModel::Model CMM =
205 CodeModel::JITDefault);
207 /// addModule - Add a Module to the list of modules that we can JIT from.
208 /// Note that this takes ownership of the Module: when the ExecutionEngine is
209 /// destroyed, it destroys the Module as well.
210 virtual void addModule(Module *M) {
211 Modules.push_back(M);
214 //===--------------------------------------------------------------------===//
216 const DataLayout *getDataLayout() const { return TD; }
218 /// removeModule - Remove a Module from the list of modules. Returns true if
220 virtual bool removeModule(Module *M);
222 /// FindFunctionNamed - Search all of the active modules to find the one that
223 /// defines FnName. This is very slow operation and shouldn't be used for
225 Function *FindFunctionNamed(const char *FnName);
227 /// runFunction - Execute the specified function with the specified arguments,
228 /// and return the result.
229 virtual GenericValue runFunction(Function *F,
230 const std::vector<GenericValue> &ArgValues) = 0;
232 /// getPointerToNamedFunction - This method returns the address of the
233 /// specified function by using the dlsym function call. As such it is only
234 /// useful for resolving library symbols, not code generated symbols.
236 /// If AbortOnFailure is false and no function with the given name is
237 /// found, this function silently returns a null pointer. Otherwise,
238 /// it prints a message to stderr and aborts.
240 virtual void *getPointerToNamedFunction(const std::string &Name,
241 bool AbortOnFailure = true) = 0;
243 /// mapSectionAddress - map a section to its target address space value.
244 /// Map the address of a JIT section as returned from the memory manager
245 /// to the address in the target process as the running code will see it.
246 /// This is the address which will be used for relocation resolution.
247 virtual void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) {
248 llvm_unreachable("Re-mapping of section addresses not supported with this "
252 // finalizeObject - This method should be called after sections within an
253 // object have been relocated using mapSectionAddress. When this method is
254 // called the MCJIT execution engine will reapply relocations for a loaded
255 // object. This method has no effect for the legacy JIT engine or the
257 virtual void finalizeObject() {}
259 /// runStaticConstructorsDestructors - This method is used to execute all of
260 /// the static constructors or destructors for a program.
262 /// \param isDtors - Run the destructors instead of constructors.
263 void runStaticConstructorsDestructors(bool isDtors);
265 /// runStaticConstructorsDestructors - This method is used to execute all of
266 /// the static constructors or destructors for a particular module.
268 /// \param isDtors - Run the destructors instead of constructors.
269 void runStaticConstructorsDestructors(Module *module, bool isDtors);
272 /// runFunctionAsMain - This is a helper function which wraps runFunction to
273 /// handle the common task of starting up main with the specified argc, argv,
274 /// and envp parameters.
275 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
276 const char * const * envp);
279 /// addGlobalMapping - Tell the execution engine that the specified global is
280 /// at the specified location. This is used internally as functions are JIT'd
281 /// and as global variables are laid out in memory. It can and should also be
282 /// used by clients of the EE that want to have an LLVM global overlay
283 /// existing data in memory. Mappings are automatically removed when their
284 /// GlobalValue is destroyed.
285 void addGlobalMapping(const GlobalValue *GV, void *Addr);
287 /// clearAllGlobalMappings - Clear all global mappings and start over again,
288 /// for use in dynamic compilation scenarios to move globals.
289 void clearAllGlobalMappings();
291 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
292 /// particular module, because it has been removed from the JIT.
293 void clearGlobalMappingsFromModule(Module *M);
295 /// updateGlobalMapping - Replace an existing mapping for GV with a new
296 /// address. This updates both maps as required. If "Addr" is null, the
297 /// entry for the global is removed from the mappings. This returns the old
298 /// value of the pointer, or null if it was not in the map.
299 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
301 /// getPointerToGlobalIfAvailable - This returns the address of the specified
302 /// global value if it is has already been codegen'd, otherwise it returns
304 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
306 /// getPointerToGlobal - This returns the address of the specified global
307 /// value. This may involve code generation if it's a function.
308 void *getPointerToGlobal(const GlobalValue *GV);
310 /// getPointerToFunction - The different EE's represent function bodies in
311 /// different ways. They should each implement this to say what a function
312 /// pointer should look like. When F is destroyed, the ExecutionEngine will
313 /// remove its global mapping and free any machine code. Be sure no threads
314 /// are running inside F when that happens.
315 virtual void *getPointerToFunction(Function *F) = 0;
317 /// getPointerToBasicBlock - The different EE's represent basic blocks in
318 /// different ways. Return the representation for a blockaddress of the
320 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
322 /// getPointerToFunctionOrStub - If the specified function has been
323 /// code-gen'd, return a pointer to the function. If not, compile it, or use
324 /// a stub to implement lazy compilation if available. See
325 /// getPointerToFunction for the requirements on destroying F.
326 virtual void *getPointerToFunctionOrStub(Function *F) {
327 // Default implementation, just codegen the function.
328 return getPointerToFunction(F);
331 // The JIT overrides a version that actually does this.
332 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
334 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
335 /// at the specified address.
337 const GlobalValue *getGlobalValueAtAddress(void *Addr);
339 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
340 /// Ptr is the address of the memory at which to store Val, cast to
341 /// GenericValue *. It is not a pointer to a GenericValue containing the
342 /// address at which to store Val.
343 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
346 void InitializeMemory(const Constant *Init, void *Addr);
348 /// recompileAndRelinkFunction - This method is used to force a function which
349 /// has already been compiled to be compiled again, possibly after it has been
350 /// modified. Then the entry to the old copy is overwritten with a branch to
351 /// the new copy. If there was no old copy, this acts just like
352 /// VM::getPointerToFunction().
353 virtual void *recompileAndRelinkFunction(Function *F) = 0;
355 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
356 /// corresponding to the machine code emitted to execute this function, useful
357 /// for garbage-collecting generated code.
358 virtual void freeMachineCodeForFunction(Function *F) = 0;
360 /// getOrEmitGlobalVariable - Return the address of the specified global
361 /// variable, possibly emitting it to memory if needed. This is used by the
363 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
364 return getPointerToGlobal((const GlobalValue *)GV);
367 /// Registers a listener to be called back on various events within
368 /// the JIT. See JITEventListener.h for more details. Does not
369 /// take ownership of the argument. The argument may be NULL, in
370 /// which case these functions do nothing.
371 virtual void RegisterJITEventListener(JITEventListener *) {}
372 virtual void UnregisterJITEventListener(JITEventListener *) {}
374 /// DisableLazyCompilation - When lazy compilation is off (the default), the
375 /// JIT will eagerly compile every function reachable from the argument to
376 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
377 /// compile the one function and emit stubs to compile the rest when they're
378 /// first called. If lazy compilation is turned off again while some lazy
379 /// stubs are still around, and one of those stubs is called, the program will
382 /// In order to safely compile lazily in a threaded program, the user must
383 /// ensure that 1) only one thread at a time can call any particular lazy
384 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
385 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
386 /// lazy stub. See http://llvm.org/PR5184 for details.
387 void DisableLazyCompilation(bool Disabled = true) {
388 CompilingLazily = !Disabled;
390 bool isCompilingLazily() const {
391 return CompilingLazily;
393 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
394 // Remove this in LLVM 2.8.
395 bool isLazyCompilationDisabled() const {
396 return !CompilingLazily;
399 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
400 /// allocate space and populate a GlobalVariable that is not internal to
402 void DisableGVCompilation(bool Disabled = true) {
403 GVCompilationDisabled = Disabled;
405 bool isGVCompilationDisabled() const {
406 return GVCompilationDisabled;
409 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
410 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
411 /// resolve symbols in a custom way.
412 void DisableSymbolSearching(bool Disabled = true) {
413 SymbolSearchingDisabled = Disabled;
415 bool isSymbolSearchingDisabled() const {
416 return SymbolSearchingDisabled;
419 /// InstallLazyFunctionCreator - If an unknown function is needed, the
420 /// specified function pointer is invoked to create it. If it returns null,
421 /// the JIT will abort.
422 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
423 LazyFunctionCreator = P;
426 /// InstallExceptionTableRegister - The JIT will use the given function
427 /// to register the exception tables it generates.
428 void InstallExceptionTableRegister(EERegisterFn F) {
429 ExceptionTableRegister = F;
431 void InstallExceptionTableDeregister(EERegisterFn F) {
432 ExceptionTableDeregister = F;
435 /// RegisterTable - Registers the given pointer as an exception table. It
436 /// uses the ExceptionTableRegister function.
437 void RegisterTable(const Function *fn, void* res) {
438 if (ExceptionTableRegister) {
439 ExceptionTableRegister(res);
440 AllExceptionTables[fn] = res;
444 /// DeregisterTable - Deregisters the exception frame previously registered
445 /// for the given function.
446 void DeregisterTable(const Function *Fn) {
447 if (ExceptionTableDeregister) {
448 DenseMap<const Function*, void*>::iterator frame =
449 AllExceptionTables.find(Fn);
450 if(frame != AllExceptionTables.end()) {
451 ExceptionTableDeregister(frame->second);
452 AllExceptionTables.erase(frame);
457 /// DeregisterAllTables - Deregisters all previously registered pointers to an
458 /// exception tables. It uses the ExceptionTableoDeregister function.
459 void DeregisterAllTables();
462 explicit ExecutionEngine(Module *M);
466 void EmitGlobalVariable(const GlobalVariable *GV);
468 GenericValue getConstantValue(const Constant *C);
469 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
473 namespace EngineKind {
474 // These are actually bitmasks that get or-ed together.
479 const static Kind Either = (Kind)(JIT | Interpreter);
482 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
483 /// stack-allocating a builder, chaining the various set* methods, and
484 /// terminating it with a .create() call.
485 class EngineBuilder {
488 EngineKind::Kind WhichEngine;
489 std::string *ErrorStr;
490 CodeGenOpt::Level OptLevel;
491 JITMemoryManager *JMM;
492 bool AllocateGVsWithCode;
493 TargetOptions Options;
494 Reloc::Model RelocModel;
495 CodeModel::Model CMModel;
498 SmallVector<std::string, 4> MAttrs;
501 /// InitEngine - Does the common initialization of default options.
503 WhichEngine = EngineKind::Either;
505 OptLevel = CodeGenOpt::Default;
507 Options = TargetOptions();
508 AllocateGVsWithCode = false;
509 RelocModel = Reloc::Default;
510 CMModel = CodeModel::JITDefault;
515 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
516 /// is successful, the created engine takes ownership of the module.
517 EngineBuilder(Module *m) : M(m) {
521 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
522 /// or whichever engine works. This option defaults to EngineKind::Either.
523 EngineBuilder &setEngineKind(EngineKind::Kind w) {
528 /// setJITMemoryManager - Sets the memory manager to use. This allows
529 /// clients to customize their memory allocation policies. If create() is
530 /// called and is successful, the created engine takes ownership of the
531 /// memory manager. This option defaults to NULL.
532 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
537 /// setErrorStr - Set the error string to write to on error. This option
538 /// defaults to NULL.
539 EngineBuilder &setErrorStr(std::string *e) {
544 /// setOptLevel - Set the optimization level for the JIT. This option
545 /// defaults to CodeGenOpt::Default.
546 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
551 /// setTargetOptions - Set the target options that the ExecutionEngine
552 /// target is using. Defaults to TargetOptions().
553 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
558 /// setRelocationModel - Set the relocation model that the ExecutionEngine
559 /// target is using. Defaults to target specific default "Reloc::Default".
560 EngineBuilder &setRelocationModel(Reloc::Model RM) {
565 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
566 /// data is using. Defaults to target specific default
567 /// "CodeModel::JITDefault".
568 EngineBuilder &setCodeModel(CodeModel::Model M) {
573 /// setAllocateGVsWithCode - Sets whether global values should be allocated
574 /// into the same buffer as code. For most applications this should be set
575 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
576 /// and is probably unsafe and bad for performance. However, we have clients
577 /// who depend on this behavior, so we must support it. This option defaults
578 /// to false so that users of the new API can safely use the new memory
579 /// manager and free machine code.
580 EngineBuilder &setAllocateGVsWithCode(bool a) {
581 AllocateGVsWithCode = a;
585 /// setMArch - Override the architecture set by the Module's triple.
586 EngineBuilder &setMArch(StringRef march) {
587 MArch.assign(march.begin(), march.end());
591 /// setMCPU - Target a specific cpu type.
592 EngineBuilder &setMCPU(StringRef mcpu) {
593 MCPU.assign(mcpu.begin(), mcpu.end());
597 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
599 EngineBuilder &setUseMCJIT(bool Value) {
604 /// setMAttrs - Set cpu-specific attributes.
605 template<typename StringSequence>
606 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
608 MAttrs.append(mattrs.begin(), mattrs.end());
612 TargetMachine *selectTarget();
614 /// selectTarget - Pick a target either via -march or by guessing the native
615 /// arch. Add any CPU features specified via -mcpu or -mattr.
616 TargetMachine *selectTarget(const Triple &TargetTriple,
619 const SmallVectorImpl<std::string>& MAttrs);
621 ExecutionEngine *create() {
622 return create(selectTarget());
625 ExecutionEngine *create(TargetMachine *TM);
628 } // End llvm namespace