CompileOnDemandLayer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. //===----- CompileOnDemandLayer.cpp - Lazily emit IR on first call --------===//
  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. #include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h"
  9. #include "llvm/IR/Mangler.h"
  10. #include "llvm/IR/Module.h"
  11. using namespace llvm;
  12. using namespace llvm::orc;
  13. static ThreadSafeModule extractSubModule(ThreadSafeModule &TSM,
  14. StringRef Suffix,
  15. GVPredicate ShouldExtract) {
  16. auto DeleteExtractedDefs = [](GlobalValue &GV) {
  17. // Bump the linkage: this global will be provided by the external module.
  18. GV.setLinkage(GlobalValue::ExternalLinkage);
  19. // Delete the definition in the source module.
  20. if (isa<Function>(GV)) {
  21. auto &F = cast<Function>(GV);
  22. F.deleteBody();
  23. F.setPersonalityFn(nullptr);
  24. } else if (isa<GlobalVariable>(GV)) {
  25. cast<GlobalVariable>(GV).setInitializer(nullptr);
  26. } else if (isa<GlobalAlias>(GV)) {
  27. // We need to turn deleted aliases into function or variable decls based
  28. // on the type of their aliasee.
  29. auto &A = cast<GlobalAlias>(GV);
  30. Constant *Aliasee = A.getAliasee();
  31. assert(A.hasName() && "Anonymous alias?");
  32. assert(Aliasee->hasName() && "Anonymous aliasee");
  33. std::string AliasName = A.getName();
  34. if (isa<Function>(Aliasee)) {
  35. auto *F = cloneFunctionDecl(*A.getParent(), *cast<Function>(Aliasee));
  36. A.replaceAllUsesWith(F);
  37. A.eraseFromParent();
  38. F->setName(AliasName);
  39. } else if (isa<GlobalVariable>(Aliasee)) {
  40. auto *G = cloneGlobalVariableDecl(*A.getParent(),
  41. *cast<GlobalVariable>(Aliasee));
  42. A.replaceAllUsesWith(G);
  43. A.eraseFromParent();
  44. G->setName(AliasName);
  45. } else
  46. llvm_unreachable("Alias to unsupported type");
  47. } else
  48. llvm_unreachable("Unsupported global type");
  49. };
  50. auto NewTSM = cloneToNewContext(TSM, ShouldExtract, DeleteExtractedDefs);
  51. NewTSM.withModuleDo([&](Module &M) {
  52. M.setModuleIdentifier((M.getModuleIdentifier() + Suffix).str());
  53. });
  54. return NewTSM;
  55. }
  56. namespace llvm {
  57. namespace orc {
  58. class PartitioningIRMaterializationUnit : public IRMaterializationUnit {
  59. public:
  60. PartitioningIRMaterializationUnit(ExecutionSession &ES, ThreadSafeModule TSM,
  61. VModuleKey K, CompileOnDemandLayer &Parent)
  62. : IRMaterializationUnit(ES, std::move(TSM), std::move(K)),
  63. Parent(Parent) {}
  64. PartitioningIRMaterializationUnit(
  65. ThreadSafeModule TSM, SymbolFlagsMap SymbolFlags,
  66. SymbolNameToDefinitionMap SymbolToDefinition,
  67. CompileOnDemandLayer &Parent)
  68. : IRMaterializationUnit(std::move(TSM), std::move(K),
  69. std::move(SymbolFlags),
  70. std::move(SymbolToDefinition)),
  71. Parent(Parent) {}
  72. private:
  73. void materialize(MaterializationResponsibility R) override {
  74. Parent.emitPartition(std::move(R), std::move(TSM),
  75. std::move(SymbolToDefinition));
  76. }
  77. void discard(const JITDylib &V, const SymbolStringPtr &Name) override {
  78. // All original symbols were materialized by the CODLayer and should be
  79. // final. The function bodies provided by M should never be overridden.
  80. llvm_unreachable("Discard should never be called on an "
  81. "ExtractingIRMaterializationUnit");
  82. }
  83. mutable std::mutex SourceModuleMutex;
  84. CompileOnDemandLayer &Parent;
  85. };
  86. Optional<CompileOnDemandLayer::GlobalValueSet>
  87. CompileOnDemandLayer::compileRequested(GlobalValueSet Requested) {
  88. return std::move(Requested);
  89. }
  90. Optional<CompileOnDemandLayer::GlobalValueSet>
  91. CompileOnDemandLayer::compileWholeModule(GlobalValueSet Requested) {
  92. return None;
  93. }
  94. CompileOnDemandLayer::CompileOnDemandLayer(
  95. ExecutionSession &ES, IRLayer &BaseLayer, LazyCallThroughManager &LCTMgr,
  96. IndirectStubsManagerBuilder BuildIndirectStubsManager)
  97. : IRLayer(ES), BaseLayer(BaseLayer), LCTMgr(LCTMgr),
  98. BuildIndirectStubsManager(std::move(BuildIndirectStubsManager)) {}
  99. void CompileOnDemandLayer::setPartitionFunction(PartitionFunction Partition) {
  100. this->Partition = std::move(Partition);
  101. }
  102. void CompileOnDemandLayer::setImplMap(ImplSymbolMap *Imp) {
  103. this->AliaseeImpls = Imp;
  104. }
  105. void CompileOnDemandLayer::emit(MaterializationResponsibility R,
  106. ThreadSafeModule TSM) {
  107. assert(TSM && "Null module");
  108. auto &ES = getExecutionSession();
  109. // Sort the callables and non-callables, build re-exports and lodge the
  110. // actual module with the implementation dylib.
  111. auto &PDR = getPerDylibResources(R.getTargetJITDylib());
  112. SymbolAliasMap NonCallables;
  113. SymbolAliasMap Callables;
  114. TSM.withModuleDo([&](Module &M) {
  115. // First, do some cleanup on the module:
  116. cleanUpModule(M);
  117. MangleAndInterner Mangle(ES, M.getDataLayout());
  118. for (auto &GV : M.global_values()) {
  119. if (GV.isDeclaration() || GV.hasLocalLinkage() ||
  120. GV.hasAppendingLinkage())
  121. continue;
  122. auto Name = Mangle(GV.getName());
  123. auto Flags = JITSymbolFlags::fromGlobalValue(GV);
  124. if (Flags.isCallable())
  125. Callables[Name] = SymbolAliasMapEntry(Name, Flags);
  126. else
  127. NonCallables[Name] = SymbolAliasMapEntry(Name, Flags);
  128. }
  129. });
  130. // Create a partitioning materialization unit and lodge it with the
  131. // implementation dylib.
  132. if (auto Err = PDR.getImplDylib().define(
  133. llvm::make_unique<PartitioningIRMaterializationUnit>(
  134. ES, std::move(TSM), R.getVModuleKey(), *this))) {
  135. ES.reportError(std::move(Err));
  136. R.failMaterialization();
  137. return;
  138. }
  139. R.replace(reexports(PDR.getImplDylib(), std::move(NonCallables), true));
  140. R.replace(lazyReexports(LCTMgr, PDR.getISManager(), PDR.getImplDylib(),
  141. std::move(Callables), AliaseeImpls));
  142. }
  143. CompileOnDemandLayer::PerDylibResources &
  144. CompileOnDemandLayer::getPerDylibResources(JITDylib &TargetD) {
  145. auto I = DylibResources.find(&TargetD);
  146. if (I == DylibResources.end()) {
  147. auto &ImplD = getExecutionSession().createJITDylib(
  148. TargetD.getName() + ".impl", false);
  149. TargetD.withSearchOrderDo([&](const JITDylibSearchList &TargetSearchOrder) {
  150. auto NewSearchOrder = TargetSearchOrder;
  151. assert(!NewSearchOrder.empty() &&
  152. NewSearchOrder.front().first == &TargetD &&
  153. NewSearchOrder.front().second == true &&
  154. "TargetD must be at the front of its own search order and match "
  155. "non-exported symbol");
  156. NewSearchOrder.insert(std::next(NewSearchOrder.begin()), {&ImplD, true});
  157. ImplD.setSearchOrder(std::move(NewSearchOrder), false);
  158. });
  159. PerDylibResources PDR(ImplD, BuildIndirectStubsManager());
  160. I = DylibResources.insert(std::make_pair(&TargetD, std::move(PDR))).first;
  161. }
  162. return I->second;
  163. }
  164. void CompileOnDemandLayer::cleanUpModule(Module &M) {
  165. for (auto &F : M.functions()) {
  166. if (F.isDeclaration())
  167. continue;
  168. if (F.hasAvailableExternallyLinkage()) {
  169. F.deleteBody();
  170. F.setPersonalityFn(nullptr);
  171. continue;
  172. }
  173. }
  174. }
  175. void CompileOnDemandLayer::expandPartition(GlobalValueSet &Partition) {
  176. // Expands the partition to ensure the following rules hold:
  177. // (1) If any alias is in the partition, its aliasee is also in the partition.
  178. // (2) If any aliasee is in the partition, its aliases are also in the
  179. // partiton.
  180. // (3) If any global variable is in the partition then all global variables
  181. // are in the partition.
  182. assert(!Partition.empty() && "Unexpected empty partition");
  183. const Module &M = *(*Partition.begin())->getParent();
  184. bool ContainsGlobalVariables = false;
  185. std::vector<const GlobalValue *> GVsToAdd;
  186. for (auto *GV : Partition)
  187. if (isa<GlobalAlias>(GV))
  188. GVsToAdd.push_back(
  189. cast<GlobalValue>(cast<GlobalAlias>(GV)->getAliasee()));
  190. else if (isa<GlobalVariable>(GV))
  191. ContainsGlobalVariables = true;
  192. for (auto &A : M.aliases())
  193. if (Partition.count(cast<GlobalValue>(A.getAliasee())))
  194. GVsToAdd.push_back(&A);
  195. if (ContainsGlobalVariables)
  196. for (auto &G : M.globals())
  197. GVsToAdd.push_back(&G);
  198. for (auto *GV : GVsToAdd)
  199. Partition.insert(GV);
  200. }
  201. void CompileOnDemandLayer::emitPartition(
  202. MaterializationResponsibility R, ThreadSafeModule TSM,
  203. IRMaterializationUnit::SymbolNameToDefinitionMap Defs) {
  204. // FIXME: Need a 'notify lazy-extracting/emitting' callback to tie the
  205. // extracted module key, extracted module, and source module key
  206. // together. This could be used, for example, to provide a specific
  207. // memory manager instance to the linking layer.
  208. auto &ES = getExecutionSession();
  209. GlobalValueSet RequestedGVs;
  210. for (auto &Name : R.getRequestedSymbols()) {
  211. assert(Defs.count(Name) && "No definition for symbol");
  212. RequestedGVs.insert(Defs[Name]);
  213. }
  214. /// Perform partitioning with the context lock held, since the partition
  215. /// function is allowed to access the globals to compute the partition.
  216. auto GVsToExtract =
  217. TSM.withModuleDo([&](Module &M) { return Partition(RequestedGVs); });
  218. // Take a 'None' partition to mean the whole module (as opposed to an empty
  219. // partition, which means "materialize nothing"). Emit the whole module
  220. // unmodified to the base layer.
  221. if (GVsToExtract == None) {
  222. Defs.clear();
  223. BaseLayer.emit(std::move(R), std::move(TSM));
  224. return;
  225. }
  226. // If the partition is empty, return the whole module to the symbol table.
  227. if (GVsToExtract->empty()) {
  228. R.replace(llvm::make_unique<PartitioningIRMaterializationUnit>(
  229. std::move(TSM), R.getSymbols(), std::move(Defs), *this));
  230. return;
  231. }
  232. // Ok -- we actually need to partition the symbols. Promote the symbol
  233. // linkages/names, expand the partition to include any required symbols
  234. // (i.e. symbols that can't be separated from our partition), and
  235. // then extract the partition.
  236. //
  237. // FIXME: We apply this promotion once per partitioning. It's safe, but
  238. // overkill.
  239. auto ExtractedTSM =
  240. TSM.withModuleDo([&](Module &M) -> Expected<ThreadSafeModule> {
  241. auto PromotedGlobals = PromoteSymbols(M);
  242. if (!PromotedGlobals.empty()) {
  243. MangleAndInterner Mangle(ES, M.getDataLayout());
  244. SymbolFlagsMap SymbolFlags;
  245. for (auto &GV : PromotedGlobals)
  246. SymbolFlags[Mangle(GV->getName())] =
  247. JITSymbolFlags::fromGlobalValue(*GV);
  248. if (auto Err = R.defineMaterializing(SymbolFlags))
  249. return std::move(Err);
  250. }
  251. expandPartition(*GVsToExtract);
  252. // Extract the requested partiton (plus any necessary aliases) and
  253. // put the rest back into the impl dylib.
  254. auto ShouldExtract = [&](const GlobalValue &GV) -> bool {
  255. return GVsToExtract->count(&GV);
  256. };
  257. return extractSubModule(TSM, ".submodule", ShouldExtract);
  258. });
  259. if (!ExtractedTSM) {
  260. ES.reportError(ExtractedTSM.takeError());
  261. R.failMaterialization();
  262. return;
  263. }
  264. R.replace(llvm::make_unique<PartitioningIRMaterializationUnit>(
  265. ES, std::move(TSM), R.getVModuleKey(), *this));
  266. BaseLayer.emit(std::move(R), std::move(*ExtractedTSM));
  267. }
  268. } // end namespace orc
  269. } // end namespace llvm