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