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