ExecutionEngine.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. //===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the abstract interface that implements execution support
  10. // for LLVM.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
  14. #define LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H
  15. #include "llvm-c/ExecutionEngine.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/Optional.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/StringMap.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/ExecutionEngine/JITSymbol.h"
  22. #include "llvm/ExecutionEngine/OrcV1Deprecation.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/Object/Binary.h"
  26. #include "llvm/Support/CBindingWrapping.h"
  27. #include "llvm/Support/CodeGen.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/Mutex.h"
  30. #include "llvm/Target/TargetMachine.h"
  31. #include "llvm/Target/TargetOptions.h"
  32. #include <algorithm>
  33. #include <cstdint>
  34. #include <functional>
  35. #include <map>
  36. #include <memory>
  37. #include <string>
  38. #include <vector>
  39. namespace llvm {
  40. class Constant;
  41. class Function;
  42. struct GenericValue;
  43. class GlobalValue;
  44. class GlobalVariable;
  45. class JITEventListener;
  46. class MCJITMemoryManager;
  47. class ObjectCache;
  48. class RTDyldMemoryManager;
  49. class Triple;
  50. class Type;
  51. namespace object {
  52. class Archive;
  53. class ObjectFile;
  54. } // end namespace object
  55. /// Helper class for helping synchronize access to the global address map
  56. /// table. Access to this class should be serialized under a mutex.
  57. class ExecutionEngineState {
  58. public:
  59. using GlobalAddressMapTy = StringMap<uint64_t>;
  60. private:
  61. /// GlobalAddressMap - A mapping between LLVM global symbol names values and
  62. /// their actualized version...
  63. GlobalAddressMapTy GlobalAddressMap;
  64. /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
  65. /// used to convert raw addresses into the LLVM global value that is emitted
  66. /// at the address. This map is not computed unless getGlobalValueAtAddress
  67. /// is called at some point.
  68. std::map<uint64_t, std::string> GlobalAddressReverseMap;
  69. public:
  70. GlobalAddressMapTy &getGlobalAddressMap() {
  71. return GlobalAddressMap;
  72. }
  73. std::map<uint64_t, std::string> &getGlobalAddressReverseMap() {
  74. return GlobalAddressReverseMap;
  75. }
  76. /// Erase an entry from the mapping table.
  77. ///
  78. /// \returns The address that \p ToUnmap was happed to.
  79. uint64_t RemoveMapping(StringRef Name);
  80. };
  81. using FunctionCreator = std::function<void *(const std::string &)>;
  82. /// Abstract interface for implementation execution of LLVM modules,
  83. /// designed to support both interpreter and just-in-time (JIT) compiler
  84. /// implementations.
  85. class ExecutionEngine {
  86. /// The state object holding the global address mapping, which must be
  87. /// accessed synchronously.
  88. //
  89. // FIXME: There is no particular need the entire map needs to be
  90. // synchronized. Wouldn't a reader-writer design be better here?
  91. ExecutionEngineState EEState;
  92. /// The target data for the platform for which execution is being performed.
  93. ///
  94. /// Note: the DataLayout is LLVMContext specific because it has an
  95. /// internal cache based on type pointers. It makes unsafe to reuse the
  96. /// ExecutionEngine across context, we don't enforce this rule but undefined
  97. /// behavior can occurs if the user tries to do it.
  98. const DataLayout DL;
  99. /// Whether lazy JIT compilation is enabled.
  100. bool CompilingLazily;
  101. /// Whether JIT compilation of external global variables is allowed.
  102. bool GVCompilationDisabled;
  103. /// Whether the JIT should perform lookups of external symbols (e.g.,
  104. /// using dlsym).
  105. bool SymbolSearchingDisabled;
  106. /// Whether the JIT should verify IR modules during compilation.
  107. bool VerifyModules;
  108. friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
  109. protected:
  110. /// The list of Modules that we are JIT'ing from. We use a SmallVector to
  111. /// optimize for the case where there is only one module.
  112. SmallVector<std::unique_ptr<Module>, 1> Modules;
  113. /// getMemoryforGV - Allocate memory for a global variable.
  114. virtual char *getMemoryForGV(const GlobalVariable *GV);
  115. static ExecutionEngine *(*MCJITCtor)(
  116. std::unique_ptr<Module> M, std::string *ErrorStr,
  117. std::shared_ptr<MCJITMemoryManager> MM,
  118. std::shared_ptr<LegacyJITSymbolResolver> SR,
  119. std::unique_ptr<TargetMachine> TM);
  120. static ExecutionEngine *(*InterpCtor)(std::unique_ptr<Module> M,
  121. std::string *ErrorStr);
  122. /// LazyFunctionCreator - If an unknown function is needed, this function
  123. /// pointer is invoked to create it. If this returns null, the JIT will
  124. /// abort.
  125. FunctionCreator LazyFunctionCreator;
  126. /// getMangledName - Get mangled name.
  127. std::string getMangledName(const GlobalValue *GV);
  128. std::string ErrMsg;
  129. public:
  130. /// lock - This lock protects the ExecutionEngine and MCJIT classes. It must
  131. /// be held while changing the internal state of any of those classes.
  132. sys::Mutex lock;
  133. //===--------------------------------------------------------------------===//
  134. // ExecutionEngine Startup
  135. //===--------------------------------------------------------------------===//
  136. virtual ~ExecutionEngine();
  137. /// Add a Module to the list of modules that we can JIT from.
  138. virtual void addModule(std::unique_ptr<Module> M) {
  139. Modules.push_back(std::move(M));
  140. }
  141. /// addObjectFile - Add an ObjectFile to the execution engine.
  142. ///
  143. /// This method is only supported by MCJIT. MCJIT will immediately load the
  144. /// object into memory and adds its symbols to the list used to resolve
  145. /// external symbols while preparing other objects for execution.
  146. ///
  147. /// Objects added using this function will not be made executable until
  148. /// needed by another object.
  149. ///
  150. /// MCJIT will take ownership of the ObjectFile.
  151. virtual void addObjectFile(std::unique_ptr<object::ObjectFile> O);
  152. virtual void addObjectFile(object::OwningBinary<object::ObjectFile> O);
  153. /// addArchive - Add an Archive to the execution engine.
  154. ///
  155. /// This method is only supported by MCJIT. MCJIT will use the archive to
  156. /// resolve external symbols in objects it is loading. If a symbol is found
  157. /// in the Archive the contained object file will be extracted (in memory)
  158. /// and loaded for possible execution.
  159. virtual void addArchive(object::OwningBinary<object::Archive> A);
  160. //===--------------------------------------------------------------------===//
  161. const DataLayout &getDataLayout() const { return DL; }
  162. /// removeModule - Removes a Module from the list of modules, but does not
  163. /// free the module's memory. Returns true if M is found, in which case the
  164. /// caller assumes responsibility for deleting the module.
  165. //
  166. // FIXME: This stealth ownership transfer is horrible. This will probably be
  167. // fixed by deleting ExecutionEngine.
  168. virtual bool removeModule(Module *M);
  169. /// FindFunctionNamed - Search all of the active modules to find the function that
  170. /// defines FnName. This is very slow operation and shouldn't be used for
  171. /// general code.
  172. virtual Function *FindFunctionNamed(StringRef FnName);
  173. /// FindGlobalVariableNamed - Search all of the active modules to find the global variable
  174. /// that defines Name. This is very slow operation and shouldn't be used for
  175. /// general code.
  176. virtual GlobalVariable *FindGlobalVariableNamed(StringRef Name, bool AllowInternal = false);
  177. /// runFunction - Execute the specified function with the specified arguments,
  178. /// and return the result.
  179. ///
  180. /// For MCJIT execution engines, clients are encouraged to use the
  181. /// "GetFunctionAddress" method (rather than runFunction) and cast the
  182. /// returned uint64_t to the desired function pointer type. However, for
  183. /// backwards compatibility MCJIT's implementation can execute 'main-like'
  184. /// function (i.e. those returning void or int, and taking either no
  185. /// arguments or (int, char*[])).
  186. virtual GenericValue runFunction(Function *F,
  187. ArrayRef<GenericValue> ArgValues) = 0;
  188. /// getPointerToNamedFunction - This method returns the address of the
  189. /// specified function by using the dlsym function call. As such it is only
  190. /// useful for resolving library symbols, not code generated symbols.
  191. ///
  192. /// If AbortOnFailure is false and no function with the given name is
  193. /// found, this function silently returns a null pointer. Otherwise,
  194. /// it prints a message to stderr and aborts.
  195. ///
  196. /// This function is deprecated for the MCJIT execution engine.
  197. virtual void *getPointerToNamedFunction(StringRef Name,
  198. bool AbortOnFailure = true) = 0;
  199. /// mapSectionAddress - map a section to its target address space value.
  200. /// Map the address of a JIT section as returned from the memory manager
  201. /// to the address in the target process as the running code will see it.
  202. /// This is the address which will be used for relocation resolution.
  203. virtual void mapSectionAddress(const void *LocalAddress,
  204. uint64_t TargetAddress) {
  205. llvm_unreachable("Re-mapping of section addresses not supported with this "
  206. "EE!");
  207. }
  208. /// generateCodeForModule - Run code generation for the specified module and
  209. /// load it into memory.
  210. ///
  211. /// When this function has completed, all code and data for the specified
  212. /// module, and any module on which this module depends, will be generated
  213. /// and loaded into memory, but relocations will not yet have been applied
  214. /// and all memory will be readable and writable but not executable.
  215. ///
  216. /// This function is primarily useful when generating code for an external
  217. /// target, allowing the client an opportunity to remap section addresses
  218. /// before relocations are applied. Clients that intend to execute code
  219. /// locally can use the getFunctionAddress call, which will generate code
  220. /// and apply final preparations all in one step.
  221. ///
  222. /// This method has no effect for the interpeter.
  223. virtual void generateCodeForModule(Module *M) {}
  224. /// finalizeObject - ensure the module is fully processed and is usable.
  225. ///
  226. /// It is the user-level function for completing the process of making the
  227. /// object usable for execution. It should be called after sections within an
  228. /// object have been relocated using mapSectionAddress. When this method is
  229. /// called the MCJIT execution engine will reapply relocations for a loaded
  230. /// object. This method has no effect for the interpeter.
  231. ///
  232. /// Returns true on success, false on failure. Error messages can be retrieved
  233. /// by calling getError();
  234. virtual void finalizeObject() {}
  235. /// Returns true if an error has been recorded.
  236. bool hasError() const { return !ErrMsg.empty(); }
  237. /// Clear the error message.
  238. void clearErrorMessage() { ErrMsg.clear(); }
  239. /// Returns the most recent error message.
  240. const std::string &getErrorMessage() const { return ErrMsg; }
  241. /// runStaticConstructorsDestructors - This method is used to execute all of
  242. /// the static constructors or destructors for a program.
  243. ///
  244. /// \param isDtors - Run the destructors instead of constructors.
  245. virtual void runStaticConstructorsDestructors(bool isDtors);
  246. /// This method is used to execute all of the static constructors or
  247. /// destructors for a particular module.
  248. ///
  249. /// \param isDtors - Run the destructors instead of constructors.
  250. void runStaticConstructorsDestructors(Module &module, bool isDtors);
  251. /// runFunctionAsMain - This is a helper function which wraps runFunction to
  252. /// handle the common task of starting up main with the specified argc, argv,
  253. /// and envp parameters.
  254. int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
  255. const char * const * envp);
  256. /// addGlobalMapping - Tell the execution engine that the specified global is
  257. /// at the specified location. This is used internally as functions are JIT'd
  258. /// and as global variables are laid out in memory. It can and should also be
  259. /// used by clients of the EE that want to have an LLVM global overlay
  260. /// existing data in memory. Values to be mapped should be named, and have
  261. /// external or weak linkage. Mappings are automatically removed when their
  262. /// GlobalValue is destroyed.
  263. void addGlobalMapping(const GlobalValue *GV, void *Addr);
  264. void addGlobalMapping(StringRef Name, uint64_t Addr);
  265. /// clearAllGlobalMappings - Clear all global mappings and start over again,
  266. /// for use in dynamic compilation scenarios to move globals.
  267. void clearAllGlobalMappings();
  268. /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
  269. /// particular module, because it has been removed from the JIT.
  270. void clearGlobalMappingsFromModule(Module *M);
  271. /// updateGlobalMapping - Replace an existing mapping for GV with a new
  272. /// address. This updates both maps as required. If "Addr" is null, the
  273. /// entry for the global is removed from the mappings. This returns the old
  274. /// value of the pointer, or null if it was not in the map.
  275. uint64_t updateGlobalMapping(const GlobalValue *GV, void *Addr);
  276. uint64_t updateGlobalMapping(StringRef Name, uint64_t Addr);
  277. /// getAddressToGlobalIfAvailable - This returns the address of the specified
  278. /// global symbol.
  279. uint64_t getAddressToGlobalIfAvailable(StringRef S);
  280. /// getPointerToGlobalIfAvailable - This returns the address of the specified
  281. /// global value if it is has already been codegen'd, otherwise it returns
  282. /// null.
  283. void *getPointerToGlobalIfAvailable(StringRef S);
  284. void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
  285. /// getPointerToGlobal - This returns the address of the specified global
  286. /// value. This may involve code generation if it's a function.
  287. ///
  288. /// This function is deprecated for the MCJIT execution engine. Use
  289. /// getGlobalValueAddress instead.
  290. void *getPointerToGlobal(const GlobalValue *GV);
  291. /// getPointerToFunction - The different EE's represent function bodies in
  292. /// different ways. They should each implement this to say what a function
  293. /// pointer should look like. When F is destroyed, the ExecutionEngine will
  294. /// remove its global mapping and free any machine code. Be sure no threads
  295. /// are running inside F when that happens.
  296. ///
  297. /// This function is deprecated for the MCJIT execution engine. Use
  298. /// getFunctionAddress instead.
  299. virtual void *getPointerToFunction(Function *F) = 0;
  300. /// getPointerToFunctionOrStub - If the specified function has been
  301. /// code-gen'd, return a pointer to the function. If not, compile it, or use
  302. /// a stub to implement lazy compilation if available. See
  303. /// getPointerToFunction for the requirements on destroying F.
  304. ///
  305. /// This function is deprecated for the MCJIT execution engine. Use
  306. /// getFunctionAddress instead.
  307. virtual void *getPointerToFunctionOrStub(Function *F) {
  308. // Default implementation, just codegen the function.
  309. return getPointerToFunction(F);
  310. }
  311. /// getGlobalValueAddress - Return the address of the specified global
  312. /// value. This may involve code generation.
  313. ///
  314. /// This function should not be called with the interpreter engine.
  315. virtual uint64_t getGlobalValueAddress(const std::string &Name) {
  316. // Default implementation for the interpreter. MCJIT will override this.
  317. // JIT and interpreter clients should use getPointerToGlobal instead.
  318. return 0;
  319. }
  320. /// getFunctionAddress - Return the address of the specified function.
  321. /// This may involve code generation.
  322. virtual uint64_t getFunctionAddress(const std::string &Name) {
  323. // Default implementation for the interpreter. MCJIT will override this.
  324. // Interpreter clients should use getPointerToFunction instead.
  325. return 0;
  326. }
  327. /// getGlobalValueAtAddress - Return the LLVM global value object that starts
  328. /// at the specified address.
  329. ///
  330. const GlobalValue *getGlobalValueAtAddress(void *Addr);
  331. /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
  332. /// Ptr is the address of the memory at which to store Val, cast to
  333. /// GenericValue *. It is not a pointer to a GenericValue containing the
  334. /// address at which to store Val.
  335. void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
  336. Type *Ty);
  337. void InitializeMemory(const Constant *Init, void *Addr);
  338. /// getOrEmitGlobalVariable - Return the address of the specified global
  339. /// variable, possibly emitting it to memory if needed. This is used by the
  340. /// Emitter.
  341. ///
  342. /// This function is deprecated for the MCJIT execution engine. Use
  343. /// getGlobalValueAddress instead.
  344. virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
  345. return getPointerToGlobal((const GlobalValue *)GV);
  346. }
  347. /// Registers a listener to be called back on various events within
  348. /// the JIT. See JITEventListener.h for more details. Does not
  349. /// take ownership of the argument. The argument may be NULL, in
  350. /// which case these functions do nothing.
  351. virtual void RegisterJITEventListener(JITEventListener *) {}
  352. virtual void UnregisterJITEventListener(JITEventListener *) {}
  353. /// Sets the pre-compiled object cache. The ownership of the ObjectCache is
  354. /// not changed. Supported by MCJIT but not the interpreter.
  355. virtual void setObjectCache(ObjectCache *) {
  356. llvm_unreachable("No support for an object cache");
  357. }
  358. /// setProcessAllSections (MCJIT Only): By default, only sections that are
  359. /// "required for execution" are passed to the RTDyldMemoryManager, and other
  360. /// sections are discarded. Passing 'true' to this method will cause
  361. /// RuntimeDyld to pass all sections to its RTDyldMemoryManager regardless
  362. /// of whether they are "required to execute" in the usual sense.
  363. ///
  364. /// Rationale: Some MCJIT clients want to be able to inspect metadata
  365. /// sections (e.g. Dwarf, Stack-maps) to enable functionality or analyze
  366. /// performance. Passing these sections to the memory manager allows the
  367. /// client to make policy about the relevant sections, rather than having
  368. /// MCJIT do it.
  369. virtual void setProcessAllSections(bool ProcessAllSections) {
  370. llvm_unreachable("No support for ProcessAllSections option");
  371. }
  372. /// Return the target machine (if available).
  373. virtual TargetMachine *getTargetMachine() { return nullptr; }
  374. /// DisableLazyCompilation - When lazy compilation is off (the default), the
  375. /// JIT will eagerly compile every function reachable from the argument to
  376. /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
  377. /// compile the one function and emit stubs to compile the rest when they're
  378. /// first called. If lazy compilation is turned off again while some lazy
  379. /// stubs are still around, and one of those stubs is called, the program will
  380. /// abort.
  381. ///
  382. /// In order to safely compile lazily in a threaded program, the user must
  383. /// ensure that 1) only one thread at a time can call any particular lazy
  384. /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
  385. /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
  386. /// lazy stub. See http://llvm.org/PR5184 for details.
  387. void DisableLazyCompilation(bool Disabled = true) {
  388. CompilingLazily = !Disabled;
  389. }
  390. bool isCompilingLazily() const {
  391. return CompilingLazily;
  392. }
  393. /// DisableGVCompilation - If called, the JIT will abort if it's asked to
  394. /// allocate space and populate a GlobalVariable that is not internal to
  395. /// the module.
  396. void DisableGVCompilation(bool Disabled = true) {
  397. GVCompilationDisabled = Disabled;
  398. }
  399. bool isGVCompilationDisabled() const {
  400. return GVCompilationDisabled;
  401. }
  402. /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
  403. /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
  404. /// resolve symbols in a custom way.
  405. void DisableSymbolSearching(bool Disabled = true) {
  406. SymbolSearchingDisabled = Disabled;
  407. }
  408. bool isSymbolSearchingDisabled() const {
  409. return SymbolSearchingDisabled;
  410. }
  411. /// Enable/Disable IR module verification.
  412. ///
  413. /// Note: Module verification is enabled by default in Debug builds, and
  414. /// disabled by default in Release. Use this method to override the default.
  415. void setVerifyModules(bool Verify) {
  416. VerifyModules = Verify;
  417. }
  418. bool getVerifyModules() const {
  419. return VerifyModules;
  420. }
  421. /// InstallLazyFunctionCreator - If an unknown function is needed, the
  422. /// specified function pointer is invoked to create it. If it returns null,
  423. /// the JIT will abort.
  424. void InstallLazyFunctionCreator(FunctionCreator C) {
  425. LazyFunctionCreator = std::move(C);
  426. }
  427. protected:
  428. ExecutionEngine(DataLayout DL) : DL(std::move(DL)) {}
  429. explicit ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M);
  430. explicit ExecutionEngine(std::unique_ptr<Module> M);
  431. void emitGlobals();
  432. void emitGlobalVariable(const GlobalVariable *GV);
  433. GenericValue getConstantValue(const Constant *C);
  434. void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
  435. Type *Ty);
  436. private:
  437. void Init(std::unique_ptr<Module> M);
  438. };
  439. namespace EngineKind {
  440. // These are actually bitmasks that get or-ed together.
  441. enum Kind {
  442. JIT = 0x1,
  443. Interpreter = 0x2
  444. };
  445. const static Kind Either = (Kind)(JIT | Interpreter);
  446. } // end namespace EngineKind
  447. /// Builder class for ExecutionEngines. Use this by stack-allocating a builder,
  448. /// chaining the various set* methods, and terminating it with a .create()
  449. /// call.
  450. class EngineBuilder {
  451. private:
  452. std::unique_ptr<Module> M;
  453. EngineKind::Kind WhichEngine;
  454. std::string *ErrorStr;
  455. CodeGenOpt::Level OptLevel;
  456. std::shared_ptr<MCJITMemoryManager> MemMgr;
  457. std::shared_ptr<LegacyJITSymbolResolver> Resolver;
  458. TargetOptions Options;
  459. Optional<Reloc::Model> RelocModel;
  460. Optional<CodeModel::Model> CMModel;
  461. std::string MArch;
  462. std::string MCPU;
  463. SmallVector<std::string, 4> MAttrs;
  464. bool VerifyModules;
  465. bool EmulatedTLS = true;
  466. public:
  467. /// Default constructor for EngineBuilder.
  468. EngineBuilder();
  469. /// Constructor for EngineBuilder.
  470. EngineBuilder(std::unique_ptr<Module> M);
  471. // Out-of-line since we don't have the def'n of RTDyldMemoryManager here.
  472. ~EngineBuilder();
  473. /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
  474. /// or whichever engine works. This option defaults to EngineKind::Either.
  475. EngineBuilder &setEngineKind(EngineKind::Kind w) {
  476. WhichEngine = w;
  477. return *this;
  478. }
  479. /// setMCJITMemoryManager - Sets the MCJIT memory manager to use. This allows
  480. /// clients to customize their memory allocation policies for the MCJIT. This
  481. /// is only appropriate for the MCJIT; setting this and configuring the builder
  482. /// to create anything other than MCJIT will cause a runtime error. If create()
  483. /// is called and is successful, the created engine takes ownership of the
  484. /// memory manager. This option defaults to NULL.
  485. EngineBuilder &setMCJITMemoryManager(std::unique_ptr<RTDyldMemoryManager> mcjmm);
  486. EngineBuilder&
  487. setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM);
  488. EngineBuilder &setSymbolResolver(std::unique_ptr<LegacyJITSymbolResolver> SR);
  489. /// setErrorStr - Set the error string to write to on error. This option
  490. /// defaults to NULL.
  491. EngineBuilder &setErrorStr(std::string *e) {
  492. ErrorStr = e;
  493. return *this;
  494. }
  495. /// setOptLevel - Set the optimization level for the JIT. This option
  496. /// defaults to CodeGenOpt::Default.
  497. EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
  498. OptLevel = l;
  499. return *this;
  500. }
  501. /// setTargetOptions - Set the target options that the ExecutionEngine
  502. /// target is using. Defaults to TargetOptions().
  503. EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
  504. Options = Opts;
  505. return *this;
  506. }
  507. /// setRelocationModel - Set the relocation model that the ExecutionEngine
  508. /// target is using. Defaults to target specific default "Reloc::Default".
  509. EngineBuilder &setRelocationModel(Reloc::Model RM) {
  510. RelocModel = RM;
  511. return *this;
  512. }
  513. /// setCodeModel - Set the CodeModel that the ExecutionEngine target
  514. /// data is using. Defaults to target specific default
  515. /// "CodeModel::JITDefault".
  516. EngineBuilder &setCodeModel(CodeModel::Model M) {
  517. CMModel = M;
  518. return *this;
  519. }
  520. /// setMArch - Override the architecture set by the Module's triple.
  521. EngineBuilder &setMArch(StringRef march) {
  522. MArch.assign(march.begin(), march.end());
  523. return *this;
  524. }
  525. /// setMCPU - Target a specific cpu type.
  526. EngineBuilder &setMCPU(StringRef mcpu) {
  527. MCPU.assign(mcpu.begin(), mcpu.end());
  528. return *this;
  529. }
  530. /// setVerifyModules - Set whether the JIT implementation should verify
  531. /// IR modules during compilation.
  532. EngineBuilder &setVerifyModules(bool Verify) {
  533. VerifyModules = Verify;
  534. return *this;
  535. }
  536. /// setMAttrs - Set cpu-specific attributes.
  537. template<typename StringSequence>
  538. EngineBuilder &setMAttrs(const StringSequence &mattrs) {
  539. MAttrs.clear();
  540. MAttrs.append(mattrs.begin(), mattrs.end());
  541. return *this;
  542. }
  543. void setEmulatedTLS(bool EmulatedTLS) {
  544. this->EmulatedTLS = EmulatedTLS;
  545. }
  546. TargetMachine *selectTarget();
  547. /// selectTarget - Pick a target either via -march or by guessing the native
  548. /// arch. Add any CPU features specified via -mcpu or -mattr.
  549. TargetMachine *selectTarget(const Triple &TargetTriple,
  550. StringRef MArch,
  551. StringRef MCPU,
  552. const SmallVectorImpl<std::string>& MAttrs);
  553. ExecutionEngine *create() {
  554. return create(selectTarget());
  555. }
  556. ExecutionEngine *create(TargetMachine *TM);
  557. };
  558. // Create wrappers for C Binding types (see CBindingWrapping.h).
  559. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionEngine, LLVMExecutionEngineRef)
  560. } // end namespace llvm
  561. #endif // LLVM_EXECUTIONENGINE_EXECUTIONENGINE_H