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