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