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