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
21 #include "llvm/MC/MCCodeGenInfo.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/ValueMap.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/Support/Mutex.h"
28 #include "llvm/Target/TargetMachine.h"
34 class ExecutionEngine;
38 class JITEventListener;
39 class JITMemoryManager;
40 class MachineCodeInfo;
46 /// \brief Helper class for helping synchronize access to the global address map
48 class ExecutionEngineState {
50 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
51 typedef ExecutionEngineState *ExtraData;
52 static sys::Mutex *getMutex(ExecutionEngineState *EES);
53 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
54 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
58 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
64 /// GlobalAddressMap - A mapping between LLVM global values and their
65 /// actualized version...
66 GlobalAddressMapTy GlobalAddressMap;
68 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
69 /// used to convert raw addresses into the LLVM global value that is emitted
70 /// at the address. This map is not computed unless getGlobalValueAtAddress
71 /// is called at some point.
72 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
75 ExecutionEngineState(ExecutionEngine &EE);
77 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
78 return GlobalAddressMap;
81 std::map<void*, AssertingVH<const GlobalValue> > &
82 getGlobalAddressReverseMap(const MutexGuard &) {
83 return GlobalAddressReverseMap;
86 /// \brief Erase an entry from the mapping table.
88 /// \returns The address that \arg ToUnmap was happed to.
89 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
92 /// \brief Abstract interface for implementation execution of LLVM modules,
93 /// designed to support both interpreter and just-in-time (JIT) compiler
95 class ExecutionEngine {
96 /// The state object holding the global address mapping, which must be
97 /// accessed synchronously.
99 // FIXME: There is no particular need the entire map needs to be
100 // synchronized. Wouldn't a reader-writer design be better here?
101 ExecutionEngineState EEState;
103 /// The target data for the platform for which execution is being performed.
104 const TargetData *TD;
106 /// Whether lazy JIT compilation is enabled.
107 bool CompilingLazily;
109 /// Whether JIT compilation of external global variables is allowed.
110 bool GVCompilationDisabled;
112 /// Whether the JIT should perform lookups of external symbols (e.g.,
114 bool SymbolSearchingDisabled;
116 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
119 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
120 /// optimize for the case where there is only one module.
121 SmallVector<Module*, 1> Modules;
123 void setTargetData(const TargetData *td) {
127 /// getMemoryforGV - Allocate memory for a global variable.
128 virtual char *getMemoryForGV(const GlobalVariable *GV);
130 // To avoid having libexecutionengine depend on the JIT and interpreter
131 // libraries, the execution engine implementations set these functions to ctor
132 // pointers at startup time if they are linked in.
133 static ExecutionEngine *(*JITCtor)(
135 std::string *ErrorStr,
136 JITMemoryManager *JMM,
137 CodeGenOpt::Level OptLevel,
140 static ExecutionEngine *(*MCJITCtor)(
142 std::string *ErrorStr,
143 JITMemoryManager *JMM,
144 CodeGenOpt::Level OptLevel,
147 static ExecutionEngine *(*InterpCtor)(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 void *(*LazyFunctionCreator)(const std::string &);
155 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
156 /// register dwarf tables with this function.
157 typedef void (*EERegisterFn)(void*);
158 EERegisterFn ExceptionTableRegister;
159 EERegisterFn ExceptionTableDeregister;
160 /// This maps functions to their exception tables frames.
161 DenseMap<const Function*, void*> AllExceptionTables;
165 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
166 /// JITEmitter classes. It must be held while changing the internal state of
167 /// any of those classes.
170 //===--------------------------------------------------------------------===//
171 // ExecutionEngine Startup
172 //===--------------------------------------------------------------------===//
174 virtual ~ExecutionEngine();
176 /// create - This is the factory method for creating an execution engine which
177 /// is appropriate for the current machine. This takes ownership of the
180 /// \param GVsWithCode - Allocating globals with code breaks
181 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
182 /// However, we have clients who depend on this behavior, so we must support
183 /// it. Eventually, when we're willing to break some backwards compatibility,
184 /// this flag should be flipped to false, so that by default
185 /// freeMachineCodeForFunction works.
186 static ExecutionEngine *create(Module *M,
187 bool ForceInterpreter = false,
188 std::string *ErrorStr = 0,
189 CodeGenOpt::Level OptLevel =
191 bool GVsWithCode = true);
193 /// createJIT - This is the factory method for creating a JIT for the current
194 /// machine, it does not fall back to the interpreter. This takes ownership
195 /// of the Module and JITMemoryManager if successful.
197 /// Clients should make sure to initialize targets prior to calling this
199 static ExecutionEngine *createJIT(Module *M,
200 std::string *ErrorStr = 0,
201 JITMemoryManager *JMM = 0,
202 CodeGenOpt::Level OptLevel =
204 bool GVsWithCode = true,
205 Reloc::Model RM = Reloc::Default,
206 CodeModel::Model CMM =
207 CodeModel::JITDefault);
209 /// addModule - Add a Module to the list of modules that we can JIT from.
210 /// Note that this takes ownership of the Module: when the ExecutionEngine is
211 /// destroyed, it destroys the Module as well.
212 virtual void addModule(Module *M) {
213 Modules.push_back(M);
216 //===--------------------------------------------------------------------===//
218 const TargetData *getTargetData() const { return TD; }
220 /// removeModule - Remove a Module from the list of modules. Returns true if
222 virtual bool removeModule(Module *M);
224 /// FindFunctionNamed - Search all of the active modules to find the one that
225 /// defines FnName. This is very slow operation and shouldn't be used for
227 Function *FindFunctionNamed(const char *FnName);
229 /// runFunction - Execute the specified function with the specified arguments,
230 /// and return the result.
231 virtual GenericValue runFunction(Function *F,
232 const std::vector<GenericValue> &ArgValues) = 0;
234 /// runStaticConstructorsDestructors - This method is used to execute all of
235 /// the static constructors or destructors for a program.
237 /// \param isDtors - Run the destructors instead of constructors.
238 void runStaticConstructorsDestructors(bool isDtors);
240 /// runStaticConstructorsDestructors - This method is used to execute all of
241 /// the static constructors or destructors for a particular module.
243 /// \param isDtors - Run the destructors instead of constructors.
244 void runStaticConstructorsDestructors(Module *module, bool isDtors);
247 /// runFunctionAsMain - This is a helper function which wraps runFunction to
248 /// handle the common task of starting up main with the specified argc, argv,
249 /// and envp parameters.
250 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
251 const char * const * envp);
254 /// addGlobalMapping - Tell the execution engine that the specified global is
255 /// at the specified location. This is used internally as functions are JIT'd
256 /// and as global variables are laid out in memory. It can and should also be
257 /// used by clients of the EE that want to have an LLVM global overlay
258 /// existing data in memory. Mappings are automatically removed when their
259 /// GlobalValue is destroyed.
260 void addGlobalMapping(const GlobalValue *GV, void *Addr);
262 /// clearAllGlobalMappings - Clear all global mappings and start over again,
263 /// for use in dynamic compilation scenarios to move globals.
264 void clearAllGlobalMappings();
266 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
267 /// particular module, because it has been removed from the JIT.
268 void clearGlobalMappingsFromModule(Module *M);
270 /// updateGlobalMapping - Replace an existing mapping for GV with a new
271 /// address. This updates both maps as required. If "Addr" is null, the
272 /// entry for the global is removed from the mappings. This returns the old
273 /// value of the pointer, or null if it was not in the map.
274 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
276 /// getPointerToGlobalIfAvailable - This returns the address of the specified
277 /// global value if it is has already been codegen'd, otherwise it returns
279 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
281 /// getPointerToGlobal - This returns the address of the specified global
282 /// value. This may involve code generation if it's a function.
283 void *getPointerToGlobal(const GlobalValue *GV);
285 /// getPointerToFunction - The different EE's represent function bodies in
286 /// different ways. They should each implement this to say what a function
287 /// pointer should look like. When F is destroyed, the ExecutionEngine will
288 /// remove its global mapping and free any machine code. Be sure no threads
289 /// are running inside F when that happens.
290 virtual void *getPointerToFunction(Function *F) = 0;
292 /// getPointerToBasicBlock - The different EE's represent basic blocks in
293 /// different ways. Return the representation for a blockaddress of the
295 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
297 /// getPointerToFunctionOrStub - If the specified function has been
298 /// code-gen'd, return a pointer to the function. If not, compile it, or use
299 /// a stub to implement lazy compilation if available. See
300 /// getPointerToFunction for the requirements on destroying F.
301 virtual void *getPointerToFunctionOrStub(Function *F) {
302 // Default implementation, just codegen the function.
303 return getPointerToFunction(F);
306 // The JIT overrides a version that actually does this.
307 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
309 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
310 /// at the specified address.
312 const GlobalValue *getGlobalValueAtAddress(void *Addr);
314 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
315 /// Ptr is the address of the memory at which to store Val, cast to
316 /// GenericValue *. It is not a pointer to a GenericValue containing the
317 /// address at which to store Val.
318 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
321 void InitializeMemory(const Constant *Init, void *Addr);
323 /// recompileAndRelinkFunction - This method is used to force a function which
324 /// has already been compiled to be compiled again, possibly after it has been
325 /// modified. Then the entry to the old copy is overwritten with a branch to
326 /// the new copy. If there was no old copy, this acts just like
327 /// VM::getPointerToFunction().
328 virtual void *recompileAndRelinkFunction(Function *F) = 0;
330 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
331 /// corresponding to the machine code emitted to execute this function, useful
332 /// for garbage-collecting generated code.
333 virtual void freeMachineCodeForFunction(Function *F) = 0;
335 /// getOrEmitGlobalVariable - Return the address of the specified global
336 /// variable, possibly emitting it to memory if needed. This is used by the
338 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
339 return getPointerToGlobal((GlobalValue*)GV);
342 /// Registers a listener to be called back on various events within
343 /// the JIT. See JITEventListener.h for more details. Does not
344 /// take ownership of the argument. The argument may be NULL, in
345 /// which case these functions do nothing.
346 virtual void RegisterJITEventListener(JITEventListener *) {}
347 virtual void UnregisterJITEventListener(JITEventListener *) {}
349 /// DisableLazyCompilation - When lazy compilation is off (the default), the
350 /// JIT will eagerly compile every function reachable from the argument to
351 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
352 /// compile the one function and emit stubs to compile the rest when they're
353 /// first called. If lazy compilation is turned off again while some lazy
354 /// stubs are still around, and one of those stubs is called, the program will
357 /// In order to safely compile lazily in a threaded program, the user must
358 /// ensure that 1) only one thread at a time can call any particular lazy
359 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
360 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
361 /// lazy stub. See http://llvm.org/PR5184 for details.
362 void DisableLazyCompilation(bool Disabled = true) {
363 CompilingLazily = !Disabled;
365 bool isCompilingLazily() const {
366 return CompilingLazily;
368 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
369 // Remove this in LLVM 2.8.
370 bool isLazyCompilationDisabled() const {
371 return !CompilingLazily;
374 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
375 /// allocate space and populate a GlobalVariable that is not internal to
377 void DisableGVCompilation(bool Disabled = true) {
378 GVCompilationDisabled = Disabled;
380 bool isGVCompilationDisabled() const {
381 return GVCompilationDisabled;
384 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
385 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
386 /// resolve symbols in a custom way.
387 void DisableSymbolSearching(bool Disabled = true) {
388 SymbolSearchingDisabled = Disabled;
390 bool isSymbolSearchingDisabled() const {
391 return SymbolSearchingDisabled;
394 /// InstallLazyFunctionCreator - If an unknown function is needed, the
395 /// specified function pointer is invoked to create it. If it returns null,
396 /// the JIT will abort.
397 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
398 LazyFunctionCreator = P;
401 /// InstallExceptionTableRegister - The JIT will use the given function
402 /// to register the exception tables it generates.
403 void InstallExceptionTableRegister(EERegisterFn F) {
404 ExceptionTableRegister = F;
406 void InstallExceptionTableDeregister(EERegisterFn F) {
407 ExceptionTableDeregister = F;
410 /// RegisterTable - Registers the given pointer as an exception table. It
411 /// uses the ExceptionTableRegister function.
412 void RegisterTable(const Function *fn, void* res) {
413 if (ExceptionTableRegister) {
414 ExceptionTableRegister(res);
415 AllExceptionTables[fn] = res;
419 /// DeregisterTable - Deregisters the exception frame previously registered
420 /// for the given function.
421 void DeregisterTable(const Function *Fn) {
422 if (ExceptionTableDeregister) {
423 DenseMap<const Function*, void*>::iterator frame =
424 AllExceptionTables.find(Fn);
425 if(frame != AllExceptionTables.end()) {
426 ExceptionTableDeregister(frame->second);
427 AllExceptionTables.erase(frame);
432 /// DeregisterAllTables - Deregisters all previously registered pointers to an
433 /// exception tables. It uses the ExceptionTableoDeregister function.
434 void DeregisterAllTables();
437 explicit ExecutionEngine(Module *M);
441 void EmitGlobalVariable(const GlobalVariable *GV);
443 GenericValue getConstantValue(const Constant *C);
444 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
448 namespace EngineKind {
449 // These are actually bitmasks that get or-ed together.
454 const static Kind Either = (Kind)(JIT | Interpreter);
457 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
458 /// stack-allocating a builder, chaining the various set* methods, and
459 /// terminating it with a .create() call.
460 class EngineBuilder {
463 EngineKind::Kind WhichEngine;
464 std::string *ErrorStr;
465 CodeGenOpt::Level OptLevel;
466 JITMemoryManager *JMM;
467 bool AllocateGVsWithCode;
468 Reloc::Model RelocModel;
469 CodeModel::Model CMModel;
472 SmallVector<std::string, 4> MAttrs;
475 /// InitEngine - Does the common initialization of default options.
477 WhichEngine = EngineKind::Either;
479 OptLevel = CodeGenOpt::Default;
481 AllocateGVsWithCode = false;
482 RelocModel = Reloc::Default;
483 CMModel = CodeModel::JITDefault;
488 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
489 /// is successful, the created engine takes ownership of the module.
490 EngineBuilder(Module *m) : M(m) {
494 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
495 /// or whichever engine works. This option defaults to EngineKind::Either.
496 EngineBuilder &setEngineKind(EngineKind::Kind w) {
501 /// setJITMemoryManager - Sets the memory manager to use. This allows
502 /// clients to customize their memory allocation policies. If create() is
503 /// called and is successful, the created engine takes ownership of the
504 /// memory manager. This option defaults to NULL.
505 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
510 /// setErrorStr - Set the error string to write to on error. This option
511 /// defaults to NULL.
512 EngineBuilder &setErrorStr(std::string *e) {
517 /// setOptLevel - Set the optimization level for the JIT. This option
518 /// defaults to CodeGenOpt::Default.
519 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
524 /// setRelocationModel - Set the relocation model that the ExecutionEngine
525 /// target is using. Defaults to target specific default "Reloc::Default".
526 EngineBuilder &setRelocationModel(Reloc::Model RM) {
531 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
532 /// data is using. Defaults to target specific default
533 /// "CodeModel::JITDefault".
534 EngineBuilder &setCodeModel(CodeModel::Model M) {
539 /// setAllocateGVsWithCode - Sets whether global values should be allocated
540 /// into the same buffer as code. For most applications this should be set
541 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
542 /// and is probably unsafe and bad for performance. However, we have clients
543 /// who depend on this behavior, so we must support it. This option defaults
544 /// to false so that users of the new API can safely use the new memory
545 /// manager and free machine code.
546 EngineBuilder &setAllocateGVsWithCode(bool a) {
547 AllocateGVsWithCode = a;
551 /// setMArch - Override the architecture set by the Module's triple.
552 EngineBuilder &setMArch(StringRef march) {
553 MArch.assign(march.begin(), march.end());
557 /// setMCPU - Target a specific cpu type.
558 EngineBuilder &setMCPU(StringRef mcpu) {
559 MCPU.assign(mcpu.begin(), mcpu.end());
563 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
565 EngineBuilder &setUseMCJIT(bool Value) {
570 /// setMAttrs - Set cpu-specific attributes.
571 template<typename StringSequence>
572 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
574 MAttrs.append(mattrs.begin(), mattrs.end());
578 /// selectTarget - Pick a target either via -march or by guessing the native
579 /// arch. Add any CPU features specified via -mcpu or -mattr.
580 static TargetMachine *selectTarget(Module *M,
583 const SmallVectorImpl<std::string>& MAttrs,
588 ExecutionEngine *create();
591 } // End llvm namespace