JITLinkGeneric.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. //===--------- JITLinkGeneric.cpp - Generic JIT linker utilities ----------===//
  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. //
  9. // Generic JITLinker utility class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "JITLinkGeneric.h"
  13. #include "llvm/Support/BinaryStreamReader.h"
  14. #include "llvm/Support/MemoryBuffer.h"
  15. #define DEBUG_TYPE "jitlink"
  16. namespace llvm {
  17. namespace jitlink {
  18. JITLinkerBase::~JITLinkerBase() {}
  19. void JITLinkerBase::linkPhase1(std::unique_ptr<JITLinkerBase> Self) {
  20. LLVM_DEBUG({
  21. dbgs() << "Starting link phase 1 for graph " << G->getName() << "\n";
  22. });
  23. // Prune and optimize the graph.
  24. if (auto Err = runPasses(Passes.PrePrunePasses))
  25. return Ctx->notifyFailed(std::move(Err));
  26. LLVM_DEBUG({
  27. dbgs() << "Link graph \"" << G->getName() << "\" pre-pruning:\n";
  28. G->dump(dbgs());
  29. });
  30. prune(*G);
  31. LLVM_DEBUG({
  32. dbgs() << "Link graph \"" << G->getName() << "\" post-pruning:\n";
  33. G->dump(dbgs());
  34. });
  35. // Run post-pruning passes.
  36. if (auto Err = runPasses(Passes.PostPrunePasses))
  37. return Ctx->notifyFailed(std::move(Err));
  38. Ctx->getMemoryManager().allocate(
  39. Ctx->getJITLinkDylib(), *G,
  40. [S = std::move(Self)](AllocResult AR) mutable {
  41. auto *TmpSelf = S.get();
  42. TmpSelf->linkPhase2(std::move(S), std::move(AR));
  43. });
  44. }
  45. void JITLinkerBase::linkPhase2(std::unique_ptr<JITLinkerBase> Self,
  46. AllocResult AR) {
  47. if (AR)
  48. Alloc = std::move(*AR);
  49. else
  50. return Ctx->notifyFailed(AR.takeError());
  51. LLVM_DEBUG({
  52. dbgs() << "Link graph \"" << G->getName()
  53. << "\" before post-allocation passes:\n";
  54. G->dump(dbgs());
  55. });
  56. // Run post-allocation passes.
  57. if (auto Err = runPasses(Passes.PostAllocationPasses))
  58. return Ctx->notifyFailed(std::move(Err));
  59. // Notify client that the defined symbols have been assigned addresses.
  60. LLVM_DEBUG(dbgs() << "Resolving symbols defined in " << G->getName() << "\n");
  61. if (auto Err = Ctx->notifyResolved(*G))
  62. return Ctx->notifyFailed(std::move(Err));
  63. auto ExternalSymbols = getExternalSymbolNames();
  64. // If there are no external symbols then proceed immediately with phase 3.
  65. if (ExternalSymbols.empty()) {
  66. LLVM_DEBUG({
  67. dbgs() << "No external symbols for " << G->getName()
  68. << ". Proceeding immediately with link phase 3.\n";
  69. });
  70. // FIXME: Once callee expressions are defined to be sequenced before
  71. // argument expressions (c++17) we can simplify this. See below.
  72. auto &TmpSelf = *Self;
  73. TmpSelf.linkPhase3(std::move(Self), AsyncLookupResult());
  74. return;
  75. }
  76. // Otherwise look up the externals.
  77. LLVM_DEBUG({
  78. dbgs() << "Issuing lookup for external symbols for " << G->getName()
  79. << " (may trigger materialization/linking of other graphs)...\n";
  80. });
  81. // We're about to hand off ownership of ourself to the continuation. Grab a
  82. // pointer to the context so that we can call it to initiate the lookup.
  83. //
  84. // FIXME: Once callee expressions are defined to be sequenced before argument
  85. // expressions (c++17) we can simplify all this to:
  86. //
  87. // Ctx->lookup(std::move(UnresolvedExternals),
  88. // [Self=std::move(Self)](Expected<AsyncLookupResult> Result) {
  89. // Self->linkPhase3(std::move(Self), std::move(Result));
  90. // });
  91. Ctx->lookup(std::move(ExternalSymbols),
  92. createLookupContinuation(
  93. [S = std::move(Self)](
  94. Expected<AsyncLookupResult> LookupResult) mutable {
  95. auto &TmpSelf = *S;
  96. TmpSelf.linkPhase3(std::move(S), std::move(LookupResult));
  97. }));
  98. }
  99. void JITLinkerBase::linkPhase3(std::unique_ptr<JITLinkerBase> Self,
  100. Expected<AsyncLookupResult> LR) {
  101. LLVM_DEBUG({
  102. dbgs() << "Starting link phase 3 for graph " << G->getName() << "\n";
  103. });
  104. // If the lookup failed, bail out.
  105. if (!LR)
  106. return abandonAllocAndBailOut(std::move(Self), LR.takeError());
  107. // Assign addresses to external addressables.
  108. applyLookupResult(*LR);
  109. LLVM_DEBUG({
  110. dbgs() << "Link graph \"" << G->getName()
  111. << "\" before pre-fixup passes:\n";
  112. G->dump(dbgs());
  113. });
  114. if (auto Err = runPasses(Passes.PreFixupPasses))
  115. return abandonAllocAndBailOut(std::move(Self), std::move(Err));
  116. LLVM_DEBUG({
  117. dbgs() << "Link graph \"" << G->getName() << "\" before copy-and-fixup:\n";
  118. G->dump(dbgs());
  119. });
  120. // Fix up block content.
  121. if (auto Err = fixUpBlocks(*G))
  122. return abandonAllocAndBailOut(std::move(Self), std::move(Err));
  123. LLVM_DEBUG({
  124. dbgs() << "Link graph \"" << G->getName() << "\" after copy-and-fixup:\n";
  125. G->dump(dbgs());
  126. });
  127. if (auto Err = runPasses(Passes.PostFixupPasses))
  128. return abandonAllocAndBailOut(std::move(Self), std::move(Err));
  129. Alloc->finalize([S = std::move(Self)](FinalizeResult FR) mutable {
  130. auto *TmpSelf = S.get();
  131. TmpSelf->linkPhase4(std::move(S), std::move(FR));
  132. });
  133. }
  134. void JITLinkerBase::linkPhase4(std::unique_ptr<JITLinkerBase> Self,
  135. FinalizeResult FR) {
  136. LLVM_DEBUG({
  137. dbgs() << "Starting link phase 4 for graph " << G->getName() << "\n";
  138. });
  139. if (!FR)
  140. return Ctx->notifyFailed(FR.takeError());
  141. Ctx->notifyFinalized(std::move(*FR));
  142. LLVM_DEBUG({ dbgs() << "Link of graph " << G->getName() << " complete\n"; });
  143. }
  144. Error JITLinkerBase::runPasses(LinkGraphPassList &Passes) {
  145. for (auto &P : Passes)
  146. if (auto Err = P(*G))
  147. return Err;
  148. return Error::success();
  149. }
  150. JITLinkContext::LookupMap JITLinkerBase::getExternalSymbolNames() const {
  151. // Identify unresolved external symbols.
  152. JITLinkContext::LookupMap UnresolvedExternals;
  153. for (auto *Sym : G->external_symbols()) {
  154. assert(!Sym->getAddress() &&
  155. "External has already been assigned an address");
  156. assert(Sym->getName() != StringRef() && Sym->getName() != "" &&
  157. "Externals must be named");
  158. SymbolLookupFlags LookupFlags =
  159. Sym->getLinkage() == Linkage::Weak
  160. ? SymbolLookupFlags::WeaklyReferencedSymbol
  161. : SymbolLookupFlags::RequiredSymbol;
  162. UnresolvedExternals[Sym->getName()] = LookupFlags;
  163. }
  164. return UnresolvedExternals;
  165. }
  166. void JITLinkerBase::applyLookupResult(AsyncLookupResult Result) {
  167. for (auto *Sym : G->external_symbols()) {
  168. assert(Sym->getOffset() == 0 &&
  169. "External symbol is not at the start of its addressable block");
  170. assert(!Sym->getAddress() && "Symbol already resolved");
  171. assert(!Sym->isDefined() && "Symbol being resolved is already defined");
  172. auto ResultI = Result.find(Sym->getName());
  173. if (ResultI != Result.end())
  174. Sym->getAddressable().setAddress(
  175. orc::ExecutorAddr(ResultI->second.getAddress()));
  176. else
  177. assert(Sym->getLinkage() == Linkage::Weak &&
  178. "Failed to resolve non-weak reference");
  179. }
  180. LLVM_DEBUG({
  181. dbgs() << "Externals after applying lookup result:\n";
  182. for (auto *Sym : G->external_symbols())
  183. dbgs() << " " << Sym->getName() << ": "
  184. << formatv("{0:x16}", Sym->getAddress().getValue()) << "\n";
  185. });
  186. }
  187. void JITLinkerBase::abandonAllocAndBailOut(std::unique_ptr<JITLinkerBase> Self,
  188. Error Err) {
  189. assert(Err && "Should not be bailing out on success value");
  190. assert(Alloc && "can not call abandonAllocAndBailOut before allocation");
  191. Alloc->abandon([S = std::move(Self), E1 = std::move(Err)](Error E2) mutable {
  192. S->Ctx->notifyFailed(joinErrors(std::move(E1), std::move(E2)));
  193. });
  194. }
  195. void prune(LinkGraph &G) {
  196. std::vector<Symbol *> Worklist;
  197. DenseSet<Block *> VisitedBlocks;
  198. // Build the initial worklist from all symbols initially live.
  199. for (auto *Sym : G.defined_symbols())
  200. if (Sym->isLive())
  201. Worklist.push_back(Sym);
  202. // Propagate live flags to all symbols reachable from the initial live set.
  203. while (!Worklist.empty()) {
  204. auto *Sym = Worklist.back();
  205. Worklist.pop_back();
  206. auto &B = Sym->getBlock();
  207. // Skip addressables that we've visited before.
  208. if (VisitedBlocks.count(&B))
  209. continue;
  210. VisitedBlocks.insert(&B);
  211. for (auto &E : Sym->getBlock().edges()) {
  212. // If the edge target is a defined symbol that is being newly marked live
  213. // then add it to the worklist.
  214. if (E.getTarget().isDefined() && !E.getTarget().isLive())
  215. Worklist.push_back(&E.getTarget());
  216. // Mark the target live.
  217. E.getTarget().setLive(true);
  218. }
  219. }
  220. // Collect all defined symbols to remove, then remove them.
  221. {
  222. LLVM_DEBUG(dbgs() << "Dead-stripping defined symbols:\n");
  223. std::vector<Symbol *> SymbolsToRemove;
  224. for (auto *Sym : G.defined_symbols())
  225. if (!Sym->isLive())
  226. SymbolsToRemove.push_back(Sym);
  227. for (auto *Sym : SymbolsToRemove) {
  228. LLVM_DEBUG(dbgs() << " " << *Sym << "...\n");
  229. G.removeDefinedSymbol(*Sym);
  230. }
  231. }
  232. // Delete any unused blocks.
  233. {
  234. LLVM_DEBUG(dbgs() << "Dead-stripping blocks:\n");
  235. std::vector<Block *> BlocksToRemove;
  236. for (auto *B : G.blocks())
  237. if (!VisitedBlocks.count(B))
  238. BlocksToRemove.push_back(B);
  239. for (auto *B : BlocksToRemove) {
  240. LLVM_DEBUG(dbgs() << " " << *B << "...\n");
  241. G.removeBlock(*B);
  242. }
  243. }
  244. // Collect all external symbols to remove, then remove them.
  245. {
  246. LLVM_DEBUG(dbgs() << "Removing unused external symbols:\n");
  247. std::vector<Symbol *> SymbolsToRemove;
  248. for (auto *Sym : G.external_symbols())
  249. if (!Sym->isLive())
  250. SymbolsToRemove.push_back(Sym);
  251. for (auto *Sym : SymbolsToRemove) {
  252. LLVM_DEBUG(dbgs() << " " << *Sym << "...\n");
  253. G.removeExternalSymbol(*Sym);
  254. }
  255. }
  256. }
  257. } // end namespace jitlink
  258. } // end namespace llvm