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