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