BreakCriticalEdges.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
  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. // BreakCriticalEdges pass - Break all of the critical edges in the CFG by
  10. // inserting a dummy basic block. This pass may be "required" by passes that
  11. // cannot deal with critical edges. For this usage, the structure type is
  12. // forward declared. This pass obviously invalidates the CFG, but can update
  13. // dominator trees.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
  17. #include "llvm/ADT/SetVector.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/BlockFrequencyInfo.h"
  21. #include "llvm/Analysis/BranchProbabilityInfo.h"
  22. #include "llvm/Analysis/CFG.h"
  23. #include "llvm/Analysis/LoopInfo.h"
  24. #include "llvm/Analysis/MemorySSAUpdater.h"
  25. #include "llvm/Analysis/PostDominators.h"
  26. #include "llvm/IR/CFG.h"
  27. #include "llvm/IR/Dominators.h"
  28. #include "llvm/IR/Instructions.h"
  29. #include "llvm/IR/Type.h"
  30. #include "llvm/InitializePasses.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Transforms/Utils.h"
  33. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  34. #include "llvm/Transforms/Utils/Cloning.h"
  35. #include "llvm/Transforms/Utils/ValueMapper.h"
  36. using namespace llvm;
  37. #define DEBUG_TYPE "break-crit-edges"
  38. STATISTIC(NumBroken, "Number of blocks inserted");
  39. namespace {
  40. struct BreakCriticalEdges : public FunctionPass {
  41. static char ID; // Pass identification, replacement for typeid
  42. BreakCriticalEdges() : FunctionPass(ID) {
  43. initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
  44. }
  45. bool runOnFunction(Function &F) override {
  46. auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  47. auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
  48. auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
  49. auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
  50. auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
  51. auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
  52. unsigned N =
  53. SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI, nullptr, PDT));
  54. NumBroken += N;
  55. return N > 0;
  56. }
  57. void getAnalysisUsage(AnalysisUsage &AU) const override {
  58. AU.addPreserved<DominatorTreeWrapperPass>();
  59. AU.addPreserved<LoopInfoWrapperPass>();
  60. // No loop canonicalization guarantees are broken by this pass.
  61. AU.addPreservedID(LoopSimplifyID);
  62. }
  63. };
  64. }
  65. char BreakCriticalEdges::ID = 0;
  66. INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
  67. "Break critical edges in CFG", false, false)
  68. // Publicly exposed interface to pass...
  69. char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
  70. FunctionPass *llvm::createBreakCriticalEdgesPass() {
  71. return new BreakCriticalEdges();
  72. }
  73. PreservedAnalyses BreakCriticalEdgesPass::run(Function &F,
  74. FunctionAnalysisManager &AM) {
  75. auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
  76. auto *LI = AM.getCachedResult<LoopAnalysis>(F);
  77. unsigned N = SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
  78. NumBroken += N;
  79. if (N == 0)
  80. return PreservedAnalyses::all();
  81. PreservedAnalyses PA;
  82. PA.preserve<DominatorTreeAnalysis>();
  83. PA.preserve<LoopAnalysis>();
  84. return PA;
  85. }
  86. //===----------------------------------------------------------------------===//
  87. // Implementation of the external critical edge manipulation functions
  88. //===----------------------------------------------------------------------===//
  89. /// When a loop exit edge is split, LCSSA form may require new PHIs in the new
  90. /// exit block. This function inserts the new PHIs, as needed. Preds is a list
  91. /// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
  92. /// the old loop exit, now the successor of SplitBB.
  93. static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
  94. BasicBlock *SplitBB,
  95. BasicBlock *DestBB) {
  96. // SplitBB shouldn't have anything non-trivial in it yet.
  97. assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
  98. SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
  99. // For each PHI in the destination block.
  100. for (PHINode &PN : DestBB->phis()) {
  101. unsigned Idx = PN.getBasicBlockIndex(SplitBB);
  102. Value *V = PN.getIncomingValue(Idx);
  103. // If the input is a PHI which already satisfies LCSSA, don't create
  104. // a new one.
  105. if (const PHINode *VP = dyn_cast<PHINode>(V))
  106. if (VP->getParent() == SplitBB)
  107. continue;
  108. // Otherwise a new PHI is needed. Create one and populate it.
  109. PHINode *NewPN = PHINode::Create(
  110. PN.getType(), Preds.size(), "split",
  111. SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
  112. for (unsigned i = 0, e = Preds.size(); i != e; ++i)
  113. NewPN->addIncoming(V, Preds[i]);
  114. // Update the original PHI.
  115. PN.setIncomingValue(Idx, NewPN);
  116. }
  117. }
  118. BasicBlock *llvm::SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
  119. const CriticalEdgeSplittingOptions &Options,
  120. const Twine &BBName) {
  121. if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
  122. return nullptr;
  123. assert(!isa<IndirectBrInst>(TI) &&
  124. "Cannot split critical edge from IndirectBrInst");
  125. BasicBlock *TIBB = TI->getParent();
  126. BasicBlock *DestBB = TI->getSuccessor(SuccNum);
  127. // Splitting the critical edge to a pad block is non-trivial. Don't do
  128. // it in this generic function.
  129. if (DestBB->isEHPad()) return nullptr;
  130. if (Options.IgnoreUnreachableDests &&
  131. isa<UnreachableInst>(DestBB->getFirstNonPHIOrDbgOrLifetime()))
  132. return nullptr;
  133. auto *LI = Options.LI;
  134. SmallVector<BasicBlock *, 4> LoopPreds;
  135. // Check if extra modifications will be required to preserve loop-simplify
  136. // form after splitting. If it would require splitting blocks with IndirectBr
  137. // or CallBr terminators, bail out if preserving loop-simplify form is
  138. // requested.
  139. if (LI) {
  140. if (Loop *TIL = LI->getLoopFor(TIBB)) {
  141. // The only way that we can break LoopSimplify form by splitting a
  142. // critical edge is if after the split there exists some edge from TIL to
  143. // DestBB *and* the only edge into DestBB from outside of TIL is that of
  144. // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
  145. // is the new exit block and it has no non-loop predecessors. If the
  146. // second isn't true, then DestBB was not in LoopSimplify form prior to
  147. // the split as it had a non-loop predecessor. In both of these cases,
  148. // the predecessor must be directly in TIL, not in a subloop, or again
  149. // LoopSimplify doesn't hold.
  150. for (BasicBlock *P : predecessors(DestBB)) {
  151. if (P == TIBB)
  152. continue; // The new block is known.
  153. if (LI->getLoopFor(P) != TIL) {
  154. // No need to re-simplify, it wasn't to start with.
  155. LoopPreds.clear();
  156. break;
  157. }
  158. LoopPreds.push_back(P);
  159. }
  160. // Loop-simplify form can be preserved, if we can split all in-loop
  161. // predecessors.
  162. if (any_of(LoopPreds, [](BasicBlock *Pred) {
  163. const Instruction *T = Pred->getTerminator();
  164. if (const auto *CBR = dyn_cast<CallBrInst>(T))
  165. return CBR->getDefaultDest() != Pred;
  166. return isa<IndirectBrInst>(T);
  167. })) {
  168. if (Options.PreserveLoopSimplify)
  169. return nullptr;
  170. LoopPreds.clear();
  171. }
  172. }
  173. }
  174. // Create a new basic block, linking it into the CFG.
  175. BasicBlock *NewBB = nullptr;
  176. if (BBName.str() != "")
  177. NewBB = BasicBlock::Create(TI->getContext(), BBName);
  178. else
  179. NewBB = BasicBlock::Create(TI->getContext(), TIBB->getName() + "." +
  180. DestBB->getName() +
  181. "_crit_edge");
  182. // Create our unconditional branch.
  183. BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
  184. NewBI->setDebugLoc(TI->getDebugLoc());
  185. // Insert the block into the function... right after the block TI lives in.
  186. Function &F = *TIBB->getParent();
  187. Function::iterator FBBI = TIBB->getIterator();
  188. F.getBasicBlockList().insert(++FBBI, NewBB);
  189. // Branch to the new block, breaking the edge.
  190. TI->setSuccessor(SuccNum, NewBB);
  191. // If there are any PHI nodes in DestBB, we need to update them so that they
  192. // merge incoming values from NewBB instead of from TIBB.
  193. {
  194. unsigned BBIdx = 0;
  195. for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
  196. // We no longer enter through TIBB, now we come in through NewBB.
  197. // Revector exactly one entry in the PHI node that used to come from
  198. // TIBB to come from NewBB.
  199. PHINode *PN = cast<PHINode>(I);
  200. // Reuse the previous value of BBIdx if it lines up. In cases where we
  201. // have multiple phi nodes with *lots* of predecessors, this is a speed
  202. // win because we don't have to scan the PHI looking for TIBB. This
  203. // happens because the BB list of PHI nodes are usually in the same
  204. // order.
  205. if (PN->getIncomingBlock(BBIdx) != TIBB)
  206. BBIdx = PN->getBasicBlockIndex(TIBB);
  207. PN->setIncomingBlock(BBIdx, NewBB);
  208. }
  209. }
  210. // If there are any other edges from TIBB to DestBB, update those to go
  211. // through the split block, making those edges non-critical as well (and
  212. // reducing the number of phi entries in the DestBB if relevant).
  213. if (Options.MergeIdenticalEdges) {
  214. for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
  215. if (TI->getSuccessor(i) != DestBB) continue;
  216. // Remove an entry for TIBB from DestBB phi nodes.
  217. DestBB->removePredecessor(TIBB, Options.KeepOneInputPHIs);
  218. // We found another edge to DestBB, go to NewBB instead.
  219. TI->setSuccessor(i, NewBB);
  220. }
  221. }
  222. // If we have nothing to update, just return.
  223. auto *DT = Options.DT;
  224. auto *PDT = Options.PDT;
  225. auto *MSSAU = Options.MSSAU;
  226. if (MSSAU)
  227. MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
  228. DestBB, NewBB, {TIBB}, Options.MergeIdenticalEdges);
  229. if (!DT && !PDT && !LI)
  230. return NewBB;
  231. if (DT || PDT) {
  232. // Update the DominatorTree.
  233. // ---> NewBB -----\
  234. // / V
  235. // TIBB -------\\------> DestBB
  236. //
  237. // First, inform the DT about the new path from TIBB to DestBB via NewBB,
  238. // then delete the old edge from TIBB to DestBB. By doing this in that order
  239. // DestBB stays reachable in the DT the whole time and its subtree doesn't
  240. // get disconnected.
  241. SmallVector<DominatorTree::UpdateType, 3> Updates;
  242. Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
  243. Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
  244. if (!llvm::is_contained(successors(TIBB), DestBB))
  245. Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
  246. if (DT)
  247. DT->applyUpdates(Updates);
  248. if (PDT)
  249. PDT->applyUpdates(Updates);
  250. }
  251. // Update LoopInfo if it is around.
  252. if (LI) {
  253. if (Loop *TIL = LI->getLoopFor(TIBB)) {
  254. // If one or the other blocks were not in a loop, the new block is not
  255. // either, and thus LI doesn't need to be updated.
  256. if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
  257. if (TIL == DestLoop) {
  258. // Both in the same loop, the NewBB joins loop.
  259. DestLoop->addBasicBlockToLoop(NewBB, *LI);
  260. } else if (TIL->contains(DestLoop)) {
  261. // Edge from an outer loop to an inner loop. Add to the outer loop.
  262. TIL->addBasicBlockToLoop(NewBB, *LI);
  263. } else if (DestLoop->contains(TIL)) {
  264. // Edge from an inner loop to an outer loop. Add to the outer loop.
  265. DestLoop->addBasicBlockToLoop(NewBB, *LI);
  266. } else {
  267. // Edge from two loops with no containment relation. Because these
  268. // are natural loops, we know that the destination block must be the
  269. // header of its loop (adding a branch into a loop elsewhere would
  270. // create an irreducible loop).
  271. assert(DestLoop->getHeader() == DestBB &&
  272. "Should not create irreducible loops!");
  273. if (Loop *P = DestLoop->getParentLoop())
  274. P->addBasicBlockToLoop(NewBB, *LI);
  275. }
  276. }
  277. // If TIBB is in a loop and DestBB is outside of that loop, we may need
  278. // to update LoopSimplify form and LCSSA form.
  279. if (!TIL->contains(DestBB)) {
  280. assert(!TIL->contains(NewBB) &&
  281. "Split point for loop exit is contained in loop!");
  282. // Update LCSSA form in the newly created exit block.
  283. if (Options.PreserveLCSSA) {
  284. createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
  285. }
  286. if (!LoopPreds.empty()) {
  287. assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
  288. BasicBlock *NewExitBB = SplitBlockPredecessors(
  289. DestBB, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
  290. if (Options.PreserveLCSSA)
  291. createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
  292. }
  293. }
  294. }
  295. }
  296. return NewBB;
  297. }
  298. // Return the unique indirectbr predecessor of a block. This may return null
  299. // even if such a predecessor exists, if it's not useful for splitting.
  300. // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
  301. // predecessors of BB.
  302. static BasicBlock *
  303. findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
  304. // If the block doesn't have any PHIs, we don't care about it, since there's
  305. // no point in splitting it.
  306. PHINode *PN = dyn_cast<PHINode>(BB->begin());
  307. if (!PN)
  308. return nullptr;
  309. // Verify we have exactly one IBR predecessor.
  310. // Conservatively bail out if one of the other predecessors is not a "regular"
  311. // terminator (that is, not a switch or a br).
  312. BasicBlock *IBB = nullptr;
  313. for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
  314. BasicBlock *PredBB = PN->getIncomingBlock(Pred);
  315. Instruction *PredTerm = PredBB->getTerminator();
  316. switch (PredTerm->getOpcode()) {
  317. case Instruction::IndirectBr:
  318. if (IBB)
  319. return nullptr;
  320. IBB = PredBB;
  321. break;
  322. case Instruction::Br:
  323. case Instruction::Switch:
  324. OtherPreds.push_back(PredBB);
  325. continue;
  326. default:
  327. return nullptr;
  328. }
  329. }
  330. return IBB;
  331. }
  332. bool llvm::SplitIndirectBrCriticalEdges(Function &F,
  333. BranchProbabilityInfo *BPI,
  334. BlockFrequencyInfo *BFI) {
  335. // Check whether the function has any indirectbrs, and collect which blocks
  336. // they may jump to. Since most functions don't have indirect branches,
  337. // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
  338. SmallSetVector<BasicBlock *, 16> Targets;
  339. for (auto &BB : F) {
  340. auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
  341. if (!IBI)
  342. continue;
  343. for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
  344. Targets.insert(IBI->getSuccessor(Succ));
  345. }
  346. if (Targets.empty())
  347. return false;
  348. bool ShouldUpdateAnalysis = BPI && BFI;
  349. bool Changed = false;
  350. for (BasicBlock *Target : Targets) {
  351. SmallVector<BasicBlock *, 16> OtherPreds;
  352. BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
  353. // If we did not found an indirectbr, or the indirectbr is the only
  354. // incoming edge, this isn't the kind of edge we're looking for.
  355. if (!IBRPred || OtherPreds.empty())
  356. continue;
  357. // Don't even think about ehpads/landingpads.
  358. Instruction *FirstNonPHI = Target->getFirstNonPHI();
  359. if (FirstNonPHI->isEHPad() || Target->isLandingPad())
  360. continue;
  361. // Remember edge probabilities if needed.
  362. SmallVector<BranchProbability, 4> EdgeProbabilities;
  363. if (ShouldUpdateAnalysis) {
  364. EdgeProbabilities.reserve(Target->getTerminator()->getNumSuccessors());
  365. for (unsigned I = 0, E = Target->getTerminator()->getNumSuccessors();
  366. I < E; ++I)
  367. EdgeProbabilities.emplace_back(BPI->getEdgeProbability(Target, I));
  368. BPI->eraseBlock(Target);
  369. }
  370. BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
  371. if (ShouldUpdateAnalysis) {
  372. // Copy the BFI/BPI from Target to BodyBlock.
  373. BPI->setEdgeProbability(BodyBlock, EdgeProbabilities);
  374. BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
  375. }
  376. // It's possible Target was its own successor through an indirectbr.
  377. // In this case, the indirectbr now comes from BodyBlock.
  378. if (IBRPred == Target)
  379. IBRPred = BodyBlock;
  380. // At this point Target only has PHIs, and BodyBlock has the rest of the
  381. // block's body. Create a copy of Target that will be used by the "direct"
  382. // preds.
  383. ValueToValueMapTy VMap;
  384. BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
  385. BlockFrequency BlockFreqForDirectSucc;
  386. for (BasicBlock *Pred : OtherPreds) {
  387. // If the target is a loop to itself, then the terminator of the split
  388. // block (BodyBlock) needs to be updated.
  389. BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
  390. Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
  391. if (ShouldUpdateAnalysis)
  392. BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
  393. BPI->getEdgeProbability(Src, DirectSucc);
  394. }
  395. if (ShouldUpdateAnalysis) {
  396. BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
  397. BlockFrequency NewBlockFreqForTarget =
  398. BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
  399. BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
  400. }
  401. // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
  402. // they are clones, so the number of PHIs are the same.
  403. // (a) Remove the edge coming from IBRPred from the "Direct" PHI
  404. // (b) Leave that as the only edge in the "Indirect" PHI.
  405. // (c) Merge the two in the body block.
  406. BasicBlock::iterator Indirect = Target->begin(),
  407. End = Target->getFirstNonPHI()->getIterator();
  408. BasicBlock::iterator Direct = DirectSucc->begin();
  409. BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
  410. assert(&*End == Target->getTerminator() &&
  411. "Block was expected to only contain PHIs");
  412. while (Indirect != End) {
  413. PHINode *DirPHI = cast<PHINode>(Direct);
  414. PHINode *IndPHI = cast<PHINode>(Indirect);
  415. // Now, clean up - the direct block shouldn't get the indirect value,
  416. // and vice versa.
  417. DirPHI->removeIncomingValue(IBRPred);
  418. Direct++;
  419. // Advance the pointer here, to avoid invalidation issues when the old
  420. // PHI is erased.
  421. Indirect++;
  422. PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
  423. NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
  424. IBRPred);
  425. // Create a PHI in the body block, to merge the direct and indirect
  426. // predecessors.
  427. PHINode *MergePHI =
  428. PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
  429. MergePHI->addIncoming(NewIndPHI, Target);
  430. MergePHI->addIncoming(DirPHI, DirectSucc);
  431. IndPHI->replaceAllUsesWith(MergePHI);
  432. IndPHI->eraseFromParent();
  433. }
  434. Changed = true;
  435. }
  436. return Changed;
  437. }