add a mechanism for the JIT to invoke a function to lazily create functions as they...
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 EXECUTION_ENGINE_H
16 #define 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
38 class ExecutionEngineState {
39 private:
40   /// GlobalAddressMap - A mapping between LLVM global values and their
41   /// actualized version...
42   std::map<const GlobalValue*, void *> GlobalAddressMap;
43
44   /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
45   /// used to convert raw addresses into the LLVM global value that is emitted
46   /// at the address.  This map is not computed unless getGlobalValueAtAddress
47   /// is called at some point.
48   std::map<void *, const GlobalValue*> GlobalAddressReverseMap;
49
50 public:
51   std::map<const GlobalValue*, void *> &
52   getGlobalAddressMap(const MutexGuard &locked) {
53     return GlobalAddressMap;
54   }
55
56   std::map<void*, const GlobalValue*> & 
57   getGlobalAddressReverseMap(const MutexGuard& locked) {
58     return GlobalAddressReverseMap;
59   }
60 };
61
62
63 class ExecutionEngine {
64   const TargetData *TD;
65   ExecutionEngineState state;
66   bool LazyCompilationDisabled;
67
68 protected:
69   /// Modules - This is a list of ModuleProvider's that we are JIT'ing from.  We
70   /// use a smallvector to optimize for the case where there is only one module.
71   SmallVector<ModuleProvider*, 1> Modules;
72   
73   void setTargetData(const TargetData *td) {
74     TD = td;
75   }
76
77   // To avoid having libexecutionengine depend on the JIT and interpreter
78   // libraries, the JIT and Interpreter set these functions to ctor pointers
79   // at startup time if they are linked in.
80   typedef ExecutionEngine *(*EECtorFn)(ModuleProvider*, std::string*);
81   static EECtorFn JITCtor, InterpCtor;
82
83   /// LazyFunctionCreator - If an unknown function is needed, this function
84   /// pointer is invoked to create it. If this returns null, the JIT will abort.
85   void* (*LazyFunctionCreator)(const std::string &);
86   
87 public:
88   /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
89   /// JITEmitter classes.  It must be held while changing the internal state of
90   /// any of those classes.
91   sys::Mutex lock; // Used to make this class and subclasses thread-safe
92
93   ExecutionEngine(ModuleProvider *P);
94   ExecutionEngine(Module *M);
95   virtual ~ExecutionEngine();
96
97   const TargetData *getTargetData() const { return TD; }
98
99   /// addModuleProvider - Add a ModuleProvider to the list of modules that we
100   /// can JIT from.  Note that this takes ownership of the ModuleProvider: when
101   /// the ExecutionEngine is destroyed, it destroys the MP as well.
102   void addModuleProvider(ModuleProvider *P) {
103     Modules.push_back(P);
104   }
105
106   /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
107   /// Release module from ModuleProvider.
108   Module* removeModuleProvider(ModuleProvider *P, std::string *ErrInfo = 0);
109
110   /// FindFunctionNamed - Search all of the active modules to find the one that
111   /// defines FnName.  This is very slow operation and shouldn't be used for
112   /// general code.
113   Function *FindFunctionNamed(const char *FnName);
114   
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
117   /// module provider.
118   static ExecutionEngine *create(ModuleProvider *MP,
119                                  bool ForceInterpreter = false,
120                                  std::string *ErrorStr = 0);
121
122   /// create - This is the factory method for creating an execution engine which
123   /// is appropriate for the current machine.  This takes ownership of the
124   /// module.
125   static ExecutionEngine *create(Module *M);
126   
127   /// runFunction - Execute the specified function with the specified arguments,
128   /// and return the result.
129   ///
130   virtual GenericValue runFunction(Function *F,
131                                 const std::vector<GenericValue> &ArgValues) = 0;
132
133   /// runStaticConstructorsDestructors - This method is used to execute all of
134   /// the static constructors or destructors for a module, depending on the
135   /// value of isDtors.
136   void runStaticConstructorsDestructors(bool isDtors);
137   
138   
139   /// runFunctionAsMain - This is a helper function which wraps runFunction to
140   /// handle the common task of starting up main with the specified argc, argv,
141   /// and envp parameters.
142   int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
143                         const char * const * envp);
144
145
146   /// addGlobalMapping - Tell the execution engine that the specified global is
147   /// at the specified location.  This is used internally as functions are JIT'd
148   /// and as global variables are laid out in memory.  It can and should also be
149   /// used by clients of the EE that want to have an LLVM global overlay
150   /// existing data in memory.
151   void addGlobalMapping(const GlobalValue *GV, void *Addr);
152   
153   /// clearAllGlobalMappings - Clear all global mappings and start over again
154   /// use in dynamic compilation scenarios when you want to move globals
155   void clearAllGlobalMappings();
156   
157   /// updateGlobalMapping - Replace an existing mapping for GV with a new
158   /// address.  This updates both maps as required.  If "Addr" is null, the
159   /// entry for the global is removed from the mappings.
160   void updateGlobalMapping(const GlobalValue *GV, void *Addr);
161   
162   /// getPointerToGlobalIfAvailable - This returns the address of the specified
163   /// global value if it is has already been codegen'd, otherwise it returns
164   /// null.
165   ///
166   void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
167
168   /// getPointerToGlobal - This returns the address of the specified global
169   /// value.  This may involve code generation if it's a function.
170   ///
171   void *getPointerToGlobal(const GlobalValue *GV);
172
173   /// getPointerToFunction - The different EE's represent function bodies in
174   /// different ways.  They should each implement this to say what a function
175   /// pointer should look like.
176   ///
177   virtual void *getPointerToFunction(Function *F) = 0;
178
179   /// getPointerToFunctionOrStub - If the specified function has been
180   /// code-gen'd, return a pointer to the function.  If not, compile it, or use
181   /// a stub to implement lazy compilation if available.
182   ///
183   virtual void *getPointerToFunctionOrStub(Function *F) {
184     // Default implementation, just codegen the function.
185     return getPointerToFunction(F);
186   }
187
188   /// getGlobalValueAtAddress - Return the LLVM global value object that starts
189   /// at the specified address.
190   ///
191   const GlobalValue *getGlobalValueAtAddress(void *Addr);
192
193
194   void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr, const Type *Ty);
195   void InitializeMemory(const Constant *Init, void *Addr);
196
197   /// recompileAndRelinkFunction - This method is used to force a function
198   /// which has already been compiled to be compiled again, possibly
199   /// after it has been modified. Then the entry to the old copy is overwritten
200   /// with a branch to the new copy. If there was no old copy, this acts
201   /// just like VM::getPointerToFunction().
202   ///
203   virtual void *recompileAndRelinkFunction(Function *F) = 0;
204
205   /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
206   /// corresponding to the machine code emitted to execute this function, useful
207   /// for garbage-collecting generated code.
208   ///
209   virtual void freeMachineCodeForFunction(Function *F) = 0;
210
211   /// getOrEmitGlobalVariable - Return the address of the specified global
212   /// variable, possibly emitting it to memory if needed.  This is used by the
213   /// Emitter.
214   virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
215     return getPointerToGlobal((GlobalValue*)GV);
216   }
217   
218   /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation
219   // is ever attempted.
220   void DisableLazyCompilation() {
221     LazyCompilationDisabled = true;
222   }
223   bool isLazyCompilationDisabled() const {
224     return LazyCompilationDisabled;
225   }
226   
227   
228   /// InstallLazyFunctionCreator - If an unknown function is needed, the
229   /// specified function pointer is invoked to create it.  If it returns null,
230   /// the JIT will abort.
231   void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
232     LazyFunctionCreator = P;
233   }
234
235 protected:
236   void emitGlobals();
237
238   // EmitGlobalVariable - This method emits the specified global variable to the
239   // address specified in GlobalAddresses, or allocates new memory if it's not
240   // already in the map.
241   void EmitGlobalVariable(const GlobalVariable *GV);
242
243   GenericValue getConstantValue(const Constant *C);
244   void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr, 
245                            const Type *Ty);
246 };
247
248 } // End llvm namespace
249
250 #endif