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