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