Add DisableGVCompilation which forces the JIT to assert when it tries to allocate...
[oota-llvm.git] / include / llvm / ExecutionEngine / ExecutionEngine.h
1 //===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the abstract interface that implements execution support
11 // for LLVM.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_EXECUTION_ENGINE_H
16 #define LLVM_EXECUTION_ENGINE_H
17
18 #include <vector>
19 #include <map>
20 #include <cassert>
21 #include <string>
22 #include "llvm/System/Mutex.h"
23 #include "llvm/ADT/SmallVector.h"
24
25 namespace llvm {
26
27 struct GenericValue;
28 class Constant;
29 class Function;
30 class GlobalVariable;
31 class GlobalValue;
32 class Module;
33 class ModuleProvider;
34 class TargetData;
35 class Type;
36 class MutexGuard;
37 class JITMemoryManager;
38
39 class ExecutionEngineState {
40 private:
41   /// GlobalAddressMap - A mapping between LLVM global values and their
42   /// actualized version...
43   std::map<const GlobalValue*, void *> GlobalAddressMap;
44
45   /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
46   /// used to convert raw addresses into the LLVM global value that is emitted
47   /// at the address.  This map is not computed unless getGlobalValueAtAddress
48   /// is called at some point.
49   std::map<void *, const GlobalValue*> GlobalAddressReverseMap;
50
51 public:
52   std::map<const GlobalValue*, void *> &
53   getGlobalAddressMap(const MutexGuard &) {
54     return GlobalAddressMap;
55   }
56
57   std::map<void*, const GlobalValue*> & 
58   getGlobalAddressReverseMap(const MutexGuard &) {
59     return GlobalAddressReverseMap;
60   }
61 };
62
63
64 class ExecutionEngine {
65   const TargetData *TD;
66   ExecutionEngineState state;
67   bool LazyCompilationDisabled;
68   bool GVCompilationDisabled;
69   bool SymbolSearchingDisabled;
70
71 protected:
72   /// Modules - This is a list of ModuleProvider's that we are JIT'ing from.  We
73   /// use a smallvector to optimize for the case where there is only one module.
74   SmallVector<ModuleProvider*, 1> Modules;
75   
76   void setTargetData(const TargetData *td) {
77     TD = td;
78   }
79
80   // To avoid having libexecutionengine depend on the JIT and interpreter
81   // libraries, the JIT and Interpreter set these functions to ctor pointers
82   // at startup time if they are linked in.
83   typedef ExecutionEngine *(*EECtorFn)(ModuleProvider*, std::string*,
84                                        bool Fast);
85   static EECtorFn JITCtor, InterpCtor;
86
87   /// LazyFunctionCreator - If an unknown function is needed, this function
88   /// pointer is invoked to create it. If this returns null, the JIT will abort.
89   void* (*LazyFunctionCreator)(const std::string &);
90   
91   /// ExceptionTableRegister - If Exception Handling is set, the JIT will 
92   /// register dwarf tables with this function
93   typedef void (*EERegisterFn)(void*);
94   static EERegisterFn ExceptionTableRegister;
95
96 public:
97   /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
98   /// JITEmitter classes.  It must be held while changing the internal state of
99   /// any of those classes.
100   sys::Mutex lock; // Used to make this class and subclasses thread-safe
101
102   //===--------------------------------------------------------------------===//
103   //  ExecutionEngine Startup
104   //===--------------------------------------------------------------------===//
105
106   virtual ~ExecutionEngine();
107
108   /// create - This is the factory method for creating an execution engine which
109   /// is appropriate for the current machine.  This takes ownership of the
110   /// module provider.
111   static ExecutionEngine *create(ModuleProvider *MP,
112                                  bool ForceInterpreter = false,
113                                  std::string *ErrorStr = 0,
114                                  bool Fast = false);
115   
116   /// create - This is the factory method for creating an execution engine which
117   /// is appropriate for the current machine.  This takes ownership of the
118   /// module.
119   static ExecutionEngine *create(Module *M);
120
121   /// createJIT - This is the factory method for creating a JIT for the current
122   /// machine, it does not fall back to the interpreter.  This takes ownership
123   /// of the ModuleProvider and JITMemoryManager if successful.
124   static ExecutionEngine *createJIT(ModuleProvider *MP,
125                                     std::string *ErrorStr = 0,
126                                     JITMemoryManager *JMM = 0,
127                                     bool Fast = false);
128   
129   
130   
131   /// addModuleProvider - Add a ModuleProvider to the list of modules that we
132   /// can JIT from.  Note that this takes ownership of the ModuleProvider: when
133   /// the ExecutionEngine is destroyed, it destroys the MP as well.
134   virtual void addModuleProvider(ModuleProvider *P) {
135     Modules.push_back(P);
136   }
137   
138   //===----------------------------------------------------------------------===//
139
140   const TargetData *getTargetData() const { return TD; }
141
142
143   /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
144   /// Release module from ModuleProvider.
145   virtual Module* removeModuleProvider(ModuleProvider *P,
146                                        std::string *ErrInfo = 0);
147
148   /// FindFunctionNamed - Search all of the active modules to find the one that
149   /// defines FnName.  This is very slow operation and shouldn't be used for
150   /// general code.
151   Function *FindFunctionNamed(const char *FnName);
152   
153   /// runFunction - Execute the specified function with the specified arguments,
154   /// and return the result.
155   ///
156   virtual GenericValue runFunction(Function *F,
157                                 const std::vector<GenericValue> &ArgValues) = 0;
158
159   /// runStaticConstructorsDestructors - This method is used to execute all of
160   /// the static constructors or destructors for a module, depending on the
161   /// value of isDtors.
162   void runStaticConstructorsDestructors(bool isDtors);
163   
164   
165   /// runFunctionAsMain - This is a helper function which wraps runFunction to
166   /// handle the common task of starting up main with the specified argc, argv,
167   /// and envp parameters.
168   int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
169                         const char * const * envp);
170
171
172   /// addGlobalMapping - Tell the execution engine that the specified global is
173   /// at the specified location.  This is used internally as functions are JIT'd
174   /// and as global variables are laid out in memory.  It can and should also be
175   /// used by clients of the EE that want to have an LLVM global overlay
176   /// existing data in memory.
177   void addGlobalMapping(const GlobalValue *GV, void *Addr);
178   
179   /// clearAllGlobalMappings - Clear all global mappings and start over again
180   /// use in dynamic compilation scenarios when you want to move globals
181   void clearAllGlobalMappings();
182   
183   /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
184   /// particular module, because it has been removed from the JIT.
185   void clearGlobalMappingsFromModule(Module *M);
186   
187   /// updateGlobalMapping - Replace an existing mapping for GV with a new
188   /// address.  This updates both maps as required.  If "Addr" is null, the
189   /// entry for the global is removed from the mappings.  This returns the old
190   /// value of the pointer, or null if it was not in the map.
191   void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
192   
193   /// getPointerToGlobalIfAvailable - This returns the address of the specified
194   /// global value if it is has already been codegen'd, otherwise it returns
195   /// null.
196   ///
197   void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
198
199   /// getPointerToGlobal - This returns the address of the specified global
200   /// value.  This may involve code generation if it's a function.
201   ///
202   void *getPointerToGlobal(const GlobalValue *GV);
203
204   /// getPointerToFunction - The different EE's represent function bodies in
205   /// different ways.  They should each implement this to say what a function
206   /// pointer should look like.
207   ///
208   virtual void *getPointerToFunction(Function *F) = 0;
209
210   /// getPointerToFunctionOrStub - If the specified function has been
211   /// code-gen'd, return a pointer to the function.  If not, compile it, or use
212   /// a stub to implement lazy compilation if available.
213   ///
214   virtual void *getPointerToFunctionOrStub(Function *F) {
215     // Default implementation, just codegen the function.
216     return getPointerToFunction(F);
217   }
218
219   /// getGlobalValueAtAddress - Return the LLVM global value object that starts
220   /// at the specified address.
221   ///
222   const GlobalValue *getGlobalValueAtAddress(void *Addr);
223
224
225   void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
226                           const Type *Ty);
227   void InitializeMemory(const Constant *Init, void *Addr);
228
229   /// recompileAndRelinkFunction - This method is used to force a function
230   /// which has already been compiled to be compiled again, possibly
231   /// after it has been modified. Then the entry to the old copy is overwritten
232   /// with a branch to the new copy. If there was no old copy, this acts
233   /// just like VM::getPointerToFunction().
234   ///
235   virtual void *recompileAndRelinkFunction(Function *F) = 0;
236
237   /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
238   /// corresponding to the machine code emitted to execute this function, useful
239   /// for garbage-collecting generated code.
240   ///
241   virtual void freeMachineCodeForFunction(Function *F) = 0;
242
243   /// getOrEmitGlobalVariable - Return the address of the specified global
244   /// variable, possibly emitting it to memory if needed.  This is used by the
245   /// Emitter.
246   virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
247     return getPointerToGlobal((GlobalValue*)GV);
248   }
249   
250   /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation
251   /// is ever attempted.
252   void DisableLazyCompilation(bool Disabled = true) {
253     LazyCompilationDisabled = Disabled;
254   }
255   bool isLazyCompilationDisabled() const {
256     return LazyCompilationDisabled;
257   }
258
259   /// DisableGVCompilation - If called, the JIT will abort if it's asked to allocate
260   /// space and populate a GlobalVariable.
261   void DisableGVCompilation(bool Disabled = true) {
262     GVCompilationDisabled = Disabled;
263   }
264   bool isGVCompilationDisabled() const {
265     return GVCompilationDisabled;
266   }
267
268   /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
269   /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
270   /// resolve symbols in a custom way.
271   void DisableSymbolSearching(bool Disabled = true) {
272     SymbolSearchingDisabled = Disabled;
273   }
274   bool isSymbolSearchingDisabled() const {
275     return SymbolSearchingDisabled;
276   }
277   
278   
279   /// InstallLazyFunctionCreator - If an unknown function is needed, the
280   /// specified function pointer is invoked to create it.  If it returns null,
281   /// the JIT will abort.
282   void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
283     LazyFunctionCreator = P;
284   }
285   
286   /// InstallExceptionTableRegister - The JIT will use the given function
287   /// to register the exception tables it generates.
288   static void InstallExceptionTableRegister(void (*F)(void*)) {
289     ExceptionTableRegister = F;
290   }
291   
292   /// RegisterTable - Registers the given pointer as an exception table. It uses
293   /// the ExceptionTableRegister function.
294   static void RegisterTable(void* res) {
295     if (ExceptionTableRegister)
296       ExceptionTableRegister(res);
297   }
298
299 protected:
300   explicit ExecutionEngine(ModuleProvider *P);
301
302   void emitGlobals();
303
304   // EmitGlobalVariable - This method emits the specified global variable to the
305   // address specified in GlobalAddresses, or allocates new memory if it's not
306   // already in the map.
307   void EmitGlobalVariable(const GlobalVariable *GV);
308
309   GenericValue getConstantValue(const Constant *C);
310   void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr, 
311                            const Type *Ty);
312 };
313
314 } // End llvm namespace
315
316 #endif