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