add interpreter support for indirect goto / blockaddress. The interpreter
[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 <string>
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/ValueMap.h"
23 #include "llvm/Support/ValueHandle.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/Target/TargetMachine.h"
26
27 namespace llvm {
28
29 struct GenericValue;
30 class Constant;
31 class ExecutionEngine;
32 class Function;
33 class GlobalVariable;
34 class GlobalValue;
35 class JITEventListener;
36 class JITMemoryManager;
37 class MachineCodeInfo;
38 class Module;
39 class ModuleProvider;
40 class MutexGuard;
41 class TargetData;
42 class Type;
43
44 class ExecutionEngineState {
45 public:
46   struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
47     typedef ExecutionEngineState *ExtraData;
48     static sys::Mutex *getMutex(ExecutionEngineState *EES);
49     static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
50     static void onRAUW(ExecutionEngineState *, const GlobalValue *,
51                        const GlobalValue *);
52   };
53
54   typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
55       GlobalAddressMapTy;
56
57 private:
58   ExecutionEngine &EE;
59
60   /// GlobalAddressMap - A mapping between LLVM global values and their
61   /// actualized version...
62   GlobalAddressMapTy GlobalAddressMap;
63
64   /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
65   /// used to convert raw addresses into the LLVM global value that is emitted
66   /// at the address.  This map is not computed unless getGlobalValueAtAddress
67   /// is called at some point.
68   std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
69
70 public:
71   ExecutionEngineState(ExecutionEngine &EE);
72
73   GlobalAddressMapTy &
74   getGlobalAddressMap(const MutexGuard &) {
75     return GlobalAddressMap;
76   }
77
78   std::map<void*, AssertingVH<const GlobalValue> > &
79   getGlobalAddressReverseMap(const MutexGuard &) {
80     return GlobalAddressReverseMap;
81   }
82
83   // Returns the address ToUnmap was mapped to.
84   void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
85 };
86
87
88 class ExecutionEngine {
89   const TargetData *TD;
90   ExecutionEngineState EEState;
91   bool CompilingLazily;
92   bool GVCompilationDisabled;
93   bool SymbolSearchingDisabled;
94   bool DlsymStubsEnabled;
95
96   friend class EngineBuilder;  // To allow access to JITCtor and InterpCtor.
97
98 protected:
99   /// Modules - This is a list of ModuleProvider's that we are JIT'ing from.  We
100   /// use a smallvector to optimize for the case where there is only one module.
101   SmallVector<ModuleProvider*, 1> Modules;
102   
103   void setTargetData(const TargetData *td) {
104     TD = td;
105   }
106   
107   /// getMemoryforGV - Allocate memory for a global variable.
108   virtual char* getMemoryForGV(const GlobalVariable* GV);
109
110   // To avoid having libexecutionengine depend on the JIT and interpreter
111   // libraries, the JIT and Interpreter set these functions to ctor pointers
112   // at startup time if they are linked in.
113   static ExecutionEngine *(*JITCtor)(ModuleProvider *MP,
114                                      std::string *ErrorStr,
115                                      JITMemoryManager *JMM,
116                                      CodeGenOpt::Level OptLevel,
117                                      bool GVsWithCode);
118   static ExecutionEngine *(*InterpCtor)(ModuleProvider *MP,
119                                         std::string *ErrorStr);
120
121   /// LazyFunctionCreator - If an unknown function is needed, this function
122   /// pointer is invoked to create it. If this returns null, the JIT will abort.
123   void* (*LazyFunctionCreator)(const std::string &);
124   
125   /// ExceptionTableRegister - If Exception Handling is set, the JIT will 
126   /// register dwarf tables with this function
127   typedef void (*EERegisterFn)(void*);
128   static EERegisterFn ExceptionTableRegister;
129
130 public:
131   /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and
132   /// JITEmitter classes.  It must be held while changing the internal state of
133   /// any of those classes.
134   sys::Mutex lock; // Used to make this class and subclasses thread-safe
135
136   //===--------------------------------------------------------------------===//
137   //  ExecutionEngine Startup
138   //===--------------------------------------------------------------------===//
139
140   virtual ~ExecutionEngine();
141
142   /// create - This is the factory method for creating an execution engine which
143   /// is appropriate for the current machine.  This takes ownership of the
144   /// module provider.
145   static ExecutionEngine *create(ModuleProvider *MP,
146                                  bool ForceInterpreter = false,
147                                  std::string *ErrorStr = 0,
148                                  CodeGenOpt::Level OptLevel =
149                                    CodeGenOpt::Default,
150                                  // Allocating globals with code breaks
151                                  // freeMachineCodeForFunction and is probably
152                                  // unsafe and bad for performance.  However,
153                                  // we have clients who depend on this
154                                  // behavior, so we must support it.
155                                  // Eventually, when we're willing to break
156                                  // some backwards compatability, this flag
157                                  // should be flipped to false, so that by
158                                  // default freeMachineCodeForFunction works.
159                                  bool GVsWithCode = true);
160
161   /// create - This is the factory method for creating an execution engine which
162   /// is appropriate for the current machine.  This takes ownership of the
163   /// module.
164   static ExecutionEngine *create(Module *M);
165
166   /// createJIT - This is the factory method for creating a JIT for the current
167   /// machine, it does not fall back to the interpreter.  This takes ownership
168   /// of the ModuleProvider and JITMemoryManager if successful.
169   ///
170   /// Clients should make sure to initialize targets prior to calling this
171   /// function.
172   static ExecutionEngine *createJIT(ModuleProvider *MP,
173                                     std::string *ErrorStr = 0,
174                                     JITMemoryManager *JMM = 0,
175                                     CodeGenOpt::Level OptLevel =
176                                       CodeGenOpt::Default,
177                                     bool GVsWithCode = true);
178
179   /// addModuleProvider - Add a ModuleProvider to the list of modules that we
180   /// can JIT from.  Note that this takes ownership of the ModuleProvider: when
181   /// the ExecutionEngine is destroyed, it destroys the MP as well.
182   virtual void addModuleProvider(ModuleProvider *P) {
183     Modules.push_back(P);
184   }
185   
186   //===----------------------------------------------------------------------===//
187
188   const TargetData *getTargetData() const { return TD; }
189
190
191   /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
192   /// Relases the Module from the ModuleProvider, materializing it in the
193   /// process, and returns the materialized Module.
194   virtual Module* removeModuleProvider(ModuleProvider *P,
195                                        std::string *ErrInfo = 0);
196
197   /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
198   /// and deletes the ModuleProvider and owned Module.  Avoids materializing 
199   /// the underlying module.
200   virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
201
202   /// FindFunctionNamed - Search all of the active modules to find the one that
203   /// defines FnName.  This is very slow operation and shouldn't be used for
204   /// general code.
205   Function *FindFunctionNamed(const char *FnName);
206   
207   /// runFunction - Execute the specified function with the specified arguments,
208   /// and return the result.
209   ///
210   virtual GenericValue runFunction(Function *F,
211                                 const std::vector<GenericValue> &ArgValues) = 0;
212
213   /// runStaticConstructorsDestructors - This method is used to execute all of
214   /// the static constructors or destructors for a program, depending on the
215   /// value of isDtors.
216   void runStaticConstructorsDestructors(bool isDtors);
217   /// runStaticConstructorsDestructors - This method is used to execute all of
218   /// the static constructors or destructors for a module, depending on the
219   /// value of isDtors.
220   void runStaticConstructorsDestructors(Module *module, bool isDtors);
221   
222   
223   /// runFunctionAsMain - This is a helper function which wraps runFunction to
224   /// handle the common task of starting up main with the specified argc, argv,
225   /// and envp parameters.
226   int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
227                         const char * const * envp);
228
229
230   /// addGlobalMapping - Tell the execution engine that the specified global is
231   /// at the specified location.  This is used internally as functions are JIT'd
232   /// and as global variables are laid out in memory.  It can and should also be
233   /// used by clients of the EE that want to have an LLVM global overlay
234   /// existing data in memory.  Mappings are automatically removed when their
235   /// GlobalValue is destroyed.
236   void addGlobalMapping(const GlobalValue *GV, void *Addr);
237   
238   /// clearAllGlobalMappings - Clear all global mappings and start over again
239   /// use in dynamic compilation scenarios when you want to move globals
240   void clearAllGlobalMappings();
241   
242   /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
243   /// particular module, because it has been removed from the JIT.
244   void clearGlobalMappingsFromModule(Module *M);
245   
246   /// updateGlobalMapping - Replace an existing mapping for GV with a new
247   /// address.  This updates both maps as required.  If "Addr" is null, the
248   /// entry for the global is removed from the mappings.  This returns the old
249   /// value of the pointer, or null if it was not in the map.
250   void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
251   
252   /// getPointerToGlobalIfAvailable - This returns the address of the specified
253   /// global value if it is has already been codegen'd, otherwise it returns
254   /// null.
255   ///
256   void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
257
258   /// getPointerToGlobal - This returns the address of the specified global
259   /// value.  This may involve code generation if it's a function.
260   ///
261   void *getPointerToGlobal(const GlobalValue *GV);
262
263   /// getPointerToFunction - The different EE's represent function bodies in
264   /// different ways.  They should each implement this to say what a function
265   /// pointer should look like.  When F is destroyed, the ExecutionEngine will
266   /// remove its global mapping and free any machine code.  Be sure no threads
267   /// are running inside F when that happens.
268   ///
269   virtual void *getPointerToFunction(Function *F) = 0;
270
271   /// getPointerToBasicBlock - The different EE's represent basic blocks in
272   /// different ways.  Return the representation for a blockaddress of the
273   /// specified block.
274   ///
275   virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
276   
277   /// getPointerToFunctionOrStub - If the specified function has been
278   /// code-gen'd, return a pointer to the function.  If not, compile it, or use
279   /// a stub to implement lazy compilation if available.  See
280   /// getPointerToFunction for the requirements on destroying F.
281   ///
282   virtual void *getPointerToFunctionOrStub(Function *F) {
283     // Default implementation, just codegen the function.
284     return getPointerToFunction(F);
285   }
286
287   // The JIT overrides a version that actually does this.
288   virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
289
290   /// getGlobalValueAtAddress - Return the LLVM global value object that starts
291   /// at the specified address.
292   ///
293   const GlobalValue *getGlobalValueAtAddress(void *Addr);
294
295
296   void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
297                           const Type *Ty);
298   void InitializeMemory(const Constant *Init, void *Addr);
299
300   /// recompileAndRelinkFunction - This method is used to force a function
301   /// which has already been compiled to be compiled again, possibly
302   /// after it has been modified. Then the entry to the old copy is overwritten
303   /// with a branch to the new copy. If there was no old copy, this acts
304   /// just like VM::getPointerToFunction().
305   ///
306   virtual void *recompileAndRelinkFunction(Function *F) = 0;
307
308   /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
309   /// corresponding to the machine code emitted to execute this function, useful
310   /// for garbage-collecting generated code.
311   ///
312   virtual void freeMachineCodeForFunction(Function *F) = 0;
313
314   /// getOrEmitGlobalVariable - Return the address of the specified global
315   /// variable, possibly emitting it to memory if needed.  This is used by the
316   /// Emitter.
317   virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
318     return getPointerToGlobal((GlobalValue*)GV);
319   }
320
321   /// Registers a listener to be called back on various events within
322   /// the JIT.  See JITEventListener.h for more details.  Does not
323   /// take ownership of the argument.  The argument may be NULL, in
324   /// which case these functions do nothing.
325   virtual void RegisterJITEventListener(JITEventListener *) {}
326   virtual void UnregisterJITEventListener(JITEventListener *) {}
327
328   /// DisableLazyCompilation - When lazy compilation is off (the default), the
329   /// JIT will eagerly compile every function reachable from the argument to
330   /// getPointerToFunction.  If lazy compilation is turned on, the JIT will only
331   /// compile the one function and emit stubs to compile the rest when they're
332   /// first called.  If lazy compilation is turned off again while some lazy
333   /// stubs are still around, and one of those stubs is called, the program will
334   /// abort.
335   ///
336   /// In order to safely compile lazily in a threaded program, the user must
337   /// ensure that 1) only one thread at a time can call any particular lazy
338   /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
339   /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
340   /// lazy stub.  See http://llvm.org/PR5184 for details.
341   void DisableLazyCompilation(bool Disabled = true) {
342     CompilingLazily = !Disabled;
343   }
344   bool isCompilingLazily() const {
345     return CompilingLazily;
346   }
347   // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
348   // Remove this in LLVM 2.8.
349   bool isLazyCompilationDisabled() const {
350     return !CompilingLazily;
351   }
352
353   /// DisableGVCompilation - If called, the JIT will abort if it's asked to
354   /// allocate space and populate a GlobalVariable that is not internal to
355   /// the module.
356   void DisableGVCompilation(bool Disabled = true) {
357     GVCompilationDisabled = Disabled;
358   }
359   bool isGVCompilationDisabled() const {
360     return GVCompilationDisabled;
361   }
362
363   /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
364   /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
365   /// resolve symbols in a custom way.
366   void DisableSymbolSearching(bool Disabled = true) {
367     SymbolSearchingDisabled = Disabled;
368   }
369   bool isSymbolSearchingDisabled() const {
370     return SymbolSearchingDisabled;
371   }
372   
373   /// EnableDlsymStubs - 
374   void EnableDlsymStubs(bool Enabled = true) {
375     DlsymStubsEnabled = Enabled;
376   }
377   bool areDlsymStubsEnabled() const {
378     return DlsymStubsEnabled;
379   }
380   
381   /// InstallLazyFunctionCreator - If an unknown function is needed, the
382   /// specified function pointer is invoked to create it.  If it returns null,
383   /// the JIT will abort.
384   void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
385     LazyFunctionCreator = P;
386   }
387   
388   /// InstallExceptionTableRegister - The JIT will use the given function
389   /// to register the exception tables it generates.
390   static void InstallExceptionTableRegister(void (*F)(void*)) {
391     ExceptionTableRegister = F;
392   }
393   
394   /// RegisterTable - Registers the given pointer as an exception table. It uses
395   /// the ExceptionTableRegister function.
396   static void RegisterTable(void* res) {
397     if (ExceptionTableRegister)
398       ExceptionTableRegister(res);
399   }
400
401 protected:
402   explicit ExecutionEngine(ModuleProvider *P);
403
404   void emitGlobals();
405
406   // EmitGlobalVariable - This method emits the specified global variable to the
407   // address specified in GlobalAddresses, or allocates new memory if it's not
408   // already in the map.
409   void EmitGlobalVariable(const GlobalVariable *GV);
410
411   GenericValue getConstantValue(const Constant *C);
412   void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr, 
413                            const Type *Ty);
414 };
415
416 namespace EngineKind {
417   // These are actually bitmasks that get or-ed together.
418   enum Kind {
419     JIT         = 0x1,
420     Interpreter = 0x2
421   };
422   const static Kind Either = (Kind)(JIT | Interpreter);
423 }
424
425 /// EngineBuilder - Builder class for ExecutionEngines.  Use this by
426 /// stack-allocating a builder, chaining the various set* methods, and
427 /// terminating it with a .create() call.
428 class EngineBuilder {
429
430  private:
431   ModuleProvider *MP;
432   EngineKind::Kind WhichEngine;
433   std::string *ErrorStr;
434   CodeGenOpt::Level OptLevel;
435   JITMemoryManager *JMM;
436   bool AllocateGVsWithCode;
437
438   /// InitEngine - Does the common initialization of default options.
439   ///
440   void InitEngine() {
441     WhichEngine = EngineKind::Either;
442     ErrorStr = NULL;
443     OptLevel = CodeGenOpt::Default;
444     JMM = NULL;
445     AllocateGVsWithCode = false;
446   }
447
448  public:
449   /// EngineBuilder - Constructor for EngineBuilder.  If create() is called and
450   /// is successful, the created engine takes ownership of the module
451   /// provider.
452   EngineBuilder(ModuleProvider *mp) : MP(mp) {
453     InitEngine();
454   }
455
456   /// EngineBuilder - Overloaded constructor that automatically creates an
457   /// ExistingModuleProvider for an existing module.
458   EngineBuilder(Module *m);
459
460   /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
461   /// or whichever engine works.  This option defaults to EngineKind::Either.
462   EngineBuilder &setEngineKind(EngineKind::Kind w) {
463     WhichEngine = w;
464     return *this;
465   }
466
467   /// setJITMemoryManager - Sets the memory manager to use.  This allows
468   /// clients to customize their memory allocation policies.  If create() is
469   /// called and is successful, the created engine takes ownership of the
470   /// memory manager.  This option defaults to NULL.
471   EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
472     JMM = jmm;
473     return *this;
474   }
475
476   /// setErrorStr - Set the error string to write to on error.  This option
477   /// defaults to NULL.
478   EngineBuilder &setErrorStr(std::string *e) {
479     ErrorStr = e;
480     return *this;
481   }
482
483   /// setOptLevel - Set the optimization level for the JIT.  This option
484   /// defaults to CodeGenOpt::Default.
485   EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
486     OptLevel = l;
487     return *this;
488   }
489
490   /// setAllocateGVsWithCode - Sets whether global values should be allocated
491   /// into the same buffer as code.  For most applications this should be set
492   /// to false.  Allocating globals with code breaks freeMachineCodeForFunction
493   /// and is probably unsafe and bad for performance.  However, we have clients
494   /// who depend on this behavior, so we must support it.  This option defaults
495   /// to false so that users of the new API can safely use the new memory
496   /// manager and free machine code.
497   EngineBuilder &setAllocateGVsWithCode(bool a) {
498     AllocateGVsWithCode = a;
499     return *this;
500   }
501
502   ExecutionEngine *create();
503 };
504
505 } // End llvm namespace
506
507 #endif