Re-apply r196639: Add support for archives and object file caching under MCJIT.
[oota-llvm.git] / include / llvm / ExecutionEngine / ExecutionEngine.h
1 //===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the abstract interface that implements execution support
11 // for LLVM.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
16 #define LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
17
18 #include "llvm-c/ExecutionEngine.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/ValueMap.h"
22 #include "llvm/MC/MCCodeGenInfo.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/ValueHandle.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.
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(const MutexGuard &) {
88     return GlobalAddressMap;
89   }
90
91   std::map<void*, AssertingVH<const GlobalValue> > &
92   getGlobalAddressReverseMap(const MutexGuard &) {
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 MutexGuard &, 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 *TD;
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   friend class EngineBuilder;  // To allow access to JITCtor and InterpCtor.
127
128 protected:
129   /// The list of Modules that we are JIT'ing from.  We use a SmallVector to
130   /// optimize for the case where there is only one module.
131   SmallVector<Module*, 1> Modules;
132
133   void setDataLayout(const DataLayout *td) { TD = td; }
134
135   /// getMemoryforGV - Allocate memory for a global variable.
136   virtual char *getMemoryForGV(const GlobalVariable *GV);
137
138   // To avoid having libexecutionengine depend on the JIT and interpreter
139   // libraries, the execution engine implementations set these functions to ctor
140   // pointers at startup time if they are linked in.
141   static ExecutionEngine *(*JITCtor)(
142     Module *M,
143     std::string *ErrorStr,
144     JITMemoryManager *JMM,
145     bool GVsWithCode,
146     TargetMachine *TM);
147   static ExecutionEngine *(*MCJITCtor)(
148     Module *M,
149     std::string *ErrorStr,
150     RTDyldMemoryManager *MCJMM,
151     bool GVsWithCode,
152     TargetMachine *TM);
153   static ExecutionEngine *(*InterpCtor)(Module *M, std::string *ErrorStr);
154
155   /// LazyFunctionCreator - If an unknown function is needed, this function
156   /// pointer is invoked to create it.  If this returns null, the JIT will
157   /// abort.
158   void *(*LazyFunctionCreator)(const std::string &);
159
160 public:
161   /// lock - This lock protects the ExecutionEngine, MCJIT, JIT, JITResolver and
162   /// JITEmitter classes.  It must be held while changing the internal state of
163   /// any of those classes.
164   sys::Mutex lock;
165
166   //===--------------------------------------------------------------------===//
167   //  ExecutionEngine Startup
168   //===--------------------------------------------------------------------===//
169
170   virtual ~ExecutionEngine();
171
172   /// create - This is the factory method for creating an execution engine which
173   /// is appropriate for the current machine.  This takes ownership of the
174   /// module.
175   ///
176   /// \param GVsWithCode - Allocating globals with code breaks
177   /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
178   /// However, we have clients who depend on this behavior, so we must support
179   /// it.  Eventually, when we're willing to break some backwards compatibility,
180   /// this flag should be flipped to false, so that by default
181   /// freeMachineCodeForFunction works.
182   static ExecutionEngine *create(Module *M,
183                                  bool ForceInterpreter = false,
184                                  std::string *ErrorStr = 0,
185                                  CodeGenOpt::Level OptLevel =
186                                  CodeGenOpt::Default,
187                                  bool GVsWithCode = true);
188
189   /// createJIT - This is the factory method for creating a JIT for the current
190   /// machine, it does not fall back to the interpreter.  This takes ownership
191   /// of the Module and JITMemoryManager if successful.
192   ///
193   /// Clients should make sure to initialize targets prior to calling this
194   /// function.
195   static ExecutionEngine *createJIT(Module *M,
196                                     std::string *ErrorStr = 0,
197                                     JITMemoryManager *JMM = 0,
198                                     CodeGenOpt::Level OptLevel =
199                                     CodeGenOpt::Default,
200                                     bool GVsWithCode = true,
201                                     Reloc::Model RM = Reloc::Default,
202                                     CodeModel::Model CMM =
203                                     CodeModel::JITDefault);
204
205   /// addModule - Add a Module to the list of modules that we can JIT from.
206   /// Note that this takes ownership of the Module: when the ExecutionEngine is
207   /// destroyed, it destroys the Module as well.
208   virtual void addModule(Module *M) {
209     Modules.push_back(M);
210   }
211
212   /// addObjectFile - Add an ObjectFile to the execution engine.
213   ///
214   /// This method is only supported by MCJIT.  MCJIT will immediately load the
215   /// object into memory and adds its symbols to the list used to resolve
216   /// external symbols while preparing other objects for execution.
217   ///
218   /// Objects added using this function will not be made executable until
219   /// needed by another object.
220   ///
221   /// MCJIT will take ownership of the ObjectFile.
222   virtual void addObjectFile(object::ObjectFile *O) {
223     llvm_unreachable(
224       "ExecutionEngine subclass doesn't implement addObjectFile.");
225   }
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 TD; }
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 * = 0) { }
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   /// DisableLazyCompilation - When lazy compilation is off (the default), the
466   /// JIT will eagerly compile every function reachable from the argument to
467   /// getPointerToFunction.  If lazy compilation is turned on, the JIT will only
468   /// compile the one function and emit stubs to compile the rest when they're
469   /// first called.  If lazy compilation is turned off again while some lazy
470   /// stubs are still around, and one of those stubs is called, the program will
471   /// abort.
472   ///
473   /// In order to safely compile lazily in a threaded program, the user must
474   /// ensure that 1) only one thread at a time can call any particular lazy
475   /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
476   /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
477   /// lazy stub.  See http://llvm.org/PR5184 for details.
478   void DisableLazyCompilation(bool Disabled = true) {
479     CompilingLazily = !Disabled;
480   }
481   bool isCompilingLazily() const {
482     return CompilingLazily;
483   }
484   // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
485   // Remove this in LLVM 2.8.
486   bool isLazyCompilationDisabled() const {
487     return !CompilingLazily;
488   }
489
490   /// DisableGVCompilation - If called, the JIT will abort if it's asked to
491   /// allocate space and populate a GlobalVariable that is not internal to
492   /// the module.
493   void DisableGVCompilation(bool Disabled = true) {
494     GVCompilationDisabled = Disabled;
495   }
496   bool isGVCompilationDisabled() const {
497     return GVCompilationDisabled;
498   }
499
500   /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
501   /// symbols with dlsym.  A client can still use InstallLazyFunctionCreator to
502   /// resolve symbols in a custom way.
503   void DisableSymbolSearching(bool Disabled = true) {
504     SymbolSearchingDisabled = Disabled;
505   }
506   bool isSymbolSearchingDisabled() const {
507     return SymbolSearchingDisabled;
508   }
509
510   /// InstallLazyFunctionCreator - If an unknown function is needed, the
511   /// specified function pointer is invoked to create it.  If it returns null,
512   /// the JIT will abort.
513   void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
514     LazyFunctionCreator = P;
515   }
516
517 protected:
518   explicit ExecutionEngine(Module *M);
519
520   void emitGlobals();
521
522   void EmitGlobalVariable(const GlobalVariable *GV);
523
524   GenericValue getConstantValue(const Constant *C);
525   void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
526                            Type *Ty);
527 };
528
529 namespace EngineKind {
530   // These are actually bitmasks that get or-ed together.
531   enum Kind {
532     JIT         = 0x1,
533     Interpreter = 0x2
534   };
535   const static Kind Either = (Kind)(JIT | Interpreter);
536 }
537
538 /// EngineBuilder - Builder class for ExecutionEngines.  Use this by
539 /// stack-allocating a builder, chaining the various set* methods, and
540 /// terminating it with a .create() call.
541 class EngineBuilder {
542 private:
543   Module *M;
544   EngineKind::Kind WhichEngine;
545   std::string *ErrorStr;
546   CodeGenOpt::Level OptLevel;
547   RTDyldMemoryManager *MCJMM;
548   JITMemoryManager *JMM;
549   bool AllocateGVsWithCode;
550   TargetOptions Options;
551   Reloc::Model RelocModel;
552   CodeModel::Model CMModel;
553   std::string MArch;
554   std::string MCPU;
555   SmallVector<std::string, 4> MAttrs;
556   bool UseMCJIT;
557
558   /// InitEngine - Does the common initialization of default options.
559   void InitEngine() {
560     WhichEngine = EngineKind::Either;
561     ErrorStr = NULL;
562     OptLevel = CodeGenOpt::Default;
563     MCJMM = NULL;
564     JMM = NULL;
565     Options = TargetOptions();
566     AllocateGVsWithCode = false;
567     RelocModel = Reloc::Default;
568     CMModel = CodeModel::JITDefault;
569     UseMCJIT = false;
570   }
571
572 public:
573   /// EngineBuilder - Constructor for EngineBuilder.  If create() is called and
574   /// is successful, the created engine takes ownership of the module.
575   EngineBuilder(Module *m) : M(m) {
576     InitEngine();
577   }
578
579   /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
580   /// or whichever engine works.  This option defaults to EngineKind::Either.
581   EngineBuilder &setEngineKind(EngineKind::Kind w) {
582     WhichEngine = w;
583     return *this;
584   }
585
586   /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
587   /// clients to customize their memory allocation policies for the MCJIT. This
588   /// is only appropriate for the MCJIT; setting this and configuring the builder
589   /// to create anything other than MCJIT will cause a runtime error. If create()
590   /// is called and is successful, the created engine takes ownership of the
591   /// memory manager. This option defaults to NULL. Using this option nullifies
592   /// the setJITMemoryManager() option.
593   EngineBuilder &setMCJITMemoryManager(RTDyldMemoryManager *mcjmm) {
594     MCJMM = mcjmm;
595     JMM = NULL;
596     return *this;
597   }
598
599   /// setJITMemoryManager - Sets the JIT memory manager to use.  This allows
600   /// clients to customize their memory allocation policies.  This is only
601   /// appropriate for either JIT or MCJIT; setting this and configuring the
602   /// builder to create an interpreter will cause a runtime error. If create()
603   /// is called and is successful, the created engine takes ownership of the
604   /// memory manager.  This option defaults to NULL. This option overrides
605   /// setMCJITMemoryManager() as well.
606   EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
607     MCJMM = NULL;
608     JMM = jmm;
609     return *this;
610   }
611
612   /// setErrorStr - Set the error string to write to on error.  This option
613   /// defaults to NULL.
614   EngineBuilder &setErrorStr(std::string *e) {
615     ErrorStr = e;
616     return *this;
617   }
618
619   /// setOptLevel - Set the optimization level for the JIT.  This option
620   /// defaults to CodeGenOpt::Default.
621   EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
622     OptLevel = l;
623     return *this;
624   }
625
626   /// setTargetOptions - Set the target options that the ExecutionEngine
627   /// target is using. Defaults to TargetOptions().
628   EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
629     Options = Opts;
630     return *this;
631   }
632
633   /// setRelocationModel - Set the relocation model that the ExecutionEngine
634   /// target is using. Defaults to target specific default "Reloc::Default".
635   EngineBuilder &setRelocationModel(Reloc::Model RM) {
636     RelocModel = RM;
637     return *this;
638   }
639
640   /// setCodeModel - Set the CodeModel that the ExecutionEngine target
641   /// data is using. Defaults to target specific default
642   /// "CodeModel::JITDefault".
643   EngineBuilder &setCodeModel(CodeModel::Model M) {
644     CMModel = M;
645     return *this;
646   }
647
648   /// setAllocateGVsWithCode - Sets whether global values should be allocated
649   /// into the same buffer as code.  For most applications this should be set
650   /// to false.  Allocating globals with code breaks freeMachineCodeForFunction
651   /// and is probably unsafe and bad for performance.  However, we have clients
652   /// who depend on this behavior, so we must support it.  This option defaults
653   /// to false so that users of the new API can safely use the new memory
654   /// manager and free machine code.
655   EngineBuilder &setAllocateGVsWithCode(bool a) {
656     AllocateGVsWithCode = a;
657     return *this;
658   }
659
660   /// setMArch - Override the architecture set by the Module's triple.
661   EngineBuilder &setMArch(StringRef march) {
662     MArch.assign(march.begin(), march.end());
663     return *this;
664   }
665
666   /// setMCPU - Target a specific cpu type.
667   EngineBuilder &setMCPU(StringRef mcpu) {
668     MCPU.assign(mcpu.begin(), mcpu.end());
669     return *this;
670   }
671
672   /// setUseMCJIT - Set whether the MC-JIT implementation should be used
673   /// (experimental).
674   EngineBuilder &setUseMCJIT(bool Value) {
675     UseMCJIT = Value;
676     return *this;
677   }
678
679   /// setMAttrs - Set cpu-specific attributes.
680   template<typename StringSequence>
681   EngineBuilder &setMAttrs(const StringSequence &mattrs) {
682     MAttrs.clear();
683     MAttrs.append(mattrs.begin(), mattrs.end());
684     return *this;
685   }
686
687   TargetMachine *selectTarget();
688
689   /// selectTarget - Pick a target either via -march or by guessing the native
690   /// arch.  Add any CPU features specified via -mcpu or -mattr.
691   TargetMachine *selectTarget(const Triple &TargetTriple,
692                               StringRef MArch,
693                               StringRef MCPU,
694                               const SmallVectorImpl<std::string>& MAttrs);
695
696   ExecutionEngine *create() {
697     return create(selectTarget());
698   }
699
700   ExecutionEngine *create(TargetMachine *TM);
701 };
702
703 // Create wrappers for C Binding types (see CBindingWrapping.h).
704 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
705
706 } // End llvm namespace
707
708 #endif