LoopSimplifyCFG.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. //===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification 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. // This file implements the Loop SimplifyCFG Pass. This pass is responsible for
  10. // basic loop CFG cleanup, primarily to assist other loop passes. If you
  11. // encounter a noncanonical CFG construct that causes another loop pass to
  12. // perform suboptimally, this is the place to fix it up.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/DependenceAnalysis.h"
  19. #include "llvm/Analysis/DomTreeUpdater.h"
  20. #include "llvm/Analysis/LoopInfo.h"
  21. #include "llvm/Analysis/LoopIterator.h"
  22. #include "llvm/Analysis/LoopPass.h"
  23. #include "llvm/Analysis/MemorySSA.h"
  24. #include "llvm/Analysis/MemorySSAUpdater.h"
  25. #include "llvm/Analysis/ScalarEvolution.h"
  26. #include "llvm/IR/Dominators.h"
  27. #include "llvm/IR/IRBuilder.h"
  28. #include "llvm/InitializePasses.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Transforms/Scalar.h"
  31. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  32. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  33. #include "llvm/Transforms/Utils/LoopUtils.h"
  34. #include <optional>
  35. using namespace llvm;
  36. #define DEBUG_TYPE "loop-simplifycfg"
  37. static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
  38. cl::init(true));
  39. STATISTIC(NumTerminatorsFolded,
  40. "Number of terminators folded to unconditional branches");
  41. STATISTIC(NumLoopBlocksDeleted,
  42. "Number of loop blocks deleted");
  43. STATISTIC(NumLoopExitsDeleted,
  44. "Number of loop exiting edges deleted");
  45. /// If \p BB is a switch or a conditional branch, but only one of its successors
  46. /// can be reached from this block in runtime, return this successor. Otherwise,
  47. /// return nullptr.
  48. static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
  49. Instruction *TI = BB->getTerminator();
  50. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  51. if (BI->isUnconditional())
  52. return nullptr;
  53. if (BI->getSuccessor(0) == BI->getSuccessor(1))
  54. return BI->getSuccessor(0);
  55. ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
  56. if (!Cond)
  57. return nullptr;
  58. return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
  59. }
  60. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  61. auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
  62. if (!CI)
  63. return nullptr;
  64. for (auto Case : SI->cases())
  65. if (Case.getCaseValue() == CI)
  66. return Case.getCaseSuccessor();
  67. return SI->getDefaultDest();
  68. }
  69. return nullptr;
  70. }
  71. /// Removes \p BB from all loops from [FirstLoop, LastLoop) in parent chain.
  72. static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,
  73. Loop *LastLoop = nullptr) {
  74. assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&
  75. "First loop is supposed to be inside of last loop!");
  76. assert(FirstLoop->contains(BB) && "Must be a loop block!");
  77. for (Loop *Current = FirstLoop; Current != LastLoop;
  78. Current = Current->getParentLoop())
  79. Current->removeBlockFromLoop(BB);
  80. }
  81. /// Find innermost loop that contains at least one block from \p BBs and
  82. /// contains the header of loop \p L.
  83. static Loop *getInnermostLoopFor(SmallPtrSetImpl<BasicBlock *> &BBs,
  84. Loop &L, LoopInfo &LI) {
  85. Loop *Innermost = nullptr;
  86. for (BasicBlock *BB : BBs) {
  87. Loop *BBL = LI.getLoopFor(BB);
  88. while (BBL && !BBL->contains(L.getHeader()))
  89. BBL = BBL->getParentLoop();
  90. if (BBL == &L)
  91. BBL = BBL->getParentLoop();
  92. if (!BBL)
  93. continue;
  94. if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())
  95. Innermost = BBL;
  96. }
  97. return Innermost;
  98. }
  99. namespace {
  100. /// Helper class that can turn branches and switches with constant conditions
  101. /// into unconditional branches.
  102. class ConstantTerminatorFoldingImpl {
  103. private:
  104. Loop &L;
  105. LoopInfo &LI;
  106. DominatorTree &DT;
  107. ScalarEvolution &SE;
  108. MemorySSAUpdater *MSSAU;
  109. LoopBlocksDFS DFS;
  110. DomTreeUpdater DTU;
  111. SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
  112. // Whether or not the current loop has irreducible CFG.
  113. bool HasIrreducibleCFG = false;
  114. // Whether or not the current loop will still exist after terminator constant
  115. // folding will be done. In theory, there are two ways how it can happen:
  116. // 1. Loop's latch(es) become unreachable from loop header;
  117. // 2. Loop's header becomes unreachable from method entry.
  118. // In practice, the second situation is impossible because we only modify the
  119. // current loop and its preheader and do not affect preheader's reachibility
  120. // from any other block. So this variable set to true means that loop's latch
  121. // has become unreachable from loop header.
  122. bool DeleteCurrentLoop = false;
  123. // The blocks of the original loop that will still be reachable from entry
  124. // after the constant folding.
  125. SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
  126. // The blocks of the original loop that will become unreachable from entry
  127. // after the constant folding.
  128. SmallVector<BasicBlock *, 8> DeadLoopBlocks;
  129. // The exits of the original loop that will still be reachable from entry
  130. // after the constant folding.
  131. SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
  132. // The exits of the original loop that will become unreachable from entry
  133. // after the constant folding.
  134. SmallVector<BasicBlock *, 8> DeadExitBlocks;
  135. // The blocks that will still be a part of the current loop after folding.
  136. SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
  137. // The blocks that have terminators with constant condition that can be
  138. // folded. Note: fold candidates should be in L but not in any of its
  139. // subloops to avoid complex LI updates.
  140. SmallVector<BasicBlock *, 8> FoldCandidates;
  141. void dump() const {
  142. dbgs() << "Constant terminator folding for loop " << L << "\n";
  143. dbgs() << "After terminator constant-folding, the loop will";
  144. if (!DeleteCurrentLoop)
  145. dbgs() << " not";
  146. dbgs() << " be destroyed\n";
  147. auto PrintOutVector = [&](const char *Message,
  148. const SmallVectorImpl<BasicBlock *> &S) {
  149. dbgs() << Message << "\n";
  150. for (const BasicBlock *BB : S)
  151. dbgs() << "\t" << BB->getName() << "\n";
  152. };
  153. auto PrintOutSet = [&](const char *Message,
  154. const SmallPtrSetImpl<BasicBlock *> &S) {
  155. dbgs() << Message << "\n";
  156. for (const BasicBlock *BB : S)
  157. dbgs() << "\t" << BB->getName() << "\n";
  158. };
  159. PrintOutVector("Blocks in which we can constant-fold terminator:",
  160. FoldCandidates);
  161. PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
  162. PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
  163. PrintOutSet("Live exit blocks:", LiveExitBlocks);
  164. PrintOutVector("Dead exit blocks:", DeadExitBlocks);
  165. if (!DeleteCurrentLoop)
  166. PrintOutSet("The following blocks will still be part of the loop:",
  167. BlocksInLoopAfterFolding);
  168. }
  169. /// Whether or not the current loop has irreducible CFG.
  170. bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
  171. assert(DFS.isComplete() && "DFS is expected to be finished");
  172. // Index of a basic block in RPO traversal.
  173. DenseMap<const BasicBlock *, unsigned> RPO;
  174. unsigned Current = 0;
  175. for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
  176. RPO[*I] = Current++;
  177. for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
  178. BasicBlock *BB = *I;
  179. for (auto *Succ : successors(BB))
  180. if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
  181. // If an edge goes from a block with greater order number into a block
  182. // with lesses number, and it is not a loop backedge, then it can only
  183. // be a part of irreducible non-loop cycle.
  184. return true;
  185. }
  186. return false;
  187. }
  188. /// Fill all information about status of blocks and exits of the current loop
  189. /// if constant folding of all branches will be done.
  190. void analyze() {
  191. DFS.perform(&LI);
  192. assert(DFS.isComplete() && "DFS is expected to be finished");
  193. // TODO: The algorithm below relies on both RPO and Postorder traversals.
  194. // When the loop has only reducible CFG inside, then the invariant "all
  195. // predecessors of X are processed before X in RPO" is preserved. However
  196. // an irreducible loop can break this invariant (e.g. latch does not have to
  197. // be the last block in the traversal in this case, and the algorithm relies
  198. // on this). We can later decide to support such cases by altering the
  199. // algorithms, but so far we just give up analyzing them.
  200. if (hasIrreducibleCFG(DFS)) {
  201. HasIrreducibleCFG = true;
  202. return;
  203. }
  204. // Collect live and dead loop blocks and exits.
  205. LiveLoopBlocks.insert(L.getHeader());
  206. for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
  207. BasicBlock *BB = *I;
  208. // If a loop block wasn't marked as live so far, then it's dead.
  209. if (!LiveLoopBlocks.count(BB)) {
  210. DeadLoopBlocks.push_back(BB);
  211. continue;
  212. }
  213. BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
  214. // If a block has only one live successor, it's a candidate on constant
  215. // folding. Only handle blocks from current loop: branches in child loops
  216. // are skipped because if they can be folded, they should be folded during
  217. // the processing of child loops.
  218. bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
  219. if (TakeFoldCandidate)
  220. FoldCandidates.push_back(BB);
  221. // Handle successors.
  222. for (BasicBlock *Succ : successors(BB))
  223. if (!TakeFoldCandidate || TheOnlySucc == Succ) {
  224. if (L.contains(Succ))
  225. LiveLoopBlocks.insert(Succ);
  226. else
  227. LiveExitBlocks.insert(Succ);
  228. }
  229. }
  230. // Amount of dead and live loop blocks should match the total number of
  231. // blocks in loop.
  232. assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
  233. "Malformed block sets?");
  234. // Now, all exit blocks that are not marked as live are dead, if all their
  235. // predecessors are in the loop. This may not be the case, as the input loop
  236. // may not by in loop-simplify/canonical form.
  237. SmallVector<BasicBlock *, 8> ExitBlocks;
  238. L.getExitBlocks(ExitBlocks);
  239. SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
  240. for (auto *ExitBlock : ExitBlocks)
  241. if (!LiveExitBlocks.count(ExitBlock) &&
  242. UniqueDeadExits.insert(ExitBlock).second &&
  243. all_of(predecessors(ExitBlock),
  244. [this](BasicBlock *Pred) { return L.contains(Pred); }))
  245. DeadExitBlocks.push_back(ExitBlock);
  246. // Whether or not the edge From->To will still be present in graph after the
  247. // folding.
  248. auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
  249. if (!LiveLoopBlocks.count(From))
  250. return false;
  251. BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
  252. return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
  253. };
  254. // The loop will not be destroyed if its latch is live.
  255. DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
  256. // If we are going to delete the current loop completely, no extra analysis
  257. // is needed.
  258. if (DeleteCurrentLoop)
  259. return;
  260. // Otherwise, we should check which blocks will still be a part of the
  261. // current loop after the transform.
  262. BlocksInLoopAfterFolding.insert(L.getLoopLatch());
  263. // If the loop is live, then we should compute what blocks are still in
  264. // loop after all branch folding has been done. A block is in loop if
  265. // it has a live edge to another block that is in the loop; by definition,
  266. // latch is in the loop.
  267. auto BlockIsInLoop = [&](BasicBlock *BB) {
  268. return any_of(successors(BB), [&](BasicBlock *Succ) {
  269. return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
  270. });
  271. };
  272. for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
  273. BasicBlock *BB = *I;
  274. if (BlockIsInLoop(BB))
  275. BlocksInLoopAfterFolding.insert(BB);
  276. }
  277. assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
  278. "Header not in loop?");
  279. assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
  280. "All blocks that stay in loop should be live!");
  281. }
  282. /// We need to preserve static reachibility of all loop exit blocks (this is)
  283. /// required by loop pass manager. In order to do it, we make the following
  284. /// trick:
  285. ///
  286. /// preheader:
  287. /// <preheader code>
  288. /// br label %loop_header
  289. ///
  290. /// loop_header:
  291. /// ...
  292. /// br i1 false, label %dead_exit, label %loop_block
  293. /// ...
  294. ///
  295. /// We cannot simply remove edge from the loop to dead exit because in this
  296. /// case dead_exit (and its successors) may become unreachable. To avoid that,
  297. /// we insert the following fictive preheader:
  298. ///
  299. /// preheader:
  300. /// <preheader code>
  301. /// switch i32 0, label %preheader-split,
  302. /// [i32 1, label %dead_exit_1],
  303. /// [i32 2, label %dead_exit_2],
  304. /// ...
  305. /// [i32 N, label %dead_exit_N],
  306. ///
  307. /// preheader-split:
  308. /// br label %loop_header
  309. ///
  310. /// loop_header:
  311. /// ...
  312. /// br i1 false, label %dead_exit_N, label %loop_block
  313. /// ...
  314. ///
  315. /// Doing so, we preserve static reachibility of all dead exits and can later
  316. /// remove edges from the loop to these blocks.
  317. void handleDeadExits() {
  318. // If no dead exits, nothing to do.
  319. if (DeadExitBlocks.empty())
  320. return;
  321. // Construct split preheader and the dummy switch to thread edges from it to
  322. // dead exits.
  323. BasicBlock *Preheader = L.getLoopPreheader();
  324. BasicBlock *NewPreheader = llvm::SplitBlock(
  325. Preheader, Preheader->getTerminator(), &DT, &LI, MSSAU);
  326. IRBuilder<> Builder(Preheader->getTerminator());
  327. SwitchInst *DummySwitch =
  328. Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
  329. Preheader->getTerminator()->eraseFromParent();
  330. unsigned DummyIdx = 1;
  331. for (BasicBlock *BB : DeadExitBlocks) {
  332. // Eliminate all Phis and LandingPads from dead exits.
  333. // TODO: Consider removing all instructions in this dead block.
  334. SmallVector<Instruction *, 4> DeadInstructions;
  335. for (auto &PN : BB->phis())
  336. DeadInstructions.push_back(&PN);
  337. if (auto *LandingPad = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()))
  338. DeadInstructions.emplace_back(LandingPad);
  339. for (Instruction *I : DeadInstructions) {
  340. SE.forgetBlockAndLoopDispositions(I);
  341. I->replaceAllUsesWith(PoisonValue::get(I->getType()));
  342. I->eraseFromParent();
  343. }
  344. assert(DummyIdx != 0 && "Too many dead exits!");
  345. DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
  346. DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
  347. ++NumLoopExitsDeleted;
  348. }
  349. assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
  350. if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
  351. // When we break dead edges, the outer loop may become unreachable from
  352. // the current loop. We need to fix loop info accordingly. For this, we
  353. // find the most nested loop that still contains L and remove L from all
  354. // loops that are inside of it.
  355. Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);
  356. // Okay, our loop is no longer in the outer loop (and maybe not in some of
  357. // its parents as well). Make the fixup.
  358. if (StillReachable != OuterLoop) {
  359. LI.changeLoopFor(NewPreheader, StillReachable);
  360. removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
  361. for (auto *BB : L.blocks())
  362. removeBlockFromLoops(BB, OuterLoop, StillReachable);
  363. OuterLoop->removeChildLoop(&L);
  364. if (StillReachable)
  365. StillReachable->addChildLoop(&L);
  366. else
  367. LI.addTopLevelLoop(&L);
  368. // Some values from loops in [OuterLoop, StillReachable) could be used
  369. // in the current loop. Now it is not their child anymore, so such uses
  370. // require LCSSA Phis.
  371. Loop *FixLCSSALoop = OuterLoop;
  372. while (FixLCSSALoop->getParentLoop() != StillReachable)
  373. FixLCSSALoop = FixLCSSALoop->getParentLoop();
  374. assert(FixLCSSALoop && "Should be a loop!");
  375. // We need all DT updates to be done before forming LCSSA.
  376. if (MSSAU)
  377. MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
  378. else
  379. DTU.applyUpdates(DTUpdates);
  380. DTUpdates.clear();
  381. formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
  382. SE.forgetBlockAndLoopDispositions();
  383. }
  384. }
  385. if (MSSAU) {
  386. // Clear all updates now. Facilitates deletes that follow.
  387. MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
  388. DTUpdates.clear();
  389. if (VerifyMemorySSA)
  390. MSSAU->getMemorySSA()->verifyMemorySSA();
  391. }
  392. }
  393. /// Delete loop blocks that have become unreachable after folding. Make all
  394. /// relevant updates to DT and LI.
  395. void deleteDeadLoopBlocks() {
  396. if (MSSAU) {
  397. SmallSetVector<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
  398. DeadLoopBlocks.end());
  399. MSSAU->removeBlocks(DeadLoopBlocksSet);
  400. }
  401. // The function LI.erase has some invariants that need to be preserved when
  402. // it tries to remove a loop which is not the top-level loop. In particular,
  403. // it requires loop's preheader to be strictly in loop's parent. We cannot
  404. // just remove blocks one by one, because after removal of preheader we may
  405. // break this invariant for the dead loop. So we detatch and erase all dead
  406. // loops beforehand.
  407. for (auto *BB : DeadLoopBlocks)
  408. if (LI.isLoopHeader(BB)) {
  409. assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
  410. Loop *DL = LI.getLoopFor(BB);
  411. if (!DL->isOutermost()) {
  412. for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
  413. for (auto *BB : DL->getBlocks())
  414. PL->removeBlockFromLoop(BB);
  415. DL->getParentLoop()->removeChildLoop(DL);
  416. LI.addTopLevelLoop(DL);
  417. }
  418. LI.erase(DL);
  419. }
  420. for (auto *BB : DeadLoopBlocks) {
  421. assert(BB != L.getHeader() &&
  422. "Header of the current loop cannot be dead!");
  423. LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
  424. << "\n");
  425. LI.removeBlock(BB);
  426. }
  427. detachDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
  428. DTU.applyUpdates(DTUpdates);
  429. DTUpdates.clear();
  430. for (auto *BB : DeadLoopBlocks)
  431. DTU.deleteBB(BB);
  432. NumLoopBlocksDeleted += DeadLoopBlocks.size();
  433. }
  434. /// Constant-fold terminators of blocks accumulated in FoldCandidates into the
  435. /// unconditional branches.
  436. void foldTerminators() {
  437. for (BasicBlock *BB : FoldCandidates) {
  438. assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
  439. BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
  440. assert(TheOnlySucc && "Should have one live successor!");
  441. LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
  442. << " with an unconditional branch to the block "
  443. << TheOnlySucc->getName() << "\n");
  444. SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
  445. // Remove all BB's successors except for the live one.
  446. unsigned TheOnlySuccDuplicates = 0;
  447. for (auto *Succ : successors(BB))
  448. if (Succ != TheOnlySucc) {
  449. DeadSuccessors.insert(Succ);
  450. // If our successor lies in a different loop, we don't want to remove
  451. // the one-input Phi because it is a LCSSA Phi.
  452. bool PreserveLCSSAPhi = !L.contains(Succ);
  453. Succ->removePredecessor(BB, PreserveLCSSAPhi);
  454. if (MSSAU)
  455. MSSAU->removeEdge(BB, Succ);
  456. } else
  457. ++TheOnlySuccDuplicates;
  458. assert(TheOnlySuccDuplicates > 0 && "Should be!");
  459. // If TheOnlySucc was BB's successor more than once, after transform it
  460. // will be its successor only once. Remove redundant inputs from
  461. // TheOnlySucc's Phis.
  462. bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
  463. for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
  464. TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
  465. if (MSSAU && TheOnlySuccDuplicates > 1)
  466. MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
  467. IRBuilder<> Builder(BB->getContext());
  468. Instruction *Term = BB->getTerminator();
  469. Builder.SetInsertPoint(Term);
  470. Builder.CreateBr(TheOnlySucc);
  471. Term->eraseFromParent();
  472. for (auto *DeadSucc : DeadSuccessors)
  473. DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
  474. ++NumTerminatorsFolded;
  475. }
  476. }
  477. public:
  478. ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
  479. ScalarEvolution &SE,
  480. MemorySSAUpdater *MSSAU)
  481. : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
  482. DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
  483. bool run() {
  484. assert(L.getLoopLatch() && "Should be single latch!");
  485. // Collect all available information about status of blocks after constant
  486. // folding.
  487. analyze();
  488. BasicBlock *Header = L.getHeader();
  489. (void)Header;
  490. LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()
  491. << ": ");
  492. if (HasIrreducibleCFG) {
  493. LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
  494. return false;
  495. }
  496. // Nothing to constant-fold.
  497. if (FoldCandidates.empty()) {
  498. LLVM_DEBUG(
  499. dbgs() << "No constant terminator folding candidates found in loop "
  500. << Header->getName() << "\n");
  501. return false;
  502. }
  503. // TODO: Support deletion of the current loop.
  504. if (DeleteCurrentLoop) {
  505. LLVM_DEBUG(
  506. dbgs()
  507. << "Give up constant terminator folding in loop " << Header->getName()
  508. << ": we don't currently support deletion of the current loop.\n");
  509. return false;
  510. }
  511. // TODO: Support blocks that are not dead, but also not in loop after the
  512. // folding.
  513. if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
  514. L.getNumBlocks()) {
  515. LLVM_DEBUG(
  516. dbgs() << "Give up constant terminator folding in loop "
  517. << Header->getName() << ": we don't currently"
  518. " support blocks that are not dead, but will stop "
  519. "being a part of the loop after constant-folding.\n");
  520. return false;
  521. }
  522. // TODO: Tokens may breach LCSSA form by default. However, the transform for
  523. // dead exit blocks requires LCSSA form to be maintained for all values,
  524. // tokens included, otherwise it may break use-def dominance (see PR56243).
  525. if (!DeadExitBlocks.empty() && !L.isLCSSAForm(DT, /*IgnoreTokens*/ false)) {
  526. assert(L.isLCSSAForm(DT, /*IgnoreTokens*/ true) &&
  527. "LCSSA broken not by tokens?");
  528. LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop "
  529. << Header->getName()
  530. << ": tokens uses potentially break LCSSA form.\n");
  531. return false;
  532. }
  533. SE.forgetTopmostLoop(&L);
  534. // Dump analysis results.
  535. LLVM_DEBUG(dump());
  536. LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
  537. << " terminators in loop " << Header->getName() << "\n");
  538. if (!DeadLoopBlocks.empty())
  539. SE.forgetBlockAndLoopDispositions();
  540. // Make the actual transforms.
  541. handleDeadExits();
  542. foldTerminators();
  543. if (!DeadLoopBlocks.empty()) {
  544. LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
  545. << " dead blocks in loop " << Header->getName() << "\n");
  546. deleteDeadLoopBlocks();
  547. } else {
  548. // If we didn't do updates inside deleteDeadLoopBlocks, do them here.
  549. DTU.applyUpdates(DTUpdates);
  550. DTUpdates.clear();
  551. }
  552. if (MSSAU && VerifyMemorySSA)
  553. MSSAU->getMemorySSA()->verifyMemorySSA();
  554. #ifndef NDEBUG
  555. // Make sure that we have preserved all data structures after the transform.
  556. #if defined(EXPENSIVE_CHECKS)
  557. assert(DT.verify(DominatorTree::VerificationLevel::Full) &&
  558. "DT broken after transform!");
  559. #else
  560. assert(DT.verify(DominatorTree::VerificationLevel::Fast) &&
  561. "DT broken after transform!");
  562. #endif
  563. assert(DT.isReachableFromEntry(Header));
  564. LI.verify(DT);
  565. #endif
  566. return true;
  567. }
  568. bool foldingBreaksCurrentLoop() const {
  569. return DeleteCurrentLoop;
  570. }
  571. };
  572. } // namespace
  573. /// Turn branches and switches with known constant conditions into unconditional
  574. /// branches.
  575. static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
  576. ScalarEvolution &SE,
  577. MemorySSAUpdater *MSSAU,
  578. bool &IsLoopDeleted) {
  579. if (!EnableTermFolding)
  580. return false;
  581. // To keep things simple, only process loops with single latch. We
  582. // canonicalize most loops to this form. We can support multi-latch if needed.
  583. if (!L.getLoopLatch())
  584. return false;
  585. ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
  586. bool Changed = BranchFolder.run();
  587. IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
  588. return Changed;
  589. }
  590. static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
  591. LoopInfo &LI, MemorySSAUpdater *MSSAU,
  592. ScalarEvolution &SE) {
  593. bool Changed = false;
  594. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  595. // Copy blocks into a temporary array to avoid iterator invalidation issues
  596. // as we remove them.
  597. SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
  598. for (auto &Block : Blocks) {
  599. // Attempt to merge blocks in the trivial case. Don't modify blocks which
  600. // belong to other loops.
  601. BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
  602. if (!Succ)
  603. continue;
  604. BasicBlock *Pred = Succ->getSinglePredecessor();
  605. if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
  606. continue;
  607. // Merge Succ into Pred and delete it.
  608. MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
  609. if (MSSAU && VerifyMemorySSA)
  610. MSSAU->getMemorySSA()->verifyMemorySSA();
  611. Changed = true;
  612. }
  613. if (Changed)
  614. SE.forgetBlockAndLoopDispositions();
  615. return Changed;
  616. }
  617. static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
  618. ScalarEvolution &SE, MemorySSAUpdater *MSSAU,
  619. bool &IsLoopDeleted) {
  620. bool Changed = false;
  621. // Constant-fold terminators with known constant conditions.
  622. Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, IsLoopDeleted);
  623. if (IsLoopDeleted)
  624. return true;
  625. // Eliminate unconditional branches by merging blocks into their predecessors.
  626. Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU, SE);
  627. if (Changed)
  628. SE.forgetTopmostLoop(&L);
  629. return Changed;
  630. }
  631. PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
  632. LoopStandardAnalysisResults &AR,
  633. LPMUpdater &LPMU) {
  634. std::optional<MemorySSAUpdater> MSSAU;
  635. if (AR.MSSA)
  636. MSSAU = MemorySSAUpdater(AR.MSSA);
  637. bool DeleteCurrentLoop = false;
  638. if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE, MSSAU ? &*MSSAU : nullptr,
  639. DeleteCurrentLoop))
  640. return PreservedAnalyses::all();
  641. if (DeleteCurrentLoop)
  642. LPMU.markLoopAsDeleted(L, "loop-simplifycfg");
  643. auto PA = getLoopPassPreservedAnalyses();
  644. if (AR.MSSA)
  645. PA.preserve<MemorySSAAnalysis>();
  646. return PA;
  647. }
  648. namespace {
  649. class LoopSimplifyCFGLegacyPass : public LoopPass {
  650. public:
  651. static char ID; // Pass ID, replacement for typeid
  652. LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
  653. initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
  654. }
  655. bool runOnLoop(Loop *L, LPPassManager &LPM) override {
  656. if (skipLoop(L))
  657. return false;
  658. DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  659. LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  660. ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  661. auto *MSSAA = getAnalysisIfAvailable<MemorySSAWrapperPass>();
  662. std::optional<MemorySSAUpdater> MSSAU;
  663. if (MSSAA)
  664. MSSAU = MemorySSAUpdater(&MSSAA->getMSSA());
  665. if (MSSAA && VerifyMemorySSA)
  666. MSSAU->getMemorySSA()->verifyMemorySSA();
  667. bool DeleteCurrentLoop = false;
  668. bool Changed = simplifyLoopCFG(*L, DT, LI, SE, MSSAU ? &*MSSAU : nullptr,
  669. DeleteCurrentLoop);
  670. if (DeleteCurrentLoop)
  671. LPM.markLoopAsDeleted(*L);
  672. return Changed;
  673. }
  674. void getAnalysisUsage(AnalysisUsage &AU) const override {
  675. AU.addPreserved<MemorySSAWrapperPass>();
  676. AU.addPreserved<DependenceAnalysisWrapperPass>();
  677. getLoopAnalysisUsage(AU);
  678. }
  679. };
  680. } // end namespace
  681. char LoopSimplifyCFGLegacyPass::ID = 0;
  682. INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
  683. "Simplify loop CFG", false, false)
  684. INITIALIZE_PASS_DEPENDENCY(LoopPass)
  685. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  686. INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
  687. "Simplify loop CFG", false, false)
  688. Pass *llvm::createLoopSimplifyCFGPass() {
  689. return new LoopSimplifyCFGLegacyPass();
  690. }