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;
40 template<typename> class AssertingVH;
42 class ExecutionEngineState {
44 /// GlobalAddressMap - A mapping between LLVM global values and their
45 /// actualized version...
46 std::map<AssertingVH<const GlobalValue>, void *> GlobalAddressMap;
48 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
49 /// used to convert raw addresses into the LLVM global value that is emitted
50 /// at the address. This map is not computed unless getGlobalValueAtAddress
51 /// is called at some point.
52 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
55 std::map<AssertingVH<const GlobalValue>, void *> &
56 getGlobalAddressMap(const MutexGuard &) {
57 return GlobalAddressMap;
60 std::map<void*, AssertingVH<const GlobalValue> > &
61 getGlobalAddressReverseMap(const MutexGuard &) {
62 return GlobalAddressReverseMap;
67 class ExecutionEngine {
69 ExecutionEngineState state;
70 bool LazyCompilationDisabled;
71 bool GVCompilationDisabled;
72 bool SymbolSearchingDisabled;
73 bool DlsymStubsEnabled;
75 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
78 /// Modules - This is a list of ModuleProvider's that we are JIT'ing from. We
79 /// use a smallvector to optimize for the case where there is only one module.
80 SmallVector<ModuleProvider*, 1> Modules;
82 void setTargetData(const TargetData *td) {
86 /// getMemoryforGV - Allocate memory for a global variable.
87 virtual char* getMemoryForGV(const GlobalVariable* GV);
89 // To avoid having libexecutionengine depend on the JIT and interpreter
90 // libraries, the JIT and Interpreter set these functions to ctor pointers
91 // at startup time if they are linked in.
92 static ExecutionEngine *(*JITCtor)(ModuleProvider *MP,
93 std::string *ErrorStr,
94 JITMemoryManager *JMM,
95 CodeGenOpt::Level OptLevel,
97 static ExecutionEngine *(*InterpCtor)(ModuleProvider *MP,
98 std::string *ErrorStr);
100 /// LazyFunctionCreator - If an unknown function is needed, this function
101 /// pointer is invoked to create it. If this returns null, the JIT will abort.
102 void* (*LazyFunctionCreator)(const std::string &);
104 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
105 /// register dwarf tables with this function
106 typedef void (*EERegisterFn)(void*);
107 static EERegisterFn ExceptionTableRegister;
110 /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
111 /// JITEmitter classes. It must be held while changing the internal state of
112 /// any of those classes.
113 sys::Mutex lock; // Used to make this class and subclasses thread-safe
115 //===--------------------------------------------------------------------===//
116 // ExecutionEngine Startup
117 //===--------------------------------------------------------------------===//
119 virtual ~ExecutionEngine();
121 /// create - This is the factory method for creating an execution engine which
122 /// is appropriate for the current machine. This takes ownership of the
124 static ExecutionEngine *create(ModuleProvider *MP,
125 bool ForceInterpreter = false,
126 std::string *ErrorStr = 0,
127 CodeGenOpt::Level OptLevel =
129 // Allocating globals with code breaks
130 // freeMachineCodeForFunction and is probably
131 // unsafe and bad for performance. However,
132 // we have clients who depend on this
133 // behavior, so we must support it.
134 // Eventually, when we're willing to break
135 // some backwards compatability, this flag
136 // should be flipped to false, so that by
137 // default freeMachineCodeForFunction works.
138 bool GVsWithCode = true);
140 /// create - This is the factory method for creating an execution engine which
141 /// is appropriate for the current machine. This takes ownership of the
143 static ExecutionEngine *create(Module *M);
145 /// createJIT - This is the factory method for creating a JIT for the current
146 /// machine, it does not fall back to the interpreter. This takes ownership
147 /// of the ModuleProvider and JITMemoryManager if successful.
149 /// Clients should make sure to initialize targets prior to calling this
151 static ExecutionEngine *createJIT(ModuleProvider *MP,
152 std::string *ErrorStr = 0,
153 JITMemoryManager *JMM = 0,
154 CodeGenOpt::Level OptLevel =
156 bool GVsWithCode = true);
158 /// addModuleProvider - Add a ModuleProvider to the list of modules that we
159 /// can JIT from. Note that this takes ownership of the ModuleProvider: when
160 /// the ExecutionEngine is destroyed, it destroys the MP as well.
161 virtual void addModuleProvider(ModuleProvider *P) {
162 Modules.push_back(P);
165 //===----------------------------------------------------------------------===//
167 const TargetData *getTargetData() const { return TD; }
170 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
171 /// Relases the Module from the ModuleProvider, materializing it in the
172 /// process, and returns the materialized Module.
173 virtual Module* removeModuleProvider(ModuleProvider *P,
174 std::string *ErrInfo = 0);
176 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
177 /// and deletes the ModuleProvider and owned Module. Avoids materializing
178 /// the underlying module.
179 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
181 /// FindFunctionNamed - Search all of the active modules to find the one that
182 /// defines FnName. This is very slow operation and shouldn't be used for
184 Function *FindFunctionNamed(const char *FnName);
186 /// runFunction - Execute the specified function with the specified arguments,
187 /// and return the result.
189 virtual GenericValue runFunction(Function *F,
190 const std::vector<GenericValue> &ArgValues) = 0;
192 /// runStaticConstructorsDestructors - This method is used to execute all of
193 /// the static constructors or destructors for a program, depending on the
194 /// value of isDtors.
195 void runStaticConstructorsDestructors(bool isDtors);
196 /// runStaticConstructorsDestructors - This method is used to execute all of
197 /// the static constructors or destructors for a module, depending on the
198 /// value of isDtors.
199 void runStaticConstructorsDestructors(Module *module, bool isDtors);
202 /// runFunctionAsMain - This is a helper function which wraps runFunction to
203 /// handle the common task of starting up main with the specified argc, argv,
204 /// and envp parameters.
205 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
206 const char * const * envp);
209 /// addGlobalMapping - Tell the execution engine that the specified global is
210 /// at the specified location. This is used internally as functions are JIT'd
211 /// and as global variables are laid out in memory. It can and should also be
212 /// used by clients of the EE that want to have an LLVM global overlay
213 /// existing data in memory. After adding a mapping for GV, you must not
214 /// destroy it until you've removed the mapping.
215 void addGlobalMapping(const GlobalValue *GV, void *Addr);
217 /// clearAllGlobalMappings - Clear all global mappings and start over again
218 /// use in dynamic compilation scenarios when you want to move globals
219 void clearAllGlobalMappings();
221 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
222 /// particular module, because it has been removed from the JIT.
223 void clearGlobalMappingsFromModule(Module *M);
225 /// updateGlobalMapping - Replace an existing mapping for GV with a new
226 /// address. This updates both maps as required. If "Addr" is null, the
227 /// entry for the global is removed from the mappings. This returns the old
228 /// value of the pointer, or null if it was not in the map.
229 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
231 /// getPointerToGlobalIfAvailable - This returns the address of the specified
232 /// global value if it is has already been codegen'd, otherwise it returns
235 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
237 /// getPointerToGlobal - This returns the address of the specified global
238 /// value. This may involve code generation if it's a function. After
239 /// getting a pointer to GV, it and all globals it transitively refers to have
240 /// been passed to addGlobalMapping. You must clear the mapping for each
241 /// referred-to global before destroying it. If a referred-to global RTG is a
242 /// function and this ExecutionEngine is a JIT compiler, calling
243 /// updateGlobalMapping(RTG, 0) will leak the function's machine code, so you
244 /// should call freeMachineCodeForFunction(RTG) instead. Note that
245 /// optimizations can move and delete non-external GlobalValues without
246 /// notifying the ExecutionEngine.
248 void *getPointerToGlobal(const GlobalValue *GV);
250 /// getPointerToFunction - The different EE's represent function bodies in
251 /// different ways. They should each implement this to say what a function
252 /// pointer should look like. See getPointerToGlobal for the requirements on
253 /// destroying F and any GlobalValues it refers to.
255 virtual void *getPointerToFunction(Function *F) = 0;
257 /// getPointerToFunctionOrStub - If the specified function has been
258 /// code-gen'd, return a pointer to the function. If not, compile it, or use
259 /// a stub to implement lazy compilation if available. See getPointerToGlobal
260 /// for the requirements on destroying F and any GlobalValues it refers to.
262 virtual void *getPointerToFunctionOrStub(Function *F) {
263 // Default implementation, just codegen the function.
264 return getPointerToFunction(F);
267 // The JIT overrides a version that actually does this.
268 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
270 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
271 /// at the specified address.
273 const GlobalValue *getGlobalValueAtAddress(void *Addr);
276 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
278 void InitializeMemory(const Constant *Init, void *Addr);
280 /// recompileAndRelinkFunction - This method is used to force a function
281 /// which has already been compiled to be compiled again, possibly
282 /// after it has been modified. Then the entry to the old copy is overwritten
283 /// with a branch to the new copy. If there was no old copy, this acts
284 /// just like VM::getPointerToFunction().
286 virtual void *recompileAndRelinkFunction(Function *F) = 0;
288 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
289 /// corresponding to the machine code emitted to execute this function, useful
290 /// for garbage-collecting generated code.
292 virtual void freeMachineCodeForFunction(Function *F) = 0;
294 /// getOrEmitGlobalVariable - Return the address of the specified global
295 /// variable, possibly emitting it to memory if needed. This is used by the
296 /// Emitter. See getPointerToGlobal for the requirements on destroying GV and
297 /// any GlobalValues it refers to.
298 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
299 return getPointerToGlobal((GlobalValue*)GV);
302 /// Registers a listener to be called back on various events within
303 /// the JIT. See JITEventListener.h for more details. Does not
304 /// take ownership of the argument. The argument may be NULL, in
305 /// which case these functions do nothing.
306 virtual void RegisterJITEventListener(JITEventListener *) {}
307 virtual void UnregisterJITEventListener(JITEventListener *) {}
309 /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation
310 /// is ever attempted.
311 void DisableLazyCompilation(bool Disabled = true) {
312 LazyCompilationDisabled = Disabled;
314 bool isLazyCompilationDisabled() const {
315 return LazyCompilationDisabled;
318 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
319 /// allocate space and populate a GlobalVariable that is not internal to
321 void DisableGVCompilation(bool Disabled = true) {
322 GVCompilationDisabled = Disabled;
324 bool isGVCompilationDisabled() const {
325 return GVCompilationDisabled;
328 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
329 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
330 /// resolve symbols in a custom way.
331 void DisableSymbolSearching(bool Disabled = true) {
332 SymbolSearchingDisabled = Disabled;
334 bool isSymbolSearchingDisabled() const {
335 return SymbolSearchingDisabled;
338 /// EnableDlsymStubs -
339 void EnableDlsymStubs(bool Enabled = true) {
340 DlsymStubsEnabled = Enabled;
342 bool areDlsymStubsEnabled() const {
343 return DlsymStubsEnabled;
346 /// InstallLazyFunctionCreator - If an unknown function is needed, the
347 /// specified function pointer is invoked to create it. If it returns null,
348 /// the JIT will abort.
349 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
350 LazyFunctionCreator = P;
353 /// InstallExceptionTableRegister - The JIT will use the given function
354 /// to register the exception tables it generates.
355 static void InstallExceptionTableRegister(void (*F)(void*)) {
356 ExceptionTableRegister = F;
359 /// RegisterTable - Registers the given pointer as an exception table. It uses
360 /// the ExceptionTableRegister function.
361 static void RegisterTable(void* res) {
362 if (ExceptionTableRegister)
363 ExceptionTableRegister(res);
367 explicit ExecutionEngine(ModuleProvider *P);
371 // EmitGlobalVariable - This method emits the specified global variable to the
372 // address specified in GlobalAddresses, or allocates new memory if it's not
373 // already in the map.
374 void EmitGlobalVariable(const GlobalVariable *GV);
376 GenericValue getConstantValue(const Constant *C);
377 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
381 namespace EngineKind {
382 // These are actually bitmasks that get or-ed together.
387 const static Kind Either = (Kind)(JIT | Interpreter);
390 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
391 /// stack-allocating a builder, chaining the various set* methods, and
392 /// terminating it with a .create() call.
393 class EngineBuilder {
397 EngineKind::Kind WhichEngine;
398 std::string *ErrorStr;
399 CodeGenOpt::Level OptLevel;
400 JITMemoryManager *JMM;
401 bool AllocateGVsWithCode;
403 /// InitEngine - Does the common initialization of default options.
406 WhichEngine = EngineKind::Either;
408 OptLevel = CodeGenOpt::Default;
410 AllocateGVsWithCode = false;
414 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
415 /// is successful, the created engine takes ownership of the module
417 EngineBuilder(ModuleProvider *mp) : MP(mp) {
421 /// EngineBuilder - Overloaded constructor that automatically creates an
422 /// ExistingModuleProvider for an existing module.
423 EngineBuilder(Module *m);
425 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
426 /// or whichever engine works. This option defaults to EngineKind::Either.
427 EngineBuilder &setEngineKind(EngineKind::Kind w) {
432 /// setJITMemoryManager - Sets the memory manager to use. This allows
433 /// clients to customize their memory allocation policies. If create() is
434 /// called and is successful, the created engine takes ownership of the
435 /// memory manager. This option defaults to NULL.
436 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
441 /// setErrorStr - Set the error string to write to on error. This option
442 /// defaults to NULL.
443 EngineBuilder &setErrorStr(std::string *e) {
448 /// setOptLevel - Set the optimization level for the JIT. This option
449 /// defaults to CodeGenOpt::Default.
450 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
455 /// setAllocateGVsWithCode - Sets whether global values should be allocated
456 /// into the same buffer as code. For most applications this should be set
457 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
458 /// and is probably unsafe and bad for performance. However, we have clients
459 /// who depend on this behavior, so we must support it. This option defaults
460 /// to false so that users of the new API can safely use the new memory
461 /// manager and free machine code.
462 EngineBuilder &setAllocateGVsWithCode(bool a) {
463 AllocateGVsWithCode = a;
467 ExecutionEngine *create();
471 } // End llvm namespace