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