JITLinkGeneric.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. dumpGraph(dbgs());
  29. });
  30. prune(*G);
  31. LLVM_DEBUG({
  32. dbgs() << "Link graph \"" << G->getName() << "\" post-pruning:\n";
  33. dumpGraph(dbgs());
  34. });
  35. // Run post-pruning passes.
  36. if (auto Err = runPasses(Passes.PostPrunePasses))
  37. return Ctx->notifyFailed(std::move(Err));
  38. // Sort blocks into segments.
  39. auto Layout = layOutBlocks();
  40. // Allocate memory for segments.
  41. if (auto Err = allocateSegments(Layout))
  42. return Ctx->notifyFailed(std::move(Err));
  43. LLVM_DEBUG({
  44. dbgs() << "Link graph \"" << G->getName()
  45. << "\" before post-allocation passes:\n";
  46. dumpGraph(dbgs());
  47. });
  48. // Run post-allocation passes.
  49. if (auto Err = runPasses(Passes.PostAllocationPasses))
  50. return Ctx->notifyFailed(std::move(Err));
  51. // Notify client that the defined symbols have been assigned addresses.
  52. LLVM_DEBUG(
  53. { dbgs() << "Resolving symbols defined in " << G->getName() << "\n"; });
  54. if (auto Err = Ctx->notifyResolved(*G))
  55. return Ctx->notifyFailed(std::move(Err));
  56. auto ExternalSymbols = getExternalSymbolNames();
  57. LLVM_DEBUG({
  58. dbgs() << "Issuing lookup for external symbols for " << G->getName()
  59. << " (may trigger materialization/linking of other graphs)...\n";
  60. });
  61. // We're about to hand off ownership of ourself to the continuation. Grab a
  62. // pointer to the context so that we can call it to initiate the lookup.
  63. //
  64. // FIXME: Once callee expressions are defined to be sequenced before argument
  65. // expressions (c++17) we can simplify all this to:
  66. //
  67. // Ctx->lookup(std::move(UnresolvedExternals),
  68. // [Self=std::move(Self)](Expected<AsyncLookupResult> Result) {
  69. // Self->linkPhase2(std::move(Self), std::move(Result));
  70. // });
  71. auto *TmpCtx = Ctx.get();
  72. TmpCtx->lookup(std::move(ExternalSymbols),
  73. createLookupContinuation(
  74. [S = std::move(Self), L = std::move(Layout)](
  75. Expected<AsyncLookupResult> LookupResult) mutable {
  76. auto &TmpSelf = *S;
  77. TmpSelf.linkPhase2(std::move(S), std::move(LookupResult),
  78. std::move(L));
  79. }));
  80. }
  81. void JITLinkerBase::linkPhase2(std::unique_ptr<JITLinkerBase> Self,
  82. Expected<AsyncLookupResult> LR,
  83. SegmentLayoutMap Layout) {
  84. LLVM_DEBUG({
  85. dbgs() << "Starting link phase 2 for graph " << G->getName() << "\n";
  86. });
  87. // If the lookup failed, bail out.
  88. if (!LR)
  89. return deallocateAndBailOut(LR.takeError());
  90. // Assign addresses to external addressables.
  91. applyLookupResult(*LR);
  92. // Copy block content to working memory.
  93. copyBlockContentToWorkingMemory(Layout, *Alloc);
  94. LLVM_DEBUG({
  95. dbgs() << "Link graph \"" << G->getName()
  96. << "\" before pre-fixup passes:\n";
  97. dumpGraph(dbgs());
  98. });
  99. if (auto Err = runPasses(Passes.PreFixupPasses))
  100. return deallocateAndBailOut(std::move(Err));
  101. LLVM_DEBUG({
  102. dbgs() << "Link graph \"" << G->getName() << "\" before copy-and-fixup:\n";
  103. dumpGraph(dbgs());
  104. });
  105. // Fix up block content.
  106. if (auto Err = fixUpBlocks(*G))
  107. return deallocateAndBailOut(std::move(Err));
  108. LLVM_DEBUG({
  109. dbgs() << "Link graph \"" << G->getName() << "\" after copy-and-fixup:\n";
  110. dumpGraph(dbgs());
  111. });
  112. if (auto Err = runPasses(Passes.PostFixupPasses))
  113. return deallocateAndBailOut(std::move(Err));
  114. // FIXME: Use move capture once we have c++14.
  115. auto *UnownedSelf = Self.release();
  116. auto Phase3Continuation = [UnownedSelf](Error Err) {
  117. std::unique_ptr<JITLinkerBase> Self(UnownedSelf);
  118. UnownedSelf->linkPhase3(std::move(Self), std::move(Err));
  119. };
  120. Alloc->finalizeAsync(std::move(Phase3Continuation));
  121. }
  122. void JITLinkerBase::linkPhase3(std::unique_ptr<JITLinkerBase> Self, Error Err) {
  123. LLVM_DEBUG({
  124. dbgs() << "Starting link phase 3 for graph " << G->getName() << "\n";
  125. });
  126. if (Err)
  127. return deallocateAndBailOut(std::move(Err));
  128. Ctx->notifyFinalized(std::move(Alloc));
  129. LLVM_DEBUG({ dbgs() << "Link of graph " << G->getName() << " complete\n"; });
  130. }
  131. Error JITLinkerBase::runPasses(LinkGraphPassList &Passes) {
  132. for (auto &P : Passes)
  133. if (auto Err = P(*G))
  134. return Err;
  135. return Error::success();
  136. }
  137. JITLinkerBase::SegmentLayoutMap JITLinkerBase::layOutBlocks() {
  138. SegmentLayoutMap Layout;
  139. /// Partition blocks based on permissions and content vs. zero-fill.
  140. for (auto *B : G->blocks()) {
  141. auto &SegLists = Layout[B->getSection().getProtectionFlags()];
  142. if (!B->isZeroFill())
  143. SegLists.ContentBlocks.push_back(B);
  144. else
  145. SegLists.ZeroFillBlocks.push_back(B);
  146. }
  147. /// Sort blocks within each list.
  148. for (auto &KV : Layout) {
  149. auto CompareBlocks = [](const Block *LHS, const Block *RHS) {
  150. // Sort by section, address and size
  151. if (LHS->getSection().getOrdinal() != RHS->getSection().getOrdinal())
  152. return LHS->getSection().getOrdinal() < RHS->getSection().getOrdinal();
  153. if (LHS->getAddress() != RHS->getAddress())
  154. return LHS->getAddress() < RHS->getAddress();
  155. return LHS->getSize() < RHS->getSize();
  156. };
  157. auto &SegLists = KV.second;
  158. llvm::sort(SegLists.ContentBlocks, CompareBlocks);
  159. llvm::sort(SegLists.ZeroFillBlocks, CompareBlocks);
  160. }
  161. LLVM_DEBUG({
  162. dbgs() << "Computed segment ordering:\n";
  163. for (auto &KV : Layout) {
  164. dbgs() << " Segment "
  165. << static_cast<sys::Memory::ProtectionFlags>(KV.first) << ":\n";
  166. auto &SL = KV.second;
  167. for (auto &SIEntry :
  168. {std::make_pair(&SL.ContentBlocks, "content block"),
  169. std::make_pair(&SL.ZeroFillBlocks, "zero-fill block")}) {
  170. dbgs() << " " << SIEntry.second << ":\n";
  171. for (auto *B : *SIEntry.first)
  172. dbgs() << " " << *B << "\n";
  173. }
  174. }
  175. });
  176. return Layout;
  177. }
  178. Error JITLinkerBase::allocateSegments(const SegmentLayoutMap &Layout) {
  179. // Compute segment sizes and allocate memory.
  180. LLVM_DEBUG(dbgs() << "JIT linker requesting: { ");
  181. JITLinkMemoryManager::SegmentsRequestMap Segments;
  182. for (auto &KV : Layout) {
  183. auto &Prot = KV.first;
  184. auto &SegLists = KV.second;
  185. uint64_t SegAlign = 1;
  186. // Calculate segment content size.
  187. size_t SegContentSize = 0;
  188. for (auto *B : SegLists.ContentBlocks) {
  189. SegAlign = std::max(SegAlign, B->getAlignment());
  190. SegContentSize = alignToBlock(SegContentSize, *B);
  191. SegContentSize += B->getSize();
  192. }
  193. uint64_t SegZeroFillStart = SegContentSize;
  194. uint64_t SegZeroFillEnd = SegZeroFillStart;
  195. for (auto *B : SegLists.ZeroFillBlocks) {
  196. SegAlign = std::max(SegAlign, B->getAlignment());
  197. SegZeroFillEnd = alignToBlock(SegZeroFillEnd, *B);
  198. SegZeroFillEnd += B->getSize();
  199. }
  200. Segments[Prot] = {SegAlign, SegContentSize,
  201. SegZeroFillEnd - SegZeroFillStart};
  202. LLVM_DEBUG({
  203. dbgs() << (&KV == &*Layout.begin() ? "" : "; ")
  204. << static_cast<sys::Memory::ProtectionFlags>(Prot)
  205. << ": alignment = " << SegAlign
  206. << ", content size = " << SegContentSize
  207. << ", zero-fill size = " << (SegZeroFillEnd - SegZeroFillStart);
  208. });
  209. }
  210. LLVM_DEBUG(dbgs() << " }\n");
  211. if (auto AllocOrErr =
  212. Ctx->getMemoryManager().allocate(Ctx->getJITLinkDylib(), Segments))
  213. Alloc = std::move(*AllocOrErr);
  214. else
  215. return AllocOrErr.takeError();
  216. LLVM_DEBUG({
  217. dbgs() << "JIT linker got memory (working -> target):\n";
  218. for (auto &KV : Layout) {
  219. auto Prot = static_cast<sys::Memory::ProtectionFlags>(KV.first);
  220. dbgs() << " " << Prot << ": "
  221. << (const void *)Alloc->getWorkingMemory(Prot).data() << " -> "
  222. << formatv("{0:x16}", Alloc->getTargetMemory(Prot)) << "\n";
  223. }
  224. });
  225. // Update block target addresses.
  226. for (auto &KV : Layout) {
  227. auto &Prot = KV.first;
  228. auto &SL = KV.second;
  229. JITTargetAddress NextBlockAddr =
  230. Alloc->getTargetMemory(static_cast<sys::Memory::ProtectionFlags>(Prot));
  231. for (auto *SIList : {&SL.ContentBlocks, &SL.ZeroFillBlocks})
  232. for (auto *B : *SIList) {
  233. NextBlockAddr = alignToBlock(NextBlockAddr, *B);
  234. B->setAddress(NextBlockAddr);
  235. NextBlockAddr += B->getSize();
  236. }
  237. }
  238. return Error::success();
  239. }
  240. JITLinkContext::LookupMap JITLinkerBase::getExternalSymbolNames() const {
  241. // Identify unresolved external symbols.
  242. JITLinkContext::LookupMap UnresolvedExternals;
  243. for (auto *Sym : G->external_symbols()) {
  244. assert(Sym->getAddress() == 0 &&
  245. "External has already been assigned an address");
  246. assert(Sym->getName() != StringRef() && Sym->getName() != "" &&
  247. "Externals must be named");
  248. SymbolLookupFlags LookupFlags =
  249. Sym->getLinkage() == Linkage::Weak
  250. ? SymbolLookupFlags::WeaklyReferencedSymbol
  251. : SymbolLookupFlags::RequiredSymbol;
  252. UnresolvedExternals[Sym->getName()] = LookupFlags;
  253. }
  254. return UnresolvedExternals;
  255. }
  256. void JITLinkerBase::applyLookupResult(AsyncLookupResult Result) {
  257. for (auto *Sym : G->external_symbols()) {
  258. assert(Sym->getOffset() == 0 &&
  259. "External symbol is not at the start of its addressable block");
  260. assert(Sym->getAddress() == 0 && "Symbol already resolved");
  261. assert(!Sym->isDefined() && "Symbol being resolved is already defined");
  262. auto ResultI = Result.find(Sym->getName());
  263. if (ResultI != Result.end())
  264. Sym->getAddressable().setAddress(ResultI->second.getAddress());
  265. else
  266. assert(Sym->getLinkage() == Linkage::Weak &&
  267. "Failed to resolve non-weak reference");
  268. }
  269. LLVM_DEBUG({
  270. dbgs() << "Externals after applying lookup result:\n";
  271. for (auto *Sym : G->external_symbols())
  272. dbgs() << " " << Sym->getName() << ": "
  273. << formatv("{0:x16}", Sym->getAddress()) << "\n";
  274. });
  275. }
  276. void JITLinkerBase::copyBlockContentToWorkingMemory(
  277. const SegmentLayoutMap &Layout, JITLinkMemoryManager::Allocation &Alloc) {
  278. LLVM_DEBUG(dbgs() << "Copying block content:\n");
  279. for (auto &KV : Layout) {
  280. auto &Prot = KV.first;
  281. auto &SegLayout = KV.second;
  282. auto SegMem =
  283. Alloc.getWorkingMemory(static_cast<sys::Memory::ProtectionFlags>(Prot));
  284. char *LastBlockEnd = SegMem.data();
  285. char *BlockDataPtr = LastBlockEnd;
  286. LLVM_DEBUG({
  287. dbgs() << " Processing segment "
  288. << static_cast<sys::Memory::ProtectionFlags>(Prot) << " [ "
  289. << (const void *)SegMem.data() << " .. "
  290. << (const void *)((char *)SegMem.data() + SegMem.size())
  291. << " ]\n Processing content sections:\n";
  292. });
  293. for (auto *B : SegLayout.ContentBlocks) {
  294. LLVM_DEBUG(dbgs() << " " << *B << ":\n");
  295. // Pad to alignment/alignment-offset.
  296. BlockDataPtr = alignToBlock(BlockDataPtr, *B);
  297. LLVM_DEBUG({
  298. dbgs() << " Bumped block pointer to " << (const void *)BlockDataPtr
  299. << " to meet block alignment " << B->getAlignment()
  300. << " and alignment offset " << B->getAlignmentOffset() << "\n";
  301. });
  302. // Zero pad up to alignment.
  303. LLVM_DEBUG({
  304. if (LastBlockEnd != BlockDataPtr)
  305. dbgs() << " Zero padding from " << (const void *)LastBlockEnd
  306. << " to " << (const void *)BlockDataPtr << "\n";
  307. });
  308. while (LastBlockEnd != BlockDataPtr)
  309. *LastBlockEnd++ = 0;
  310. // Copy initial block content.
  311. LLVM_DEBUG({
  312. dbgs() << " Copying block " << *B << " content, "
  313. << B->getContent().size() << " bytes, from "
  314. << (const void *)B->getContent().data() << " to "
  315. << (const void *)BlockDataPtr << "\n";
  316. });
  317. memcpy(BlockDataPtr, B->getContent().data(), B->getContent().size());
  318. // Point the block's content to the fixed up buffer.
  319. B->setContent(StringRef(BlockDataPtr, B->getContent().size()));
  320. // Update block end pointer.
  321. LastBlockEnd = BlockDataPtr + B->getContent().size();
  322. BlockDataPtr = LastBlockEnd;
  323. }
  324. // Zero pad the rest of the segment.
  325. LLVM_DEBUG({
  326. dbgs() << " Zero padding end of segment from "
  327. << (const void *)LastBlockEnd << " to "
  328. << (const void *)((char *)SegMem.data() + SegMem.size()) << "\n";
  329. });
  330. while (LastBlockEnd != SegMem.data() + SegMem.size())
  331. *LastBlockEnd++ = 0;
  332. }
  333. }
  334. void JITLinkerBase::deallocateAndBailOut(Error Err) {
  335. assert(Err && "Should not be bailing out on success value");
  336. assert(Alloc && "can not call deallocateAndBailOut before allocation");
  337. Ctx->notifyFailed(joinErrors(std::move(Err), Alloc->deallocate()));
  338. }
  339. void JITLinkerBase::dumpGraph(raw_ostream &OS) {
  340. assert(G && "Graph is not set yet");
  341. G->dump(dbgs(), [this](Edge::Kind K) { return getEdgeKindName(K); });
  342. }
  343. void prune(LinkGraph &G) {
  344. std::vector<Symbol *> Worklist;
  345. DenseSet<Block *> VisitedBlocks;
  346. // Build the initial worklist from all symbols initially live.
  347. for (auto *Sym : G.defined_symbols())
  348. if (Sym->isLive())
  349. Worklist.push_back(Sym);
  350. // Propagate live flags to all symbols reachable from the initial live set.
  351. while (!Worklist.empty()) {
  352. auto *Sym = Worklist.back();
  353. Worklist.pop_back();
  354. auto &B = Sym->getBlock();
  355. // Skip addressables that we've visited before.
  356. if (VisitedBlocks.count(&B))
  357. continue;
  358. VisitedBlocks.insert(&B);
  359. for (auto &E : Sym->getBlock().edges()) {
  360. // If the edge target is a defined symbol that is being newly marked live
  361. // then add it to the worklist.
  362. if (E.getTarget().isDefined() && !E.getTarget().isLive())
  363. Worklist.push_back(&E.getTarget());
  364. // Mark the target live.
  365. E.getTarget().setLive(true);
  366. }
  367. }
  368. // Collect all defined symbols to remove, then remove them.
  369. {
  370. LLVM_DEBUG(dbgs() << "Dead-stripping defined symbols:\n");
  371. std::vector<Symbol *> SymbolsToRemove;
  372. for (auto *Sym : G.defined_symbols())
  373. if (!Sym->isLive())
  374. SymbolsToRemove.push_back(Sym);
  375. for (auto *Sym : SymbolsToRemove) {
  376. LLVM_DEBUG(dbgs() << " " << *Sym << "...\n");
  377. G.removeDefinedSymbol(*Sym);
  378. }
  379. }
  380. // Delete any unused blocks.
  381. {
  382. LLVM_DEBUG(dbgs() << "Dead-stripping blocks:\n");
  383. std::vector<Block *> BlocksToRemove;
  384. for (auto *B : G.blocks())
  385. if (!VisitedBlocks.count(B))
  386. BlocksToRemove.push_back(B);
  387. for (auto *B : BlocksToRemove) {
  388. LLVM_DEBUG(dbgs() << " " << *B << "...\n");
  389. G.removeBlock(*B);
  390. }
  391. }
  392. // Collect all external symbols to remove, then remove them.
  393. {
  394. LLVM_DEBUG(dbgs() << "Removing unused external symbols:\n");
  395. std::vector<Symbol *> SymbolsToRemove;
  396. for (auto *Sym : G.external_symbols())
  397. if (!Sym->isLive())
  398. SymbolsToRemove.push_back(Sym);
  399. for (auto *Sym : SymbolsToRemove) {
  400. LLVM_DEBUG(dbgs() << " " << *Sym << "...\n");
  401. G.removeExternalSymbol(*Sym);
  402. }
  403. }
  404. }
  405. } // end namespace jitlink
  406. } // end namespace llvm