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/ADT/SmallVector.h"
22 #include "llvm/ADT/ValueMap.h"
23 #include "llvm/Support/ValueHandle.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/Target/TargetMachine.h"
31 class ExecutionEngine;
35 class JITEventListener;
36 class JITMemoryManager;
37 class MachineCodeInfo;
44 class ExecutionEngineState {
46 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
47 typedef ExecutionEngineState *ExtraData;
48 static sys::Mutex *getMutex(ExecutionEngineState *EES);
49 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
50 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
54 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
60 /// GlobalAddressMap - A mapping between LLVM global values and their
61 /// actualized version...
62 GlobalAddressMapTy GlobalAddressMap;
64 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
65 /// used to convert raw addresses into the LLVM global value that is emitted
66 /// at the address. This map is not computed unless getGlobalValueAtAddress
67 /// is called at some point.
68 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
71 ExecutionEngineState(ExecutionEngine &EE);
74 getGlobalAddressMap(const MutexGuard &) {
75 return GlobalAddressMap;
78 std::map<void*, AssertingVH<const GlobalValue> > &
79 getGlobalAddressReverseMap(const MutexGuard &) {
80 return GlobalAddressReverseMap;
83 // Returns the address ToUnmap was mapped to.
84 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
88 class ExecutionEngine {
90 ExecutionEngineState EEState;
92 bool GVCompilationDisabled;
93 bool SymbolSearchingDisabled;
95 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
98 /// Modules - This is a list of ModuleProvider's that we are JIT'ing from. We
99 /// use a smallvector to optimize for the case where there is only one module.
100 SmallVector<ModuleProvider*, 1> Modules;
102 void setTargetData(const TargetData *td) {
106 /// getMemoryforGV - Allocate memory for a global variable.
107 virtual char* getMemoryForGV(const GlobalVariable* GV);
109 // To avoid having libexecutionengine depend on the JIT and interpreter
110 // libraries, the JIT and Interpreter set these functions to ctor pointers
111 // at startup time if they are linked in.
112 static ExecutionEngine *(*JITCtor)(ModuleProvider *MP,
113 std::string *ErrorStr,
114 JITMemoryManager *JMM,
115 CodeGenOpt::Level OptLevel,
117 static ExecutionEngine *(*InterpCtor)(ModuleProvider *MP,
118 std::string *ErrorStr);
120 /// LazyFunctionCreator - If an unknown function is needed, this function
121 /// pointer is invoked to create it. If this returns null, the JIT will abort.
122 void* (*LazyFunctionCreator)(const std::string &);
124 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
125 /// register dwarf tables with this function
126 typedef void (*EERegisterFn)(void*);
127 static EERegisterFn ExceptionTableRegister;
130 /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
131 /// JITEmitter classes. It must be held while changing the internal state of
132 /// any of those classes.
133 sys::Mutex lock; // Used to make this class and subclasses thread-safe
135 //===--------------------------------------------------------------------===//
136 // ExecutionEngine Startup
137 //===--------------------------------------------------------------------===//
139 virtual ~ExecutionEngine();
141 /// create - This is the factory method for creating an execution engine which
142 /// is appropriate for the current machine. This takes ownership of the
144 static ExecutionEngine *create(ModuleProvider *MP,
145 bool ForceInterpreter = false,
146 std::string *ErrorStr = 0,
147 CodeGenOpt::Level OptLevel =
149 // Allocating globals with code breaks
150 // freeMachineCodeForFunction and is probably
151 // unsafe and bad for performance. However,
152 // we have clients who depend on this
153 // behavior, so we must support it.
154 // Eventually, when we're willing to break
155 // some backwards compatability, this flag
156 // should be flipped to false, so that by
157 // default freeMachineCodeForFunction works.
158 bool GVsWithCode = true);
160 /// create - This is the factory method for creating an execution engine which
161 /// is appropriate for the current machine. This takes ownership of the
163 static ExecutionEngine *create(Module *M);
165 /// createJIT - This is the factory method for creating a JIT for the current
166 /// machine, it does not fall back to the interpreter. This takes ownership
167 /// of the ModuleProvider and JITMemoryManager if successful.
169 /// Clients should make sure to initialize targets prior to calling this
171 static ExecutionEngine *createJIT(ModuleProvider *MP,
172 std::string *ErrorStr = 0,
173 JITMemoryManager *JMM = 0,
174 CodeGenOpt::Level OptLevel =
176 bool GVsWithCode = true);
178 /// addModuleProvider - Add a ModuleProvider to the list of modules that we
179 /// can JIT from. Note that this takes ownership of the ModuleProvider: when
180 /// the ExecutionEngine is destroyed, it destroys the MP as well.
181 virtual void addModuleProvider(ModuleProvider *P) {
182 Modules.push_back(P);
185 //===----------------------------------------------------------------------===//
187 const TargetData *getTargetData() const { return TD; }
190 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
191 /// Relases the Module from the ModuleProvider, materializing it in the
192 /// process, and returns the materialized Module.
193 virtual Module* removeModuleProvider(ModuleProvider *P,
194 std::string *ErrInfo = 0);
196 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
197 /// and deletes the ModuleProvider and owned Module. Avoids materializing
198 /// the underlying module.
199 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
201 /// FindFunctionNamed - Search all of the active modules to find the one that
202 /// defines FnName. This is very slow operation and shouldn't be used for
204 Function *FindFunctionNamed(const char *FnName);
206 /// runFunction - Execute the specified function with the specified arguments,
207 /// and return the result.
209 virtual GenericValue runFunction(Function *F,
210 const std::vector<GenericValue> &ArgValues) = 0;
212 /// runStaticConstructorsDestructors - This method is used to execute all of
213 /// the static constructors or destructors for a program, depending on the
214 /// value of isDtors.
215 void runStaticConstructorsDestructors(bool isDtors);
216 /// runStaticConstructorsDestructors - This method is used to execute all of
217 /// the static constructors or destructors for a module, depending on the
218 /// value of isDtors.
219 void runStaticConstructorsDestructors(Module *module, bool isDtors);
222 /// runFunctionAsMain - This is a helper function which wraps runFunction to
223 /// handle the common task of starting up main with the specified argc, argv,
224 /// and envp parameters.
225 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
226 const char * const * envp);
229 /// addGlobalMapping - Tell the execution engine that the specified global is
230 /// at the specified location. This is used internally as functions are JIT'd
231 /// and as global variables are laid out in memory. It can and should also be
232 /// used by clients of the EE that want to have an LLVM global overlay
233 /// existing data in memory. Mappings are automatically removed when their
234 /// GlobalValue is destroyed.
235 void addGlobalMapping(const GlobalValue *GV, void *Addr);
237 /// clearAllGlobalMappings - Clear all global mappings and start over again
238 /// use in dynamic compilation scenarios when you want to move globals
239 void clearAllGlobalMappings();
241 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
242 /// particular module, because it has been removed from the JIT.
243 void clearGlobalMappingsFromModule(Module *M);
245 /// updateGlobalMapping - Replace an existing mapping for GV with a new
246 /// address. This updates both maps as required. If "Addr" is null, the
247 /// entry for the global is removed from the mappings. This returns the old
248 /// value of the pointer, or null if it was not in the map.
249 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
251 /// getPointerToGlobalIfAvailable - This returns the address of the specified
252 /// global value if it is has already been codegen'd, otherwise it returns
255 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
257 /// getPointerToGlobal - This returns the address of the specified global
258 /// value. This may involve code generation if it's a function.
260 void *getPointerToGlobal(const GlobalValue *GV);
262 /// getPointerToFunction - The different EE's represent function bodies in
263 /// different ways. They should each implement this to say what a function
264 /// pointer should look like. When F is destroyed, the ExecutionEngine will
265 /// remove its global mapping and free any machine code. Be sure no threads
266 /// are running inside F when that happens.
268 virtual void *getPointerToFunction(Function *F) = 0;
270 /// getPointerToBasicBlock - The different EE's represent basic blocks in
271 /// different ways. Return the representation for a blockaddress of the
274 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
276 /// getPointerToFunctionOrStub - If the specified function has been
277 /// code-gen'd, return a pointer to the function. If not, compile it, or use
278 /// a stub to implement lazy compilation if available. See
279 /// getPointerToFunction for the requirements on destroying F.
281 virtual void *getPointerToFunctionOrStub(Function *F) {
282 // Default implementation, just codegen the function.
283 return getPointerToFunction(F);
286 // The JIT overrides a version that actually does this.
287 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
289 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
290 /// at the specified address.
292 const GlobalValue *getGlobalValueAtAddress(void *Addr);
295 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
297 void InitializeMemory(const Constant *Init, void *Addr);
299 /// recompileAndRelinkFunction - This method is used to force a function
300 /// which has already been compiled to be compiled again, possibly
301 /// after it has been modified. Then the entry to the old copy is overwritten
302 /// with a branch to the new copy. If there was no old copy, this acts
303 /// just like VM::getPointerToFunction().
305 virtual void *recompileAndRelinkFunction(Function *F) = 0;
307 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
308 /// corresponding to the machine code emitted to execute this function, useful
309 /// for garbage-collecting generated code.
311 virtual void freeMachineCodeForFunction(Function *F) = 0;
313 /// getOrEmitGlobalVariable - Return the address of the specified global
314 /// variable, possibly emitting it to memory if needed. This is used by the
316 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
317 return getPointerToGlobal((GlobalValue*)GV);
320 /// Registers a listener to be called back on various events within
321 /// the JIT. See JITEventListener.h for more details. Does not
322 /// take ownership of the argument. The argument may be NULL, in
323 /// which case these functions do nothing.
324 virtual void RegisterJITEventListener(JITEventListener *) {}
325 virtual void UnregisterJITEventListener(JITEventListener *) {}
327 /// DisableLazyCompilation - When lazy compilation is off (the default), the
328 /// JIT will eagerly compile every function reachable from the argument to
329 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
330 /// compile the one function and emit stubs to compile the rest when they're
331 /// first called. If lazy compilation is turned off again while some lazy
332 /// stubs are still around, and one of those stubs is called, the program will
335 /// In order to safely compile lazily in a threaded program, the user must
336 /// ensure that 1) only one thread at a time can call any particular lazy
337 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
338 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
339 /// lazy stub. See http://llvm.org/PR5184 for details.
340 void DisableLazyCompilation(bool Disabled = true) {
341 CompilingLazily = !Disabled;
343 bool isCompilingLazily() const {
344 return CompilingLazily;
346 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
347 // Remove this in LLVM 2.8.
348 bool isLazyCompilationDisabled() const {
349 return !CompilingLazily;
352 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
353 /// allocate space and populate a GlobalVariable that is not internal to
355 void DisableGVCompilation(bool Disabled = true) {
356 GVCompilationDisabled = Disabled;
358 bool isGVCompilationDisabled() const {
359 return GVCompilationDisabled;
362 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
363 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
364 /// resolve symbols in a custom way.
365 void DisableSymbolSearching(bool Disabled = true) {
366 SymbolSearchingDisabled = Disabled;
368 bool isSymbolSearchingDisabled() const {
369 return SymbolSearchingDisabled;
372 /// InstallLazyFunctionCreator - If an unknown function is needed, the
373 /// specified function pointer is invoked to create it. If it returns null,
374 /// the JIT will abort.
375 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
376 LazyFunctionCreator = P;
379 /// InstallExceptionTableRegister - The JIT will use the given function
380 /// to register the exception tables it generates.
381 static void InstallExceptionTableRegister(void (*F)(void*)) {
382 ExceptionTableRegister = F;
385 /// RegisterTable - Registers the given pointer as an exception table. It uses
386 /// the ExceptionTableRegister function.
387 static void RegisterTable(void* res) {
388 if (ExceptionTableRegister)
389 ExceptionTableRegister(res);
393 explicit ExecutionEngine(ModuleProvider *P);
397 // EmitGlobalVariable - This method emits the specified global variable to the
398 // address specified in GlobalAddresses, or allocates new memory if it's not
399 // already in the map.
400 void EmitGlobalVariable(const GlobalVariable *GV);
402 GenericValue getConstantValue(const Constant *C);
403 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
407 namespace EngineKind {
408 // These are actually bitmasks that get or-ed together.
413 const static Kind Either = (Kind)(JIT | Interpreter);
416 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
417 /// stack-allocating a builder, chaining the various set* methods, and
418 /// terminating it with a .create() call.
419 class EngineBuilder {
423 EngineKind::Kind WhichEngine;
424 std::string *ErrorStr;
425 CodeGenOpt::Level OptLevel;
426 JITMemoryManager *JMM;
427 bool AllocateGVsWithCode;
429 /// InitEngine - Does the common initialization of default options.
432 WhichEngine = EngineKind::Either;
434 OptLevel = CodeGenOpt::Default;
436 AllocateGVsWithCode = false;
440 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
441 /// is successful, the created engine takes ownership of the module
443 EngineBuilder(ModuleProvider *mp) : MP(mp) {
447 /// EngineBuilder - Overloaded constructor that automatically creates an
448 /// ExistingModuleProvider for an existing module.
449 EngineBuilder(Module *m);
451 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
452 /// or whichever engine works. This option defaults to EngineKind::Either.
453 EngineBuilder &setEngineKind(EngineKind::Kind w) {
458 /// setJITMemoryManager - Sets the memory manager to use. This allows
459 /// clients to customize their memory allocation policies. If create() is
460 /// called and is successful, the created engine takes ownership of the
461 /// memory manager. This option defaults to NULL.
462 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
467 /// setErrorStr - Set the error string to write to on error. This option
468 /// defaults to NULL.
469 EngineBuilder &setErrorStr(std::string *e) {
474 /// setOptLevel - Set the optimization level for the JIT. This option
475 /// defaults to CodeGenOpt::Default.
476 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
481 /// setAllocateGVsWithCode - Sets whether global values should be allocated
482 /// into the same buffer as code. For most applications this should be set
483 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
484 /// and is probably unsafe and bad for performance. However, we have clients
485 /// who depend on this behavior, so we must support it. This option defaults
486 /// to false so that users of the new API can safely use the new memory
487 /// manager and free machine code.
488 EngineBuilder &setAllocateGVsWithCode(bool a) {
489 AllocateGVsWithCode = a;
493 ExecutionEngine *create();
496 } // End llvm namespace