ExecutionEngine: fix JIT/MCJIT selectTarget() duplication
[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 compatibility,
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   /// selectTarget - Pick a target either via -march or by guessing the native
214   /// arch.  Add any CPU features specified via -mcpu or -mattr.
215   static TargetMachine *selectTarget(Module *M,
216                                      StringRef MArch,
217                                      StringRef MCPU,
218                                      const SmallVectorImpl<std::string>& MAttrs,
219                                      std::string *Err);
220
221   /// addModule - Add a Module to the list of modules that we can JIT from.
222   /// Note that this takes ownership of the Module: when the ExecutionEngine is
223   /// destroyed, it destroys the Module as well.
224   virtual void addModule(Module *M) {
225     Modules.push_back(M);
226   }
227
228   //===--------------------------------------------------------------------===//
229
230   const TargetData *getTargetData() const { return TD; }
231
232   /// removeModule - Remove a Module from the list of modules.  Returns true if
233   /// M is found.
234   virtual bool removeModule(Module *M);
235
236   /// FindFunctionNamed - Search all of the active modules to find the one that
237   /// defines FnName.  This is very slow operation and shouldn't be used for
238   /// general code.
239   Function *FindFunctionNamed(const char *FnName);
240
241   /// runFunction - Execute the specified function with the specified arguments,
242   /// and return the result.
243   virtual GenericValue runFunction(Function *F,
244                                 const std::vector<GenericValue> &ArgValues) = 0;
245
246   /// runStaticConstructorsDestructors - This method is used to execute all of
247   /// the static constructors or destructors for a program.
248   ///
249   /// \param isDtors - Run the destructors instead of constructors.
250   void runStaticConstructorsDestructors(bool isDtors);
251
252   /// runStaticConstructorsDestructors - This method is used to execute all of
253   /// the static constructors or destructors for a particular module.
254   ///
255   /// \param isDtors - Run the destructors instead of constructors.
256   void runStaticConstructorsDestructors(Module *module, bool isDtors);
257
258
259   /// runFunctionAsMain - This is a helper function which wraps runFunction to
260   /// handle the common task of starting up main with the specified argc, argv,
261   /// and envp parameters.
262   int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
263                         const char * const * envp);
264
265
266   /// addGlobalMapping - Tell the execution engine that the specified global is
267   /// at the specified location.  This is used internally as functions are JIT'd
268   /// and as global variables are laid out in memory.  It can and should also be
269   /// used by clients of the EE that want to have an LLVM global overlay
270   /// existing data in memory.  Mappings are automatically removed when their
271   /// GlobalValue is destroyed.
272   void addGlobalMapping(const GlobalValue *GV, void *Addr);
273
274   /// clearAllGlobalMappings - Clear all global mappings and start over again,
275   /// for use in dynamic compilation scenarios to move globals.
276   void clearAllGlobalMappings();
277
278   /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
279   /// particular module, because it has been removed from the JIT.
280   void clearGlobalMappingsFromModule(Module *M);
281
282   /// updateGlobalMapping - Replace an existing mapping for GV with a new
283   /// address.  This updates both maps as required.  If "Addr" is null, the
284   /// entry for the global is removed from the mappings.  This returns the old
285   /// value of the pointer, or null if it was not in the map.
286   void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
287
288   /// getPointerToGlobalIfAvailable - This returns the address of the specified
289   /// global value if it is has already been codegen'd, otherwise it returns
290   /// null.
291   void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
292
293   /// getPointerToGlobal - This returns the address of the specified global
294   /// value. This may involve code generation if it's a function.
295   void *getPointerToGlobal(const GlobalValue *GV);
296
297   /// getPointerToFunction - The different EE's represent function bodies in
298   /// different ways.  They should each implement this to say what a function
299   /// pointer should look like.  When F is destroyed, the ExecutionEngine will
300   /// remove its global mapping and free any machine code.  Be sure no threads
301   /// are running inside F when that happens.
302   virtual void *getPointerToFunction(Function *F) = 0;
303
304   /// getPointerToBasicBlock - The different EE's represent basic blocks in
305   /// different ways.  Return the representation for a blockaddress of the
306   /// specified block.
307   virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
308
309   /// getPointerToFunctionOrStub - If the specified function has been
310   /// code-gen'd, return a pointer to the function.  If not, compile it, or use
311   /// a stub to implement lazy compilation if available.  See
312   /// getPointerToFunction for the requirements on destroying F.
313   virtual void *getPointerToFunctionOrStub(Function *F) {
314     // Default implementation, just codegen the function.
315     return getPointerToFunction(F);
316   }
317
318   // The JIT overrides a version that actually does this.
319   virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
320
321   /// getGlobalValueAtAddress - Return the LLVM global value object that starts
322   /// at the specified address.
323   ///
324   const GlobalValue *getGlobalValueAtAddress(void *Addr);
325
326   /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
327   /// Ptr is the address of the memory at which to store Val, cast to
328   /// GenericValue *.  It is not a pointer to a GenericValue containing the
329   /// address at which to store Val.
330   void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
331                           const Type *Ty);
332
333   void InitializeMemory(const Constant *Init, void *Addr);
334
335   /// recompileAndRelinkFunction - This method is used to force a function which
336   /// has already been compiled to be compiled again, possibly after it has been
337   /// modified.  Then the entry to the old copy is overwritten with a branch to
338   /// the new copy.  If there was no old copy, this acts just like
339   /// VM::getPointerToFunction().
340   virtual void *recompileAndRelinkFunction(Function *F) = 0;
341
342   /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
343   /// corresponding to the machine code emitted to execute this function, useful
344   /// for garbage-collecting generated code.
345   virtual void freeMachineCodeForFunction(Function *F) = 0;
346
347   /// getOrEmitGlobalVariable - Return the address of the specified global
348   /// variable, possibly emitting it to memory if needed.  This is used by the
349   /// Emitter.
350   virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
351     return getPointerToGlobal((GlobalValue*)GV);
352   }
353
354   /// Registers a listener to be called back on various events within
355   /// the JIT.  See JITEventListener.h for more details.  Does not
356   /// take ownership of the argument.  The argument may be NULL, in
357   /// which case these functions do nothing.
358   virtual void RegisterJITEventListener(JITEventListener *) {}
359   virtual void UnregisterJITEventListener(JITEventListener *) {}
360
361   /// DisableLazyCompilation - When lazy compilation is off (the default), the
362   /// JIT will eagerly compile every function reachable from the argument to
363   /// getPointerToFunction.  If lazy compilation is turned on, the JIT will only
364   /// compile the one function and emit stubs to compile the rest when they're
365   /// first called.  If lazy compilation is turned off again while some lazy
366   /// stubs are still around, and one of those stubs is called, the program will
367   /// abort.
368   ///
369   /// In order to safely compile lazily in a threaded program, the user must
370   /// ensure that 1) only one thread at a time can call any particular lazy
371   /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
372   /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
373   /// lazy stub.  See http://llvm.org/PR5184 for details.
374   void DisableLazyCompilation(bool Disabled = true) {
375     CompilingLazily = !Disabled;
376   }
377   bool isCompilingLazily() const {
378     return CompilingLazily;
379   }
380   // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
381   // Remove this in LLVM 2.8.
382   bool isLazyCompilationDisabled() const {
383     return !CompilingLazily;
384   }
385
386   /// DisableGVCompilation - If called, the JIT will abort if it's asked to
387   /// allocate space and populate a GlobalVariable that is not internal to
388   /// the module.
389   void DisableGVCompilation(bool Disabled = true) {
390     GVCompilationDisabled = Disabled;
391   }
392   bool isGVCompilationDisabled() const {
393     return GVCompilationDisabled;
394   }
395
396   /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
397   /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
398   /// resolve symbols in a custom way.
399   void DisableSymbolSearching(bool Disabled = true) {
400     SymbolSearchingDisabled = Disabled;
401   }
402   bool isSymbolSearchingDisabled() const {
403     return SymbolSearchingDisabled;
404   }
405
406   /// InstallLazyFunctionCreator - If an unknown function is needed, the
407   /// specified function pointer is invoked to create it.  If it returns null,
408   /// the JIT will abort.
409   void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
410     LazyFunctionCreator = P;
411   }
412
413   /// InstallExceptionTableRegister - The JIT will use the given function
414   /// to register the exception tables it generates.
415   void InstallExceptionTableRegister(EERegisterFn F) {
416     ExceptionTableRegister = F;
417   }
418   void InstallExceptionTableDeregister(EERegisterFn F) {
419     ExceptionTableDeregister = F;
420   }
421
422   /// RegisterTable - Registers the given pointer as an exception table.  It
423   /// uses the ExceptionTableRegister function.
424   void RegisterTable(const Function *fn, void* res) {
425     if (ExceptionTableRegister) {
426       ExceptionTableRegister(res);
427       AllExceptionTables[fn] = res;
428     }
429   }
430
431   /// DeregisterTable - Deregisters the exception frame previously registered
432   /// for the given function.
433   void DeregisterTable(const Function *Fn) {
434     if (ExceptionTableDeregister) {
435       DenseMap<const Function*, void*>::iterator frame =
436         AllExceptionTables.find(Fn);
437       if(frame != AllExceptionTables.end()) {
438         ExceptionTableDeregister(frame->second);
439         AllExceptionTables.erase(frame);
440       }
441     }
442   }
443
444   /// DeregisterAllTables - Deregisters all previously registered pointers to an
445   /// exception tables.  It uses the ExceptionTableoDeregister function.
446   void DeregisterAllTables();
447
448 protected:
449   explicit ExecutionEngine(Module *M);
450
451   void emitGlobals();
452
453   void EmitGlobalVariable(const GlobalVariable *GV);
454
455   GenericValue getConstantValue(const Constant *C);
456   void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
457                            const Type *Ty);
458 };
459
460 namespace EngineKind {
461   // These are actually bitmasks that get or-ed together.
462   enum Kind {
463     JIT         = 0x1,
464     Interpreter = 0x2
465   };
466   const static Kind Either = (Kind)(JIT | Interpreter);
467 }
468
469 /// EngineBuilder - Builder class for ExecutionEngines.  Use this by
470 /// stack-allocating a builder, chaining the various set* methods, and
471 /// terminating it with a .create() call.
472 class EngineBuilder {
473 private:
474   Module *M;
475   EngineKind::Kind WhichEngine;
476   std::string *ErrorStr;
477   CodeGenOpt::Level OptLevel;
478   JITMemoryManager *JMM;
479   bool AllocateGVsWithCode;
480   CodeModel::Model CMModel;
481   std::string MArch;
482   std::string MCPU;
483   SmallVector<std::string, 4> MAttrs;
484   bool UseMCJIT;
485
486   /// InitEngine - Does the common initialization of default options.
487   void InitEngine() {
488     WhichEngine = EngineKind::Either;
489     ErrorStr = NULL;
490     OptLevel = CodeGenOpt::Default;
491     JMM = NULL;
492     AllocateGVsWithCode = false;
493     CMModel = CodeModel::Default;
494     UseMCJIT = false;
495   }
496
497 public:
498   /// EngineBuilder - Constructor for EngineBuilder.  If create() is called and
499   /// is successful, the created engine takes ownership of the module.
500   EngineBuilder(Module *m) : M(m) {
501     InitEngine();
502   }
503
504   /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
505   /// or whichever engine works.  This option defaults to EngineKind::Either.
506   EngineBuilder &setEngineKind(EngineKind::Kind w) {
507     WhichEngine = w;
508     return *this;
509   }
510
511   /// setJITMemoryManager - Sets the memory manager to use.  This allows
512   /// clients to customize their memory allocation policies.  If create() is
513   /// called and is successful, the created engine takes ownership of the
514   /// memory manager.  This option defaults to NULL.
515   EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
516     JMM = jmm;
517     return *this;
518   }
519
520   /// setErrorStr - Set the error string to write to on error.  This option
521   /// defaults to NULL.
522   EngineBuilder &setErrorStr(std::string *e) {
523     ErrorStr = e;
524     return *this;
525   }
526
527   /// setOptLevel - Set the optimization level for the JIT.  This option
528   /// defaults to CodeGenOpt::Default.
529   EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
530     OptLevel = l;
531     return *this;
532   }
533
534   /// setCodeModel - Set the CodeModel that the ExecutionEngine target
535   /// data is using. Defaults to target specific default "CodeModel::Default".
536   EngineBuilder &setCodeModel(CodeModel::Model M) {
537     CMModel = M;
538     return *this;
539   }
540
541   /// setAllocateGVsWithCode - Sets whether global values should be allocated
542   /// into the same buffer as code.  For most applications this should be set
543   /// to false.  Allocating globals with code breaks freeMachineCodeForFunction
544   /// and is probably unsafe and bad for performance.  However, we have clients
545   /// who depend on this behavior, so we must support it.  This option defaults
546   /// to false so that users of the new API can safely use the new memory
547   /// manager and free machine code.
548   EngineBuilder &setAllocateGVsWithCode(bool a) {
549     AllocateGVsWithCode = a;
550     return *this;
551   }
552
553   /// setMArch - Override the architecture set by the Module's triple.
554   EngineBuilder &setMArch(StringRef march) {
555     MArch.assign(march.begin(), march.end());
556     return *this;
557   }
558
559   /// setMCPU - Target a specific cpu type.
560   EngineBuilder &setMCPU(StringRef mcpu) {
561     MCPU.assign(mcpu.begin(), mcpu.end());
562     return *this;
563   }
564
565   /// setUseMCJIT - Set whether the MC-JIT implementation should be used
566   /// (experimental).
567   EngineBuilder &setUseMCJIT(bool Value) {
568     UseMCJIT = Value;
569     return *this;
570   }
571
572   /// setMAttrs - Set cpu-specific attributes.
573   template<typename StringSequence>
574   EngineBuilder &setMAttrs(const StringSequence &mattrs) {
575     MAttrs.clear();
576     MAttrs.append(mattrs.begin(), mattrs.end());
577     return *this;
578   }
579
580   ExecutionEngine *create();
581 };
582
583 } // End llvm namespace
584
585 #endif