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/Support/ValueHandle.h"
23 #include "llvm/System/Mutex.h"
24 #include "llvm/Target/TargetMachine.h"
30 class ExecutionEngine;
34 class JITEventListener;
35 class JITMemoryManager;
36 class MachineCodeInfo;
43 class ExecutionEngineState {
45 class MapUpdatingCVH : public CallbackVH {
46 ExecutionEngineState &EES;
49 MapUpdatingCVH(ExecutionEngineState &EES, const GlobalValue *GV);
51 operator const GlobalValue*() const {
52 return cast<GlobalValue>(getValPtr());
55 virtual void deleted();
56 virtual void allUsesReplacedWith(Value *new_value);
62 /// GlobalAddressMap - A mapping between LLVM global values and their
63 /// actualized version...
64 std::map<MapUpdatingCVH, void *> GlobalAddressMap;
66 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
67 /// used to convert raw addresses into the LLVM global value that is emitted
68 /// at the address. This map is not computed unless getGlobalValueAtAddress
69 /// is called at some point.
70 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
73 ExecutionEngineState(ExecutionEngine &EE) : EE(EE) {}
75 MapUpdatingCVH getVH(const GlobalValue *GV) {
76 return MapUpdatingCVH(*this, GV);
79 std::map<MapUpdatingCVH, void *> &
80 getGlobalAddressMap(const MutexGuard &) {
81 return GlobalAddressMap;
84 std::map<void*, AssertingVH<const GlobalValue> > &
85 getGlobalAddressReverseMap(const MutexGuard &) {
86 return GlobalAddressReverseMap;
89 // Returns the address ToUnmap was mapped to.
90 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
94 class ExecutionEngine {
96 ExecutionEngineState EEState;
97 bool LazyCompilationDisabled;
98 bool GVCompilationDisabled;
99 bool SymbolSearchingDisabled;
100 bool DlsymStubsEnabled;
102 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
105 /// Modules - This is a list of ModuleProvider's that we are JIT'ing from. We
106 /// use a smallvector to optimize for the case where there is only one module.
107 SmallVector<ModuleProvider*, 1> Modules;
109 void setTargetData(const TargetData *td) {
113 /// getMemoryforGV - Allocate memory for a global variable.
114 virtual char* getMemoryForGV(const GlobalVariable* GV);
116 // To avoid having libexecutionengine depend on the JIT and interpreter
117 // libraries, the JIT and Interpreter set these functions to ctor pointers
118 // at startup time if they are linked in.
119 static ExecutionEngine *(*JITCtor)(ModuleProvider *MP,
120 std::string *ErrorStr,
121 JITMemoryManager *JMM,
122 CodeGenOpt::Level OptLevel,
124 static ExecutionEngine *(*InterpCtor)(ModuleProvider *MP,
125 std::string *ErrorStr);
127 /// LazyFunctionCreator - If an unknown function is needed, this function
128 /// pointer is invoked to create it. If this returns null, the JIT will abort.
129 void* (*LazyFunctionCreator)(const std::string &);
131 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
132 /// register dwarf tables with this function
133 typedef void (*EERegisterFn)(void*);
134 static EERegisterFn ExceptionTableRegister;
137 /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
138 /// JITEmitter classes. It must be held while changing the internal state of
139 /// any of those classes.
140 sys::Mutex lock; // Used to make this class and subclasses thread-safe
142 //===--------------------------------------------------------------------===//
143 // ExecutionEngine Startup
144 //===--------------------------------------------------------------------===//
146 virtual ~ExecutionEngine();
148 /// create - This is the factory method for creating an execution engine which
149 /// is appropriate for the current machine. This takes ownership of the
151 static ExecutionEngine *create(ModuleProvider *MP,
152 bool ForceInterpreter = false,
153 std::string *ErrorStr = 0,
154 CodeGenOpt::Level OptLevel =
156 // Allocating globals with code breaks
157 // freeMachineCodeForFunction and is probably
158 // unsafe and bad for performance. However,
159 // we have clients who depend on this
160 // behavior, so we must support it.
161 // Eventually, when we're willing to break
162 // some backwards compatability, this flag
163 // should be flipped to false, so that by
164 // default freeMachineCodeForFunction works.
165 bool GVsWithCode = true);
167 /// create - This is the factory method for creating an execution engine which
168 /// is appropriate for the current machine. This takes ownership of the
170 static ExecutionEngine *create(Module *M);
172 /// createJIT - This is the factory method for creating a JIT for the current
173 /// machine, it does not fall back to the interpreter. This takes ownership
174 /// of the ModuleProvider and JITMemoryManager if successful.
176 /// Clients should make sure to initialize targets prior to calling this
178 static ExecutionEngine *createJIT(ModuleProvider *MP,
179 std::string *ErrorStr = 0,
180 JITMemoryManager *JMM = 0,
181 CodeGenOpt::Level OptLevel =
183 bool GVsWithCode = true);
185 /// addModuleProvider - Add a ModuleProvider to the list of modules that we
186 /// can JIT from. Note that this takes ownership of the ModuleProvider: when
187 /// the ExecutionEngine is destroyed, it destroys the MP as well.
188 virtual void addModuleProvider(ModuleProvider *P) {
189 Modules.push_back(P);
192 //===----------------------------------------------------------------------===//
194 const TargetData *getTargetData() const { return TD; }
197 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
198 /// Relases the Module from the ModuleProvider, materializing it in the
199 /// process, and returns the materialized Module.
200 virtual Module* removeModuleProvider(ModuleProvider *P,
201 std::string *ErrInfo = 0);
203 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
204 /// and deletes the ModuleProvider and owned Module. Avoids materializing
205 /// the underlying module.
206 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
208 /// FindFunctionNamed - Search all of the active modules to find the one that
209 /// defines FnName. This is very slow operation and shouldn't be used for
211 Function *FindFunctionNamed(const char *FnName);
213 /// runFunction - Execute the specified function with the specified arguments,
214 /// and return the result.
216 virtual GenericValue runFunction(Function *F,
217 const std::vector<GenericValue> &ArgValues) = 0;
219 /// runStaticConstructorsDestructors - This method is used to execute all of
220 /// the static constructors or destructors for a program, depending on the
221 /// value of isDtors.
222 void runStaticConstructorsDestructors(bool isDtors);
223 /// runStaticConstructorsDestructors - This method is used to execute all of
224 /// the static constructors or destructors for a module, depending on the
225 /// value of isDtors.
226 void runStaticConstructorsDestructors(Module *module, bool isDtors);
229 /// runFunctionAsMain - This is a helper function which wraps runFunction to
230 /// handle the common task of starting up main with the specified argc, argv,
231 /// and envp parameters.
232 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
233 const char * const * envp);
236 /// addGlobalMapping - Tell the execution engine that the specified global is
237 /// at the specified location. This is used internally as functions are JIT'd
238 /// and as global variables are laid out in memory. It can and should also be
239 /// used by clients of the EE that want to have an LLVM global overlay
240 /// existing data in memory. Mappings are automatically removed when their
241 /// GlobalValue is destroyed.
242 void addGlobalMapping(const GlobalValue *GV, void *Addr);
244 /// clearAllGlobalMappings - Clear all global mappings and start over again
245 /// use in dynamic compilation scenarios when you want to move globals
246 void clearAllGlobalMappings();
248 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
249 /// particular module, because it has been removed from the JIT.
250 void clearGlobalMappingsFromModule(Module *M);
252 /// updateGlobalMapping - Replace an existing mapping for GV with a new
253 /// address. This updates both maps as required. If "Addr" is null, the
254 /// entry for the global is removed from the mappings. This returns the old
255 /// value of the pointer, or null if it was not in the map.
256 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
258 /// getPointerToGlobalIfAvailable - This returns the address of the specified
259 /// global value if it is has already been codegen'd, otherwise it returns
262 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
264 /// getPointerToGlobal - This returns the address of the specified global
265 /// value. This may involve code generation if it's a function.
267 void *getPointerToGlobal(const GlobalValue *GV);
269 /// getPointerToFunction - The different EE's represent function bodies in
270 /// different ways. They should each implement this to say what a function
271 /// pointer should look like. When F is destroyed, the ExecutionEngine will
272 /// remove its global mapping but will not yet free its machine code. Call
273 /// freeMachineCodeForFunction(F) explicitly to do that. Note that global
274 /// optimizations can destroy Functions without notifying the ExecutionEngine.
276 virtual void *getPointerToFunction(Function *F) = 0;
278 /// getPointerToFunctionOrStub - If the specified function has been
279 /// code-gen'd, return a pointer to the function. If not, compile it, or use
280 /// a stub to implement lazy compilation if available. See
281 /// getPointerToFunction for the requirements on destroying F.
283 virtual void *getPointerToFunctionOrStub(Function *F) {
284 // Default implementation, just codegen the function.
285 return getPointerToFunction(F);
288 // The JIT overrides a version that actually does this.
289 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
291 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
292 /// at the specified address.
294 const GlobalValue *getGlobalValueAtAddress(void *Addr);
297 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
299 void InitializeMemory(const Constant *Init, void *Addr);
301 /// recompileAndRelinkFunction - This method is used to force a function
302 /// which has already been compiled to be compiled again, possibly
303 /// after it has been modified. Then the entry to the old copy is overwritten
304 /// with a branch to the new copy. If there was no old copy, this acts
305 /// just like VM::getPointerToFunction().
307 virtual void *recompileAndRelinkFunction(Function *F) = 0;
309 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
310 /// corresponding to the machine code emitted to execute this function, useful
311 /// for garbage-collecting generated code.
313 virtual void freeMachineCodeForFunction(Function *F) = 0;
315 /// getOrEmitGlobalVariable - Return the address of the specified global
316 /// variable, possibly emitting it to memory if needed. This is used by the
318 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
319 return getPointerToGlobal((GlobalValue*)GV);
322 /// Registers a listener to be called back on various events within
323 /// the JIT. See JITEventListener.h for more details. Does not
324 /// take ownership of the argument. The argument may be NULL, in
325 /// which case these functions do nothing.
326 virtual void RegisterJITEventListener(JITEventListener *) {}
327 virtual void UnregisterJITEventListener(JITEventListener *) {}
329 /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation
330 /// is ever attempted.
331 void DisableLazyCompilation(bool Disabled = true) {
332 LazyCompilationDisabled = Disabled;
334 bool isLazyCompilationDisabled() const {
335 return LazyCompilationDisabled;
338 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
339 /// allocate space and populate a GlobalVariable that is not internal to
341 void DisableGVCompilation(bool Disabled = true) {
342 GVCompilationDisabled = Disabled;
344 bool isGVCompilationDisabled() const {
345 return GVCompilationDisabled;
348 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
349 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
350 /// resolve symbols in a custom way.
351 void DisableSymbolSearching(bool Disabled = true) {
352 SymbolSearchingDisabled = Disabled;
354 bool isSymbolSearchingDisabled() const {
355 return SymbolSearchingDisabled;
358 /// EnableDlsymStubs -
359 void EnableDlsymStubs(bool Enabled = true) {
360 DlsymStubsEnabled = Enabled;
362 bool areDlsymStubsEnabled() const {
363 return DlsymStubsEnabled;
366 /// InstallLazyFunctionCreator - If an unknown function is needed, the
367 /// specified function pointer is invoked to create it. If it returns null,
368 /// the JIT will abort.
369 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
370 LazyFunctionCreator = P;
373 /// InstallExceptionTableRegister - The JIT will use the given function
374 /// to register the exception tables it generates.
375 static void InstallExceptionTableRegister(void (*F)(void*)) {
376 ExceptionTableRegister = F;
379 /// RegisterTable - Registers the given pointer as an exception table. It uses
380 /// the ExceptionTableRegister function.
381 static void RegisterTable(void* res) {
382 if (ExceptionTableRegister)
383 ExceptionTableRegister(res);
387 explicit ExecutionEngine(ModuleProvider *P);
391 // EmitGlobalVariable - This method emits the specified global variable to the
392 // address specified in GlobalAddresses, or allocates new memory if it's not
393 // already in the map.
394 void EmitGlobalVariable(const GlobalVariable *GV);
396 GenericValue getConstantValue(const Constant *C);
397 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
401 namespace EngineKind {
402 // These are actually bitmasks that get or-ed together.
407 const static Kind Either = (Kind)(JIT | Interpreter);
410 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
411 /// stack-allocating a builder, chaining the various set* methods, and
412 /// terminating it with a .create() call.
413 class EngineBuilder {
417 EngineKind::Kind WhichEngine;
418 std::string *ErrorStr;
419 CodeGenOpt::Level OptLevel;
420 JITMemoryManager *JMM;
421 bool AllocateGVsWithCode;
423 /// InitEngine - Does the common initialization of default options.
426 WhichEngine = EngineKind::Either;
428 OptLevel = CodeGenOpt::Default;
430 AllocateGVsWithCode = false;
434 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
435 /// is successful, the created engine takes ownership of the module
437 EngineBuilder(ModuleProvider *mp) : MP(mp) {
441 /// EngineBuilder - Overloaded constructor that automatically creates an
442 /// ExistingModuleProvider for an existing module.
443 EngineBuilder(Module *m);
445 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
446 /// or whichever engine works. This option defaults to EngineKind::Either.
447 EngineBuilder &setEngineKind(EngineKind::Kind w) {
452 /// setJITMemoryManager - Sets the memory manager to use. This allows
453 /// clients to customize their memory allocation policies. If create() is
454 /// called and is successful, the created engine takes ownership of the
455 /// memory manager. This option defaults to NULL.
456 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
461 /// setErrorStr - Set the error string to write to on error. This option
462 /// defaults to NULL.
463 EngineBuilder &setErrorStr(std::string *e) {
468 /// setOptLevel - Set the optimization level for the JIT. This option
469 /// defaults to CodeGenOpt::Default.
470 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
475 /// setAllocateGVsWithCode - Sets whether global values should be allocated
476 /// into the same buffer as code. For most applications this should be set
477 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
478 /// and is probably unsafe and bad for performance. However, we have clients
479 /// who depend on this behavior, so we must support it. This option defaults
480 /// to false so that users of the new API can safely use the new memory
481 /// manager and free machine code.
482 EngineBuilder &setAllocateGVsWithCode(bool a) {
483 AllocateGVsWithCode = a;
487 ExecutionEngine *create();
491 inline bool operator<(const ExecutionEngineState::MapUpdatingCVH& lhs,
492 const ExecutionEngineState::MapUpdatingCVH& rhs) {
493 return static_cast<const GlobalValue*>(lhs) <
494 static_cast<const GlobalValue*>(rhs);
497 } // End llvm namespace