MCJIT.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. //===-- MCJIT.h - Class definition for the MCJIT ----------------*- 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. #ifndef LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H
  9. #define LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H
  10. #include "llvm/ADT/SmallPtrSet.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  13. #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
  14. #include "llvm/ExecutionEngine/RuntimeDyld.h"
  15. namespace llvm {
  16. class MCJIT;
  17. class Module;
  18. class ObjectCache;
  19. // This is a helper class that the MCJIT execution engine uses for linking
  20. // functions across modules that it owns. It aggregates the memory manager
  21. // that is passed in to the MCJIT constructor and defers most functionality
  22. // to that object.
  23. class LinkingSymbolResolver : public LegacyJITSymbolResolver {
  24. public:
  25. LinkingSymbolResolver(MCJIT &Parent,
  26. std::shared_ptr<LegacyJITSymbolResolver> Resolver)
  27. : ParentEngine(Parent), ClientResolver(std::move(Resolver)) {}
  28. JITSymbol findSymbol(const std::string &Name) override;
  29. // MCJIT doesn't support logical dylibs.
  30. JITSymbol findSymbolInLogicalDylib(const std::string &Name) override {
  31. return nullptr;
  32. }
  33. private:
  34. MCJIT &ParentEngine;
  35. std::shared_ptr<LegacyJITSymbolResolver> ClientResolver;
  36. void anchor() override;
  37. };
  38. // About Module states: added->loaded->finalized.
  39. //
  40. // The purpose of the "added" state is having modules in standby. (added=known
  41. // but not compiled). The idea is that you can add a module to provide function
  42. // definitions but if nothing in that module is referenced by a module in which
  43. // a function is executed (note the wording here because it's not exactly the
  44. // ideal case) then the module never gets compiled. This is sort of lazy
  45. // compilation.
  46. //
  47. // The purpose of the "loaded" state (loaded=compiled and required sections
  48. // copied into local memory but not yet ready for execution) is to have an
  49. // intermediate state wherein clients can remap the addresses of sections, using
  50. // MCJIT::mapSectionAddress, (in preparation for later copying to a new location
  51. // or an external process) before relocations and page permissions are applied.
  52. //
  53. // It might not be obvious at first glance, but the "remote-mcjit" case in the
  54. // lli tool does this. In that case, the intermediate action is taken by the
  55. // RemoteMemoryManager in response to the notifyObjectLoaded function being
  56. // called.
  57. class MCJIT : public ExecutionEngine {
  58. MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
  59. std::shared_ptr<MCJITMemoryManager> MemMgr,
  60. std::shared_ptr<LegacyJITSymbolResolver> Resolver);
  61. typedef llvm::SmallPtrSet<Module *, 4> ModulePtrSet;
  62. class OwningModuleContainer {
  63. public:
  64. OwningModuleContainer() = default;
  65. ~OwningModuleContainer() {
  66. freeModulePtrSet(AddedModules);
  67. freeModulePtrSet(LoadedModules);
  68. freeModulePtrSet(FinalizedModules);
  69. }
  70. ModulePtrSet::iterator begin_added() { return AddedModules.begin(); }
  71. ModulePtrSet::iterator end_added() { return AddedModules.end(); }
  72. iterator_range<ModulePtrSet::iterator> added() {
  73. return make_range(begin_added(), end_added());
  74. }
  75. ModulePtrSet::iterator begin_loaded() { return LoadedModules.begin(); }
  76. ModulePtrSet::iterator end_loaded() { return LoadedModules.end(); }
  77. ModulePtrSet::iterator begin_finalized() { return FinalizedModules.begin(); }
  78. ModulePtrSet::iterator end_finalized() { return FinalizedModules.end(); }
  79. void addModule(std::unique_ptr<Module> M) {
  80. AddedModules.insert(M.release());
  81. }
  82. bool removeModule(Module *M) {
  83. return AddedModules.erase(M) || LoadedModules.erase(M) ||
  84. FinalizedModules.erase(M);
  85. }
  86. bool hasModuleBeenAddedButNotLoaded(Module *M) {
  87. return AddedModules.contains(M);
  88. }
  89. bool hasModuleBeenLoaded(Module *M) {
  90. // If the module is in either the "loaded" or "finalized" sections it
  91. // has been loaded.
  92. return LoadedModules.contains(M) || FinalizedModules.contains(M);
  93. }
  94. bool hasModuleBeenFinalized(Module *M) {
  95. return FinalizedModules.contains(M);
  96. }
  97. bool ownsModule(Module* M) {
  98. return AddedModules.contains(M) || LoadedModules.contains(M) ||
  99. FinalizedModules.contains(M);
  100. }
  101. void markModuleAsLoaded(Module *M) {
  102. // This checks against logic errors in the MCJIT implementation.
  103. // This function should never be called with either a Module that MCJIT
  104. // does not own or a Module that has already been loaded and/or finalized.
  105. assert(AddedModules.count(M) &&
  106. "markModuleAsLoaded: Module not found in AddedModules");
  107. // Remove the module from the "Added" set.
  108. AddedModules.erase(M);
  109. // Add the Module to the "Loaded" set.
  110. LoadedModules.insert(M);
  111. }
  112. void markModuleAsFinalized(Module *M) {
  113. // This checks against logic errors in the MCJIT implementation.
  114. // This function should never be called with either a Module that MCJIT
  115. // does not own, a Module that has not been loaded or a Module that has
  116. // already been finalized.
  117. assert(LoadedModules.count(M) &&
  118. "markModuleAsFinalized: Module not found in LoadedModules");
  119. // Remove the module from the "Loaded" section of the list.
  120. LoadedModules.erase(M);
  121. // Add the Module to the "Finalized" section of the list by inserting it
  122. // before the 'end' iterator.
  123. FinalizedModules.insert(M);
  124. }
  125. void markAllLoadedModulesAsFinalized() {
  126. for (Module *M : LoadedModules)
  127. FinalizedModules.insert(M);
  128. LoadedModules.clear();
  129. }
  130. private:
  131. ModulePtrSet AddedModules;
  132. ModulePtrSet LoadedModules;
  133. ModulePtrSet FinalizedModules;
  134. void freeModulePtrSet(ModulePtrSet& MPS) {
  135. // Go through the module set and delete everything.
  136. for (Module *M : MPS)
  137. delete M;
  138. MPS.clear();
  139. }
  140. };
  141. std::unique_ptr<TargetMachine> TM;
  142. MCContext *Ctx;
  143. std::shared_ptr<MCJITMemoryManager> MemMgr;
  144. LinkingSymbolResolver Resolver;
  145. RuntimeDyld Dyld;
  146. std::vector<JITEventListener*> EventListeners;
  147. OwningModuleContainer OwnedModules;
  148. SmallVector<object::OwningBinary<object::Archive>, 2> Archives;
  149. SmallVector<std::unique_ptr<MemoryBuffer>, 2> Buffers;
  150. SmallVector<std::unique_ptr<object::ObjectFile>, 2> LoadedObjects;
  151. // An optional ObjectCache to be notified of compiled objects and used to
  152. // perform lookup of pre-compiled code to avoid re-compilation.
  153. ObjectCache *ObjCache;
  154. Function *FindFunctionNamedInModulePtrSet(StringRef FnName,
  155. ModulePtrSet::iterator I,
  156. ModulePtrSet::iterator E);
  157. GlobalVariable *FindGlobalVariableNamedInModulePtrSet(StringRef Name,
  158. bool AllowInternal,
  159. ModulePtrSet::iterator I,
  160. ModulePtrSet::iterator E);
  161. void runStaticConstructorsDestructorsInModulePtrSet(bool isDtors,
  162. ModulePtrSet::iterator I,
  163. ModulePtrSet::iterator E);
  164. public:
  165. ~MCJIT() override;
  166. /// @name ExecutionEngine interface implementation
  167. /// @{
  168. void addModule(std::unique_ptr<Module> M) override;
  169. void addObjectFile(std::unique_ptr<object::ObjectFile> O) override;
  170. void addObjectFile(object::OwningBinary<object::ObjectFile> O) override;
  171. void addArchive(object::OwningBinary<object::Archive> O) override;
  172. bool removeModule(Module *M) override;
  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. Function *FindFunctionNamed(StringRef FnName) override;
  177. /// FindGlobalVariableNamed - Search all of the active modules to find the
  178. /// global variable that defines Name. This is very slow operation and
  179. /// shouldn't be used for general code.
  180. GlobalVariable *FindGlobalVariableNamed(StringRef Name,
  181. bool AllowInternal = false) override;
  182. /// Sets the object manager that MCJIT should use to avoid compilation.
  183. void setObjectCache(ObjectCache *manager) override;
  184. void setProcessAllSections(bool ProcessAllSections) override {
  185. Dyld.setProcessAllSections(ProcessAllSections);
  186. }
  187. void generateCodeForModule(Module *M) override;
  188. /// finalizeObject - ensure the module is fully processed and is usable.
  189. ///
  190. /// It is the user-level function for completing the process of making the
  191. /// object usable for execution. It should be called after sections within an
  192. /// object have been relocated using mapSectionAddress. When this method is
  193. /// called the MCJIT execution engine will reapply relocations for a loaded
  194. /// object.
  195. /// Is it OK to finalize a set of modules, add modules and finalize again.
  196. // FIXME: Do we really need both of these?
  197. void finalizeObject() override;
  198. virtual void finalizeModule(Module *);
  199. void finalizeLoadedModules();
  200. /// runStaticConstructorsDestructors - This method is used to execute all of
  201. /// the static constructors or destructors for a program.
  202. ///
  203. /// \param isDtors - Run the destructors instead of constructors.
  204. void runStaticConstructorsDestructors(bool isDtors) override;
  205. void *getPointerToFunction(Function *F) override;
  206. GenericValue runFunction(Function *F,
  207. ArrayRef<GenericValue> ArgValues) override;
  208. /// getPointerToNamedFunction - This method returns the address of the
  209. /// specified function by using the dlsym function call. As such it is only
  210. /// useful for resolving library symbols, not code generated symbols.
  211. ///
  212. /// If AbortOnFailure is false and no function with the given name is
  213. /// found, this function silently returns a null pointer. Otherwise,
  214. /// it prints a message to stderr and aborts.
  215. ///
  216. void *getPointerToNamedFunction(StringRef Name,
  217. bool AbortOnFailure = true) override;
  218. /// mapSectionAddress - map a section to its target address space value.
  219. /// Map the address of a JIT section as returned from the memory manager
  220. /// to the address in the target process as the running code will see it.
  221. /// This is the address which will be used for relocation resolution.
  222. void mapSectionAddress(const void *LocalAddress,
  223. uint64_t TargetAddress) override {
  224. Dyld.mapSectionAddress(LocalAddress, TargetAddress);
  225. }
  226. void RegisterJITEventListener(JITEventListener *L) override;
  227. void UnregisterJITEventListener(JITEventListener *L) override;
  228. // If successful, these function will implicitly finalize all loaded objects.
  229. // To get a function address within MCJIT without causing a finalize, use
  230. // getSymbolAddress.
  231. uint64_t getGlobalValueAddress(const std::string &Name) override;
  232. uint64_t getFunctionAddress(const std::string &Name) override;
  233. TargetMachine *getTargetMachine() override { return TM.get(); }
  234. /// @}
  235. /// @name (Private) Registration Interfaces
  236. /// @{
  237. static void Register() {
  238. MCJITCtor = createJIT;
  239. }
  240. static ExecutionEngine *
  241. createJIT(std::unique_ptr<Module> M, std::string *ErrorStr,
  242. std::shared_ptr<MCJITMemoryManager> MemMgr,
  243. std::shared_ptr<LegacyJITSymbolResolver> Resolver,
  244. std::unique_ptr<TargetMachine> TM);
  245. // @}
  246. // Takes a mangled name and returns the corresponding JITSymbol (if a
  247. // definition of that mangled name has been added to the JIT).
  248. JITSymbol findSymbol(const std::string &Name, bool CheckFunctionsOnly);
  249. // DEPRECATED - Please use findSymbol instead.
  250. //
  251. // This is not directly exposed via the ExecutionEngine API, but it is
  252. // used by the LinkingMemoryManager.
  253. //
  254. // getSymbolAddress takes an unmangled name and returns the corresponding
  255. // JITSymbol if a definition of the name has been added to the JIT.
  256. uint64_t getSymbolAddress(const std::string &Name,
  257. bool CheckFunctionsOnly);
  258. protected:
  259. /// emitObject -- Generate a JITed object in memory from the specified module
  260. /// Currently, MCJIT only supports a single module and the module passed to
  261. /// this function call is expected to be the contained module. The module
  262. /// is passed as a parameter here to prepare for multiple module support in
  263. /// the future.
  264. std::unique_ptr<MemoryBuffer> emitObject(Module *M);
  265. void notifyObjectLoaded(const object::ObjectFile &Obj,
  266. const RuntimeDyld::LoadedObjectInfo &L);
  267. void notifyFreeingObject(const object::ObjectFile &Obj);
  268. JITSymbol findExistingSymbol(const std::string &Name);
  269. Module *findModuleForSymbol(const std::string &Name, bool CheckFunctionsOnly);
  270. };
  271. } // end llvm namespace
  272. #endif // LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H