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.
142 static ExecutionEngine *createJIT(ModuleProvider *MP,
143 std::string *ErrorStr = 0,
144 JITMemoryManager *JMM = 0,
145 CodeGenOpt::Level OptLevel =
147 bool GVsWithCode = true);
149 /// addModuleProvider - Add a ModuleProvider to the list of modules that we
150 /// can JIT from. Note that this takes ownership of the ModuleProvider: when
151 /// the ExecutionEngine is destroyed, it destroys the MP as well.
152 virtual void addModuleProvider(ModuleProvider *P) {
153 Modules.push_back(P);
156 //===----------------------------------------------------------------------===//
158 const TargetData *getTargetData() const { return TD; }
161 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
162 /// Relases the Module from the ModuleProvider, materializing it in the
163 /// process, and returns the materialized Module.
164 virtual Module* removeModuleProvider(ModuleProvider *P,
165 std::string *ErrInfo = 0);
167 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
168 /// and deletes the ModuleProvider and owned Module. Avoids materializing
169 /// the underlying module.
170 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
172 /// FindFunctionNamed - Search all of the active modules to find the one that
173 /// defines FnName. This is very slow operation and shouldn't be used for
175 Function *FindFunctionNamed(const char *FnName);
177 /// runFunction - Execute the specified function with the specified arguments,
178 /// and return the result.
180 virtual GenericValue runFunction(Function *F,
181 const std::vector<GenericValue> &ArgValues) = 0;
183 /// runStaticConstructorsDestructors - This method is used to execute all of
184 /// the static constructors or destructors for a program, depending on the
185 /// value of isDtors.
186 void runStaticConstructorsDestructors(bool isDtors);
187 /// runStaticConstructorsDestructors - This method is used to execute all of
188 /// the static constructors or destructors for a module, depending on the
189 /// value of isDtors.
190 void runStaticConstructorsDestructors(Module *module, bool isDtors);
193 /// runFunctionAsMain - This is a helper function which wraps runFunction to
194 /// handle the common task of starting up main with the specified argc, argv,
195 /// and envp parameters.
196 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
197 const char * const * envp);
200 /// addGlobalMapping - Tell the execution engine that the specified global is
201 /// at the specified location. This is used internally as functions are JIT'd
202 /// and as global variables are laid out in memory. It can and should also be
203 /// used by clients of the EE that want to have an LLVM global overlay
204 /// existing data in memory. After adding a mapping for GV, you must not
205 /// destroy it until you've removed the mapping.
206 void addGlobalMapping(const GlobalValue *GV, void *Addr);
208 /// clearAllGlobalMappings - Clear all global mappings and start over again
209 /// use in dynamic compilation scenarios when you want to move globals
210 void clearAllGlobalMappings();
212 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
213 /// particular module, because it has been removed from the JIT.
214 void clearGlobalMappingsFromModule(Module *M);
216 /// updateGlobalMapping - Replace an existing mapping for GV with a new
217 /// address. This updates both maps as required. If "Addr" is null, the
218 /// entry for the global is removed from the mappings. This returns the old
219 /// value of the pointer, or null if it was not in the map.
220 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
222 /// getPointerToGlobalIfAvailable - This returns the address of the specified
223 /// global value if it is has already been codegen'd, otherwise it returns
226 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
228 /// getPointerToGlobal - This returns the address of the specified global
229 /// value. This may involve code generation if it's a function. After
230 /// getting a pointer to GV, it and all globals it transitively refers to have
231 /// been passed to addGlobalMapping. You must clear the mapping for each
232 /// referred-to global before destroying it. If a referred-to global RTG is a
233 /// function and this ExecutionEngine is a JIT compiler, calling
234 /// updateGlobalMapping(RTG, 0) will leak the function's machine code, so you
235 /// should call freeMachineCodeForFunction(RTG) instead. Note that
236 /// optimizations can move and delete non-external GlobalValues without
237 /// notifying the ExecutionEngine.
239 void *getPointerToGlobal(const GlobalValue *GV);
241 /// getPointerToFunction - The different EE's represent function bodies in
242 /// different ways. They should each implement this to say what a function
243 /// pointer should look like. See getPointerToGlobal for the requirements on
244 /// destroying F and any GlobalValues it refers to.
246 virtual void *getPointerToFunction(Function *F) = 0;
248 /// getPointerToFunctionOrStub - If the specified function has been
249 /// code-gen'd, return a pointer to the function. If not, compile it, or use
250 /// a stub to implement lazy compilation if available. See getPointerToGlobal
251 /// for the requirements on destroying F and any GlobalValues it refers to.
253 virtual void *getPointerToFunctionOrStub(Function *F) {
254 // Default implementation, just codegen the function.
255 return getPointerToFunction(F);
258 // The JIT overrides a version that actually does this.
259 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
261 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
262 /// at the specified address.
264 const GlobalValue *getGlobalValueAtAddress(void *Addr);
267 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
269 void InitializeMemory(const Constant *Init, void *Addr);
271 /// recompileAndRelinkFunction - This method is used to force a function
272 /// which has already been compiled to be compiled again, possibly
273 /// after it has been modified. Then the entry to the old copy is overwritten
274 /// with a branch to the new copy. If there was no old copy, this acts
275 /// just like VM::getPointerToFunction().
277 virtual void *recompileAndRelinkFunction(Function *F) = 0;
279 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
280 /// corresponding to the machine code emitted to execute this function, useful
281 /// for garbage-collecting generated code.
283 virtual void freeMachineCodeForFunction(Function *F) = 0;
285 /// getOrEmitGlobalVariable - Return the address of the specified global
286 /// variable, possibly emitting it to memory if needed. This is used by the
287 /// Emitter. See getPointerToGlobal for the requirements on destroying GV and
288 /// any GlobalValues it refers to.
289 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
290 return getPointerToGlobal((GlobalValue*)GV);
293 /// Registers a listener to be called back on various events within
294 /// the JIT. See JITEventListener.h for more details. Does not
295 /// take ownership of the argument. The argument may be NULL, in
296 /// which case these functions do nothing.
297 virtual void RegisterJITEventListener(JITEventListener *) {}
298 virtual void UnregisterJITEventListener(JITEventListener *) {}
300 /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation
301 /// is ever attempted.
302 void DisableLazyCompilation(bool Disabled = true) {
303 LazyCompilationDisabled = Disabled;
305 bool isLazyCompilationDisabled() const {
306 return LazyCompilationDisabled;
309 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
310 /// allocate space and populate a GlobalVariable that is not internal to
312 void DisableGVCompilation(bool Disabled = true) {
313 GVCompilationDisabled = Disabled;
315 bool isGVCompilationDisabled() const {
316 return GVCompilationDisabled;
319 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
320 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
321 /// resolve symbols in a custom way.
322 void DisableSymbolSearching(bool Disabled = true) {
323 SymbolSearchingDisabled = Disabled;
325 bool isSymbolSearchingDisabled() const {
326 return SymbolSearchingDisabled;
329 /// EnableDlsymStubs -
330 void EnableDlsymStubs(bool Enabled = true) {
331 DlsymStubsEnabled = Enabled;
333 bool areDlsymStubsEnabled() const {
334 return DlsymStubsEnabled;
337 /// InstallLazyFunctionCreator - If an unknown function is needed, the
338 /// specified function pointer is invoked to create it. If it returns null,
339 /// the JIT will abort.
340 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
341 LazyFunctionCreator = P;
344 /// InstallExceptionTableRegister - The JIT will use the given function
345 /// to register the exception tables it generates.
346 static void InstallExceptionTableRegister(void (*F)(void*)) {
347 ExceptionTableRegister = F;
350 /// RegisterTable - Registers the given pointer as an exception table. It uses
351 /// the ExceptionTableRegister function.
352 static void RegisterTable(void* res) {
353 if (ExceptionTableRegister)
354 ExceptionTableRegister(res);
358 explicit ExecutionEngine(ModuleProvider *P);
362 // EmitGlobalVariable - This method emits the specified global variable to the
363 // address specified in GlobalAddresses, or allocates new memory if it's not
364 // already in the map.
365 void EmitGlobalVariable(const GlobalVariable *GV);
367 GenericValue getConstantValue(const Constant *C);
368 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
372 } // End llvm namespace