MCJIT.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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() {
  65. }
  66. ~OwningModuleContainer() {
  67. freeModulePtrSet(AddedModules);
  68. freeModulePtrSet(LoadedModules);
  69. freeModulePtrSet(FinalizedModules);
  70. }
  71. ModulePtrSet::iterator begin_added() { return AddedModules.begin(); }
  72. ModulePtrSet::iterator end_added() { return AddedModules.end(); }
  73. iterator_range<ModulePtrSet::iterator> added() {
  74. return make_range(begin_added(), end_added());
  75. }
  76. ModulePtrSet::iterator begin_loaded() { return LoadedModules.begin(); }
  77. ModulePtrSet::iterator end_loaded() { return LoadedModules.end(); }
  78. ModulePtrSet::iterator begin_finalized() { return FinalizedModules.begin(); }
  79. ModulePtrSet::iterator end_finalized() { return FinalizedModules.end(); }
  80. void addModule(std::unique_ptr<Module> M) {
  81. AddedModules.insert(M.release());
  82. }
  83. bool removeModule(Module *M) {
  84. return AddedModules.erase(M) || LoadedModules.erase(M) ||
  85. FinalizedModules.erase(M);
  86. }
  87. bool hasModuleBeenAddedButNotLoaded(Module *M) {
  88. return AddedModules.contains(M);
  89. }
  90. bool hasModuleBeenLoaded(Module *M) {
  91. // If the module is in either the "loaded" or "finalized" sections it
  92. // has been loaded.
  93. return LoadedModules.contains(M) || FinalizedModules.contains(M);
  94. }
  95. bool hasModuleBeenFinalized(Module *M) {
  96. return FinalizedModules.contains(M);
  97. }
  98. bool ownsModule(Module* M) {
  99. return AddedModules.contains(M) || LoadedModules.contains(M) ||
  100. FinalizedModules.contains(M);
  101. }
  102. void markModuleAsLoaded(Module *M) {
  103. // This checks against logic errors in the MCJIT implementation.
  104. // This function should never be called with either a Module that MCJIT
  105. // does not own or a Module that has already been loaded and/or finalized.
  106. assert(AddedModules.count(M) &&
  107. "markModuleAsLoaded: Module not found in AddedModules");
  108. // Remove the module from the "Added" set.
  109. AddedModules.erase(M);
  110. // Add the Module to the "Loaded" set.
  111. LoadedModules.insert(M);
  112. }
  113. void markModuleAsFinalized(Module *M) {
  114. // This checks against logic errors in the MCJIT implementation.
  115. // This function should never be called with either a Module that MCJIT
  116. // does not own, a Module that has not been loaded or a Module that has
  117. // already been finalized.
  118. assert(LoadedModules.count(M) &&
  119. "markModuleAsFinalized: Module not found in LoadedModules");
  120. // Remove the module from the "Loaded" section of the list.
  121. LoadedModules.erase(M);
  122. // Add the Module to the "Finalized" section of the list by inserting it
  123. // before the 'end' iterator.
  124. FinalizedModules.insert(M);
  125. }
  126. void markAllLoadedModulesAsFinalized() {
  127. for (Module *M : LoadedModules)
  128. FinalizedModules.insert(M);
  129. LoadedModules.clear();
  130. }
  131. private:
  132. ModulePtrSet AddedModules;
  133. ModulePtrSet LoadedModules;
  134. ModulePtrSet FinalizedModules;
  135. void freeModulePtrSet(ModulePtrSet& MPS) {
  136. // Go through the module set and delete everything.
  137. for (Module *M : MPS)
  138. delete M;
  139. MPS.clear();
  140. }
  141. };
  142. std::unique_ptr<TargetMachine> TM;
  143. MCContext *Ctx;
  144. std::shared_ptr<MCJITMemoryManager> MemMgr;
  145. LinkingSymbolResolver Resolver;
  146. RuntimeDyld Dyld;
  147. std::vector<JITEventListener*> EventListeners;
  148. OwningModuleContainer OwnedModules;
  149. SmallVector<object::OwningBinary<object::Archive>, 2> Archives;
  150. SmallVector<std::unique_ptr<MemoryBuffer>, 2> Buffers;
  151. SmallVector<std::unique_ptr<object::ObjectFile>, 2> LoadedObjects;
  152. // An optional ObjectCache to be notified of compiled objects and used to
  153. // perform lookup of pre-compiled code to avoid re-compilation.
  154. ObjectCache *ObjCache;
  155. Function *FindFunctionNamedInModulePtrSet(StringRef FnName,
  156. ModulePtrSet::iterator I,
  157. ModulePtrSet::iterator E);
  158. GlobalVariable *FindGlobalVariableNamedInModulePtrSet(StringRef Name,
  159. bool AllowInternal,
  160. ModulePtrSet::iterator I,
  161. ModulePtrSet::iterator E);
  162. void runStaticConstructorsDestructorsInModulePtrSet(bool isDtors,
  163. ModulePtrSet::iterator I,
  164. ModulePtrSet::iterator E);
  165. public:
  166. ~MCJIT() override;
  167. /// @name ExecutionEngine interface implementation
  168. /// @{
  169. void addModule(std::unique_ptr<Module> M) override;
  170. void addObjectFile(std::unique_ptr<object::ObjectFile> O) override;
  171. void addObjectFile(object::OwningBinary<object::ObjectFile> O) override;
  172. void addArchive(object::OwningBinary<object::Archive> O) override;
  173. bool removeModule(Module *M) override;
  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. Function *FindFunctionNamed(StringRef FnName) override;
  178. /// FindGlobalVariableNamed - Search all of the active modules to find the
  179. /// global variable that defines Name. This is very slow operation and
  180. /// shouldn't be used for general code.
  181. GlobalVariable *FindGlobalVariableNamed(StringRef Name,
  182. bool AllowInternal = false) override;
  183. /// Sets the object manager that MCJIT should use to avoid compilation.
  184. void setObjectCache(ObjectCache *manager) override;
  185. void setProcessAllSections(bool ProcessAllSections) override {
  186. Dyld.setProcessAllSections(ProcessAllSections);
  187. }
  188. void generateCodeForModule(Module *M) override;
  189. /// finalizeObject - ensure the module is fully processed and is usable.
  190. ///
  191. /// It is the user-level function for completing the process of making the
  192. /// object usable for execution. It should be called after sections within an
  193. /// object have been relocated using mapSectionAddress. When this method is
  194. /// called the MCJIT execution engine will reapply relocations for a loaded
  195. /// object.
  196. /// Is it OK to finalize a set of modules, add modules and finalize again.
  197. // FIXME: Do we really need both of these?
  198. void finalizeObject() override;
  199. virtual void finalizeModule(Module *);
  200. void finalizeLoadedModules();
  201. /// runStaticConstructorsDestructors - This method is used to execute all of
  202. /// the static constructors or destructors for a program.
  203. ///
  204. /// \param isDtors - Run the destructors instead of constructors.
  205. void runStaticConstructorsDestructors(bool isDtors) override;
  206. void *getPointerToFunction(Function *F) override;
  207. GenericValue runFunction(Function *F,
  208. ArrayRef<GenericValue> ArgValues) override;
  209. /// getPointerToNamedFunction - This method returns the address of the
  210. /// specified function by using the dlsym function call. As such it is only
  211. /// useful for resolving library symbols, not code generated symbols.
  212. ///
  213. /// If AbortOnFailure is false and no function with the given name is
  214. /// found, this function silently returns a null pointer. Otherwise,
  215. /// it prints a message to stderr and aborts.
  216. ///
  217. void *getPointerToNamedFunction(StringRef Name,
  218. bool AbortOnFailure = true) override;
  219. /// mapSectionAddress - map a section to its target address space value.
  220. /// Map the address of a JIT section as returned from the memory manager
  221. /// to the address in the target process as the running code will see it.
  222. /// This is the address which will be used for relocation resolution.
  223. void mapSectionAddress(const void *LocalAddress,
  224. uint64_t TargetAddress) override {
  225. Dyld.mapSectionAddress(LocalAddress, TargetAddress);
  226. }
  227. void RegisterJITEventListener(JITEventListener *L) override;
  228. void UnregisterJITEventListener(JITEventListener *L) override;
  229. // If successful, these function will implicitly finalize all loaded objects.
  230. // To get a function address within MCJIT without causing a finalize, use
  231. // getSymbolAddress.
  232. uint64_t getGlobalValueAddress(const std::string &Name) override;
  233. uint64_t getFunctionAddress(const std::string &Name) override;
  234. TargetMachine *getTargetMachine() override { return TM.get(); }
  235. /// @}
  236. /// @name (Private) Registration Interfaces
  237. /// @{
  238. static void Register() {
  239. MCJITCtor = createJIT;
  240. }
  241. static ExecutionEngine *
  242. createJIT(std::unique_ptr<Module> M, std::string *ErrorStr,
  243. std::shared_ptr<MCJITMemoryManager> MemMgr,
  244. std::shared_ptr<LegacyJITSymbolResolver> Resolver,
  245. std::unique_ptr<TargetMachine> TM);
  246. // @}
  247. // Takes a mangled name and returns the corresponding JITSymbol (if a
  248. // definition of that mangled name has been added to the JIT).
  249. JITSymbol findSymbol(const std::string &Name, bool CheckFunctionsOnly);
  250. // DEPRECATED - Please use findSymbol instead.
  251. //
  252. // This is not directly exposed via the ExecutionEngine API, but it is
  253. // used by the LinkingMemoryManager.
  254. //
  255. // getSymbolAddress takes an unmangled name and returns the corresponding
  256. // JITSymbol if a definition of the name has been added to the JIT.
  257. uint64_t getSymbolAddress(const std::string &Name,
  258. bool CheckFunctionsOnly);
  259. protected:
  260. /// emitObject -- Generate a JITed object in memory from the specified module
  261. /// Currently, MCJIT only supports a single module and the module passed to
  262. /// this function call is expected to be the contained module. The module
  263. /// is passed as a parameter here to prepare for multiple module support in
  264. /// the future.
  265. std::unique_ptr<MemoryBuffer> emitObject(Module *M);
  266. void notifyObjectLoaded(const object::ObjectFile &Obj,
  267. const RuntimeDyld::LoadedObjectInfo &L);
  268. void notifyFreeingObject(const object::ObjectFile &Obj);
  269. JITSymbol findExistingSymbol(const std::string &Name);
  270. Module *findModuleForSymbol(const std::string &Name, bool CheckFunctionsOnly);
  271. };
  272. } // end llvm namespace
  273. #endif // LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H