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/System/Mutex.h"
23 #include "llvm/Target/TargetMachine.h"
32 class JITEventListener;
33 class JITMemoryManager;
34 class MachineCodeInfo;
41 class ExecutionEngineState {
43 /// GlobalAddressMap - A mapping between LLVM global values and their
44 /// actualized version...
45 std::map<const GlobalValue*, void *> GlobalAddressMap;
47 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
48 /// used to convert raw addresses into the LLVM global value that is emitted
49 /// at the address. This map is not computed unless getGlobalValueAtAddress
50 /// is called at some point.
51 std::map<void *, const GlobalValue*> GlobalAddressReverseMap;
54 std::map<const GlobalValue*, void *> &
55 getGlobalAddressMap(const MutexGuard &) {
56 return GlobalAddressMap;
59 std::map<void*, const GlobalValue*> &
60 getGlobalAddressReverseMap(const MutexGuard &) {
61 return GlobalAddressReverseMap;
66 class ExecutionEngine {
68 ExecutionEngineState state;
69 bool LazyCompilationDisabled;
70 bool GVCompilationDisabled;
71 bool SymbolSearchingDisabled;
72 bool DlsymStubsEnabled;
75 /// Modules - This is a list of ModuleProvider's that we are JIT'ing from. We
76 /// use a smallvector to optimize for the case where there is only one module.
77 SmallVector<ModuleProvider*, 1> Modules;
79 void setTargetData(const TargetData *td) {
83 /// getMemoryforGV - Allocate memory for a global variable.
84 virtual char* getMemoryForGV(const GlobalVariable* GV);
86 // To avoid having libexecutionengine depend on the JIT and interpreter
87 // libraries, the JIT and Interpreter set these functions to ctor pointers
88 // at startup time if they are linked in.
89 typedef ExecutionEngine *(*EECtorFn)(ModuleProvider*, std::string*,
90 CodeGenOpt::Level OptLevel,
92 static EECtorFn JITCtor, InterpCtor;
94 /// LazyFunctionCreator - If an unknown function is needed, this function
95 /// pointer is invoked to create it. If this returns null, the JIT will abort.
96 void* (*LazyFunctionCreator)(const std::string &);
98 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
99 /// register dwarf tables with this function
100 typedef void (*EERegisterFn)(void*);
101 static EERegisterFn ExceptionTableRegister;
104 /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
105 /// JITEmitter classes. It must be held while changing the internal state of
106 /// any of those classes.
107 sys::Mutex lock; // Used to make this class and subclasses thread-safe
109 //===--------------------------------------------------------------------===//
110 // ExecutionEngine Startup
111 //===--------------------------------------------------------------------===//
113 virtual ~ExecutionEngine();
115 /// create - This is the factory method for creating an execution engine which
116 /// is appropriate for the current machine. This takes ownership of the
118 static ExecutionEngine *create(ModuleProvider *MP,
119 bool ForceInterpreter = false,
120 std::string *ErrorStr = 0,
121 CodeGenOpt::Level OptLevel =
123 // Allocating globals with code breaks
124 // freeMachineCodeForFunction and is probably
125 // unsafe and bad for performance. However,
126 // we have clients who depend on this
127 // behavior, so we must support it.
128 // Eventually, when we're willing to break
129 // some backwards compatability, this flag
130 // should be flipped to false, so that by
131 // default freeMachineCodeForFunction works.
132 bool GVsWithCode = true);
134 /// create - This is the factory method for creating an execution engine which
135 /// is appropriate for the current machine. This takes ownership of the
137 static ExecutionEngine *create(Module *M);
139 /// createJIT - This is the factory method for creating a JIT for the current
140 /// machine, it does not fall back to the interpreter. This takes ownership
141 /// of the ModuleProvider and JITMemoryManager if successful.
143 /// Clients should make sure to initialize targets prior to calling this
145 static ExecutionEngine *createJIT(ModuleProvider *MP,
146 std::string *ErrorStr = 0,
147 JITMemoryManager *JMM = 0,
148 CodeGenOpt::Level OptLevel =
150 bool GVsWithCode = true);
152 /// addModuleProvider - Add a ModuleProvider to the list of modules that we
153 /// can JIT from. Note that this takes ownership of the ModuleProvider: when
154 /// the ExecutionEngine is destroyed, it destroys the MP as well.
155 virtual void addModuleProvider(ModuleProvider *P) {
156 Modules.push_back(P);
159 //===----------------------------------------------------------------------===//
161 const TargetData *getTargetData() const { return TD; }
164 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
165 /// Relases the Module from the ModuleProvider, materializing it in the
166 /// process, and returns the materialized Module.
167 virtual Module* removeModuleProvider(ModuleProvider *P,
168 std::string *ErrInfo = 0);
170 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
171 /// and deletes the ModuleProvider and owned Module. Avoids materializing
172 /// the underlying module.
173 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
175 /// FindFunctionNamed - Search all of the active modules to find the one that
176 /// defines FnName. This is very slow operation and shouldn't be used for
178 Function *FindFunctionNamed(const char *FnName);
180 /// runFunction - Execute the specified function with the specified arguments,
181 /// and return the result.
183 virtual GenericValue runFunction(Function *F,
184 const std::vector<GenericValue> &ArgValues) = 0;
186 /// runStaticConstructorsDestructors - This method is used to execute all of
187 /// the static constructors or destructors for a program, depending on the
188 /// value of isDtors.
189 void runStaticConstructorsDestructors(bool isDtors);
190 /// runStaticConstructorsDestructors - This method is used to execute all of
191 /// the static constructors or destructors for a module, depending on the
192 /// value of isDtors.
193 void runStaticConstructorsDestructors(Module *module, bool isDtors);
196 /// runFunctionAsMain - This is a helper function which wraps runFunction to
197 /// handle the common task of starting up main with the specified argc, argv,
198 /// and envp parameters.
199 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
200 const char * const * envp);
203 /// addGlobalMapping - Tell the execution engine that the specified global is
204 /// at the specified location. This is used internally as functions are JIT'd
205 /// and as global variables are laid out in memory. It can and should also be
206 /// used by clients of the EE that want to have an LLVM global overlay
207 /// existing data in memory. After adding a mapping for GV, you must not
208 /// destroy it until you've removed the mapping.
209 void addGlobalMapping(const GlobalValue *GV, void *Addr);
211 /// clearAllGlobalMappings - Clear all global mappings and start over again
212 /// use in dynamic compilation scenarios when you want to move globals
213 void clearAllGlobalMappings();
215 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
216 /// particular module, because it has been removed from the JIT.
217 void clearGlobalMappingsFromModule(Module *M);
219 /// updateGlobalMapping - Replace an existing mapping for GV with a new
220 /// address. This updates both maps as required. If "Addr" is null, the
221 /// entry for the global is removed from the mappings. This returns the old
222 /// value of the pointer, or null if it was not in the map.
223 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
225 /// getPointerToGlobalIfAvailable - This returns the address of the specified
226 /// global value if it is has already been codegen'd, otherwise it returns
229 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
231 /// getPointerToGlobal - This returns the address of the specified global
232 /// value. This may involve code generation if it's a function. After
233 /// getting a pointer to GV, it and all globals it transitively refers to have
234 /// been passed to addGlobalMapping. You must clear the mapping for each
235 /// referred-to global before destroying it. If a referred-to global RTG is a
236 /// function and this ExecutionEngine is a JIT compiler, calling
237 /// updateGlobalMapping(RTG, 0) will leak the function's machine code, so you
238 /// should call freeMachineCodeForFunction(RTG) instead. Note that
239 /// optimizations can move and delete non-external GlobalValues without
240 /// notifying the ExecutionEngine.
242 void *getPointerToGlobal(const GlobalValue *GV);
244 /// getPointerToFunction - The different EE's represent function bodies in
245 /// different ways. They should each implement this to say what a function
246 /// pointer should look like. See getPointerToGlobal for the requirements on
247 /// destroying F and any GlobalValues it refers to.
249 virtual void *getPointerToFunction(Function *F) = 0;
251 /// getPointerToFunctionOrStub - If the specified function has been
252 /// code-gen'd, return a pointer to the function. If not, compile it, or use
253 /// a stub to implement lazy compilation if available. See getPointerToGlobal
254 /// for the requirements on destroying F and any GlobalValues it refers to.
256 virtual void *getPointerToFunctionOrStub(Function *F) {
257 // Default implementation, just codegen the function.
258 return getPointerToFunction(F);
261 // The JIT overrides a version that actually does this.
262 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
264 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
265 /// at the specified address.
267 const GlobalValue *getGlobalValueAtAddress(void *Addr);
270 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
272 void InitializeMemory(const Constant *Init, void *Addr);
274 /// recompileAndRelinkFunction - This method is used to force a function
275 /// which has already been compiled to be compiled again, possibly
276 /// after it has been modified. Then the entry to the old copy is overwritten
277 /// with a branch to the new copy. If there was no old copy, this acts
278 /// just like VM::getPointerToFunction().
280 virtual void *recompileAndRelinkFunction(Function *F) = 0;
282 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
283 /// corresponding to the machine code emitted to execute this function, useful
284 /// for garbage-collecting generated code.
286 virtual void freeMachineCodeForFunction(Function *F) = 0;
288 /// getOrEmitGlobalVariable - Return the address of the specified global
289 /// variable, possibly emitting it to memory if needed. This is used by the
290 /// Emitter. See getPointerToGlobal for the requirements on destroying GV and
291 /// any GlobalValues it refers to.
292 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
293 return getPointerToGlobal((GlobalValue*)GV);
296 /// Registers a listener to be called back on various events within
297 /// the JIT. See JITEventListener.h for more details. Does not
298 /// take ownership of the argument. The argument may be NULL, in
299 /// which case these functions do nothing.
300 virtual void RegisterJITEventListener(JITEventListener *) {}
301 virtual void UnregisterJITEventListener(JITEventListener *) {}
303 /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation
304 /// is ever attempted.
305 void DisableLazyCompilation(bool Disabled = true) {
306 LazyCompilationDisabled = Disabled;
308 bool isLazyCompilationDisabled() const {
309 return LazyCompilationDisabled;
312 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
313 /// allocate space and populate a GlobalVariable that is not internal to
315 void DisableGVCompilation(bool Disabled = true) {
316 GVCompilationDisabled = Disabled;
318 bool isGVCompilationDisabled() const {
319 return GVCompilationDisabled;
322 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
323 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
324 /// resolve symbols in a custom way.
325 void DisableSymbolSearching(bool Disabled = true) {
326 SymbolSearchingDisabled = Disabled;
328 bool isSymbolSearchingDisabled() const {
329 return SymbolSearchingDisabled;
332 /// EnableDlsymStubs -
333 void EnableDlsymStubs(bool Enabled = true) {
334 DlsymStubsEnabled = Enabled;
336 bool areDlsymStubsEnabled() const {
337 return DlsymStubsEnabled;
340 /// InstallLazyFunctionCreator - If an unknown function is needed, the
341 /// specified function pointer is invoked to create it. If it returns null,
342 /// the JIT will abort.
343 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
344 LazyFunctionCreator = P;
347 /// InstallExceptionTableRegister - The JIT will use the given function
348 /// to register the exception tables it generates.
349 static void InstallExceptionTableRegister(void (*F)(void*)) {
350 ExceptionTableRegister = F;
353 /// RegisterTable - Registers the given pointer as an exception table. It uses
354 /// the ExceptionTableRegister function.
355 static void RegisterTable(void* res) {
356 if (ExceptionTableRegister)
357 ExceptionTableRegister(res);
361 explicit ExecutionEngine(ModuleProvider *P);
365 // EmitGlobalVariable - This method emits the specified global variable to the
366 // address specified in GlobalAddresses, or allocates new memory if it's not
367 // already in the map.
368 void EmitGlobalVariable(const GlobalVariable *GV);
370 GenericValue getConstantValue(const Constant *C);
371 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
375 } // End llvm namespace