ExecutionEngine.h 26 KB

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