ExecutionEngine.h 26 KB

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