1 //===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification Pass ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Loop SimplifyCFG Pass. This pass is responsible for 11 // basic loop CFG cleanup, primarily to assist other loop passes. If you 12 // encounter a noncanonical CFG construct that causes another loop pass to 13 // perform suboptimally, this is the place to fix it up. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/AssumptionCache.h" 22 #include "llvm/Analysis/BasicAliasAnalysis.h" 23 #include "llvm/Analysis/DependenceAnalysis.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/DomTreeUpdater.h" 33 #include "llvm/IR/Dominators.h" 34 #include "llvm/Transforms/Scalar.h" 35 #include "llvm/Transforms/Scalar/LoopPassManager.h" 36 #include "llvm/Transforms/Utils.h" 37 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38 #include "llvm/Transforms/Utils/Local.h" 39 #include "llvm/Transforms/Utils/LoopUtils.h" 40 using namespace llvm; 41 42 #define DEBUG_TYPE "loop-simplifycfg" 43 44 static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding", 45 cl::init(true)); 46 47 STATISTIC(NumTerminatorsFolded, 48 "Number of terminators folded to unconditional branches"); 49 50 /// If \p BB is a switch or a conditional branch, but only one of its successors 51 /// can be reached from this block in runtime, return this successor. Otherwise, 52 /// return nullptr. 53 static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) { 54 Instruction *TI = BB->getTerminator(); 55 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 56 if (BI->isUnconditional()) 57 return nullptr; 58 if (BI->getSuccessor(0) == BI->getSuccessor(1)) 59 return BI->getSuccessor(0); 60 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); 61 if (!Cond) 62 return nullptr; 63 return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0); 64 } 65 66 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 67 auto *CI = dyn_cast<ConstantInt>(SI->getCondition()); 68 if (!CI) 69 return nullptr; 70 for (auto Case : SI->cases()) 71 if (Case.getCaseValue() == CI) 72 return Case.getCaseSuccessor(); 73 return SI->getDefaultDest(); 74 } 75 76 return nullptr; 77 } 78 79 /// Helper class that can turn branches and switches with constant conditions 80 /// into unconditional branches. 81 class ConstantTerminatorFoldingImpl { 82 private: 83 Loop &L; 84 LoopInfo &LI; 85 DominatorTree &DT; 86 MemorySSAUpdater *MSSAU; 87 88 // Whether or not the current loop has irreducible CFG. 89 bool HasIrreducibleCFG = false; 90 // Whether or not the current loop will still exist after terminator constant 91 // folding will be done. In theory, there are two ways how it can happen: 92 // 1. Loop's latch(es) become unreachable from loop header; 93 // 2. Loop's header becomes unreachable from method entry. 94 // In practice, the second situation is impossible because we only modify the 95 // current loop and its preheader and do not affect preheader's reachibility 96 // from any other block. So this variable set to true means that loop's latch 97 // has become unreachable from loop header. 98 bool DeleteCurrentLoop = false; 99 100 // The blocks of the original loop that will still be reachable from entry 101 // after the constant folding. 102 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks; 103 // The blocks of the original loop that will become unreachable from entry 104 // after the constant folding. 105 SmallPtrSet<BasicBlock *, 8> DeadLoopBlocks; 106 // The exits of the original loop that will still be reachable from entry 107 // after the constant folding. 108 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks; 109 // The exits of the original loop that will become unreachable from entry 110 // after the constant folding. 111 SmallVector<BasicBlock *, 8> DeadExitBlocks; 112 // The blocks that will still be a part of the current loop after folding. 113 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding; 114 // The blocks that have terminators with constant condition that can be 115 // folded. Note: fold candidates should be in L but not in any of its 116 // subloops to avoid complex LI updates. 117 SmallVector<BasicBlock *, 8> FoldCandidates; 118 119 void dump() const { 120 dbgs() << "Constant terminator folding for loop " << L << "\n"; 121 dbgs() << "After terminator constant-folding, the loop will"; 122 if (!DeleteCurrentLoop) 123 dbgs() << " not"; 124 dbgs() << " be destroyed\n"; 125 auto PrintOutVector = [&](const char *Message, 126 const SmallVectorImpl<BasicBlock *> &S) { 127 dbgs() << Message << "\n"; 128 for (const BasicBlock *BB : S) 129 dbgs() << "\t" << BB->getName() << "\n"; 130 }; 131 auto PrintOutSet = [&](const char *Message, 132 const SmallPtrSetImpl<BasicBlock *> &S) { 133 dbgs() << Message << "\n"; 134 for (const BasicBlock *BB : S) 135 dbgs() << "\t" << BB->getName() << "\n"; 136 }; 137 PrintOutVector("Blocks in which we can constant-fold terminator:", 138 FoldCandidates); 139 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks); 140 PrintOutSet("Dead blocks from the original loop:", DeadLoopBlocks); 141 PrintOutSet("Live exit blocks:", LiveExitBlocks); 142 PrintOutVector("Dead exit blocks:", DeadExitBlocks); 143 if (!DeleteCurrentLoop) 144 PrintOutSet("The following blocks will still be part of the loop:", 145 BlocksInLoopAfterFolding); 146 } 147 148 /// Whether or not the current loop has irreducible CFG. 149 bool hasIrreducibleCFG(LoopBlocksDFS &DFS) { 150 assert(DFS.isComplete() && "DFS is expected to be finished"); 151 // Index of a basic block in RPO traversal. 152 DenseMap<const BasicBlock *, unsigned> RPO; 153 unsigned Current = 0; 154 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) 155 RPO[*I] = Current++; 156 157 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) { 158 BasicBlock *BB = *I; 159 for (auto *Succ : successors(BB)) 160 if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ]) 161 // If an edge goes from a block with greater order number into a block 162 // with lesses number, and it is not a loop backedge, then it can only 163 // be a part of irreducible non-loop cycle. 164 return true; 165 } 166 return false; 167 } 168 169 /// Fill all information about status of blocks and exits of the current loop 170 /// if constant folding of all branches will be done. 171 void analyze() { 172 LoopBlocksDFS DFS(&L); 173 DFS.perform(&LI); 174 assert(DFS.isComplete() && "DFS is expected to be finished"); 175 176 // TODO: The algorithm below relies on both RPO and Postorder traversals. 177 // When the loop has only reducible CFG inside, then the invariant "all 178 // predecessors of X are processed before X in RPO" is preserved. However 179 // an irreducible loop can break this invariant (e.g. latch does not have to 180 // be the last block in the traversal in this case, and the algorithm relies 181 // on this). We can later decide to support such cases by altering the 182 // algorithms, but so far we just give up analyzing them. 183 if (hasIrreducibleCFG(DFS)) { 184 HasIrreducibleCFG = true; 185 return; 186 } 187 188 // Collect live and dead loop blocks and exits. 189 LiveLoopBlocks.insert(L.getHeader()); 190 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) { 191 BasicBlock *BB = *I; 192 193 // If a loop block wasn't marked as live so far, then it's dead. 194 if (!LiveLoopBlocks.count(BB)) { 195 DeadLoopBlocks.insert(BB); 196 continue; 197 } 198 199 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB); 200 201 // If a block has only one live successor, it's a candidate on constant 202 // folding. Only handle blocks from current loop: branches in child loops 203 // are skipped because if they can be folded, they should be folded during 204 // the processing of child loops. 205 if (TheOnlySucc && LI.getLoopFor(BB) == &L) 206 FoldCandidates.push_back(BB); 207 208 // Handle successors. 209 for (BasicBlock *Succ : successors(BB)) 210 if (!TheOnlySucc || TheOnlySucc == Succ) { 211 if (L.contains(Succ)) 212 LiveLoopBlocks.insert(Succ); 213 else 214 LiveExitBlocks.insert(Succ); 215 } 216 } 217 218 // Sanity check: amount of dead and live loop blocks should match the total 219 // number of blocks in loop. 220 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() && 221 "Malformed block sets?"); 222 223 // Now, all exit blocks that are not marked as live are dead. 224 SmallVector<BasicBlock *, 8> ExitBlocks; 225 L.getExitBlocks(ExitBlocks); 226 for (auto *ExitBlock : ExitBlocks) 227 if (!LiveExitBlocks.count(ExitBlock)) 228 DeadExitBlocks.push_back(ExitBlock); 229 230 // Whether or not the edge From->To will still be present in graph after the 231 // folding. 232 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) { 233 if (!LiveLoopBlocks.count(From)) 234 return false; 235 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From); 236 return !TheOnlySucc || TheOnlySucc == To; 237 }; 238 239 // The loop will not be destroyed if its latch is live. 240 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader()); 241 242 // If we are going to delete the current loop completely, no extra analysis 243 // is needed. 244 if (DeleteCurrentLoop) 245 return; 246 247 // Otherwise, we should check which blocks will still be a part of the 248 // current loop after the transform. 249 BlocksInLoopAfterFolding.insert(L.getLoopLatch()); 250 // If the loop is live, then we should compute what blocks are still in 251 // loop after all branch folding has been done. A block is in loop if 252 // it has a live edge to another block that is in the loop; by definition, 253 // latch is in the loop. 254 auto BlockIsInLoop = [&](BasicBlock *BB) { 255 return any_of(successors(BB), [&](BasicBlock *Succ) { 256 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ); 257 }); 258 }; 259 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) { 260 BasicBlock *BB = *I; 261 if (BlockIsInLoop(BB)) 262 BlocksInLoopAfterFolding.insert(BB); 263 } 264 265 // Sanity check: header must be in loop. 266 assert(BlocksInLoopAfterFolding.count(L.getHeader()) && 267 "Header not in loop?"); 268 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() && 269 "All blocks that stay in loop should be live!"); 270 } 271 272 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the 273 /// unconditional branches. 274 void foldTerminators() { 275 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 276 277 for (BasicBlock *BB : FoldCandidates) { 278 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!"); 279 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB); 280 assert(TheOnlySucc && "Should have one live successor!"); 281 282 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName() 283 << " with an unconditional branch to the block " 284 << TheOnlySucc->getName() << "\n"); 285 286 SmallPtrSet<BasicBlock *, 2> DeadSuccessors; 287 // Remove all BB's successors except for the live one. 288 unsigned TheOnlySuccDuplicates = 0; 289 for (auto *Succ : successors(BB)) 290 if (Succ != TheOnlySucc) { 291 DeadSuccessors.insert(Succ); 292 // If our successor lies in a different loop, we don't want to remove 293 // the one-input Phi because it is a LCSSA Phi. 294 bool PreserveLCSSAPhi = !L.contains(Succ); 295 Succ->removePredecessor(BB, PreserveLCSSAPhi); 296 if (MSSAU) 297 MSSAU->removeEdge(BB, Succ); 298 } else 299 ++TheOnlySuccDuplicates; 300 301 assert(TheOnlySuccDuplicates > 0 && "Should be!"); 302 // If TheOnlySucc was BB's successor more than once, after transform it 303 // will be its successor only once. Remove redundant inputs from 304 // TheOnlySucc's Phis. 305 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc); 306 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup) 307 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi); 308 if (MSSAU && TheOnlySuccDuplicates > 1) 309 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc); 310 311 IRBuilder<> Builder(BB->getContext()); 312 Instruction *Term = BB->getTerminator(); 313 Builder.SetInsertPoint(Term); 314 Builder.CreateBr(TheOnlySucc); 315 Term->eraseFromParent(); 316 317 for (auto *DeadSucc : DeadSuccessors) 318 DTU.deleteEdge(BB, DeadSucc); 319 320 ++NumTerminatorsFolded; 321 } 322 } 323 324 public: 325 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT, 326 MemorySSAUpdater *MSSAU) 327 : L(L), LI(LI), DT(DT), MSSAU(MSSAU) {} 328 bool run() { 329 assert(L.getLoopLatch() && "Should be single latch!"); 330 331 // Collect all available information about status of blocks after constant 332 // folding. 333 analyze(); 334 335 LLVM_DEBUG(dbgs() << "In function " << L.getHeader()->getParent()->getName() 336 << ": "); 337 338 if (HasIrreducibleCFG) { 339 LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n"); 340 return false; 341 } 342 343 // Nothing to constant-fold. 344 if (FoldCandidates.empty()) { 345 LLVM_DEBUG( 346 dbgs() << "No constant terminator folding candidates found in loop " 347 << L.getHeader()->getName() << "\n"); 348 return false; 349 } 350 351 // TODO: Support deletion of the current loop. 352 if (DeleteCurrentLoop) { 353 LLVM_DEBUG( 354 dbgs() 355 << "Give up constant terminator folding in loop " 356 << L.getHeader()->getName() 357 << ": we don't currently support deletion of the current loop.\n"); 358 return false; 359 } 360 361 // TODO: Support deletion of dead loop blocks. 362 if (!DeadLoopBlocks.empty()) { 363 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop " 364 << L.getHeader()->getName() 365 << ": we don't currently" 366 " support deletion of dead in-loop blocks.\n"); 367 return false; 368 } 369 370 // TODO: Support dead loop exits. 371 if (!DeadExitBlocks.empty()) { 372 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop " 373 << L.getHeader()->getName() 374 << ": we don't currently support dead loop exits.\n"); 375 return false; 376 } 377 378 // TODO: Support blocks that are not dead, but also not in loop after the 379 // folding. 380 if (BlocksInLoopAfterFolding.size() != L.getNumBlocks()) { 381 LLVM_DEBUG( 382 dbgs() << "Give up constant terminator folding in loop " 383 << L.getHeader()->getName() 384 << ": we don't currently" 385 " support blocks that are not dead, but will stop " 386 "being a part of the loop after constant-folding.\n"); 387 return false; 388 } 389 390 // Dump analysis results. 391 LLVM_DEBUG(dump()); 392 393 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size() 394 << " terminators in loop " << L.getHeader()->getName() 395 << "\n"); 396 397 // Make the actual transforms. 398 foldTerminators(); 399 400 #ifndef NDEBUG 401 // Make sure that we have preserved all data structures after the transform. 402 DT.verify(); 403 assert(DT.isReachableFromEntry(L.getHeader())); 404 LI.verify(DT); 405 #endif 406 407 return true; 408 } 409 }; 410 411 /// Turn branches and switches with known constant conditions into unconditional 412 /// branches. 413 static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI, 414 MemorySSAUpdater *MSSAU) { 415 if (!EnableTermFolding) 416 return false; 417 418 // To keep things simple, only process loops with single latch. We 419 // canonicalize most loops to this form. We can support multi-latch if needed. 420 if (!L.getLoopLatch()) 421 return false; 422 423 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, MSSAU); 424 return BranchFolder.run(); 425 } 426 427 static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT, 428 LoopInfo &LI, MemorySSAUpdater *MSSAU) { 429 bool Changed = false; 430 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 431 // Copy blocks into a temporary array to avoid iterator invalidation issues 432 // as we remove them. 433 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks()); 434 435 for (auto &Block : Blocks) { 436 // Attempt to merge blocks in the trivial case. Don't modify blocks which 437 // belong to other loops. 438 BasicBlock *Succ = cast_or_null<BasicBlock>(Block); 439 if (!Succ) 440 continue; 441 442 BasicBlock *Pred = Succ->getSinglePredecessor(); 443 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L) 444 continue; 445 446 // Merge Succ into Pred and delete it. 447 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU); 448 449 Changed = true; 450 } 451 452 return Changed; 453 } 454 455 static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI, 456 ScalarEvolution &SE, MemorySSAUpdater *MSSAU) { 457 bool Changed = false; 458 459 // Constant-fold terminators with known constant conditions. 460 Changed |= constantFoldTerminators(L, DT, LI, MSSAU); 461 462 // Eliminate unconditional branches by merging blocks into their predecessors. 463 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU); 464 465 if (Changed) 466 SE.forgetTopmostLoop(&L); 467 468 return Changed; 469 } 470 471 PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM, 472 LoopStandardAnalysisResults &AR, 473 LPMUpdater &) { 474 Optional<MemorySSAUpdater> MSSAU; 475 if (EnableMSSALoopDependency && AR.MSSA) 476 MSSAU = MemorySSAUpdater(AR.MSSA); 477 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE, 478 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr)) 479 return PreservedAnalyses::all(); 480 481 return getLoopPassPreservedAnalyses(); 482 } 483 484 namespace { 485 class LoopSimplifyCFGLegacyPass : public LoopPass { 486 public: 487 static char ID; // Pass ID, replacement for typeid 488 LoopSimplifyCFGLegacyPass() : LoopPass(ID) { 489 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry()); 490 } 491 492 bool runOnLoop(Loop *L, LPPassManager &) override { 493 if (skipLoop(L)) 494 return false; 495 496 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 497 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 498 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 499 Optional<MemorySSAUpdater> MSSAU; 500 if (EnableMSSALoopDependency) { 501 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA(); 502 MSSAU = MemorySSAUpdater(MSSA); 503 if (VerifyMemorySSA) 504 MSSA->verifyMemorySSA(); 505 } 506 return simplifyLoopCFG(*L, DT, LI, SE, 507 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr); 508 } 509 510 void getAnalysisUsage(AnalysisUsage &AU) const override { 511 if (EnableMSSALoopDependency) { 512 AU.addRequired<MemorySSAWrapperPass>(); 513 AU.addPreserved<MemorySSAWrapperPass>(); 514 } 515 AU.addPreserved<DependenceAnalysisWrapperPass>(); 516 getLoopAnalysisUsage(AU); 517 } 518 }; 519 } 520 521 char LoopSimplifyCFGLegacyPass::ID = 0; 522 INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg", 523 "Simplify loop CFG", false, false) 524 INITIALIZE_PASS_DEPENDENCY(LoopPass) 525 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 526 INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg", 527 "Simplify loop CFG", false, false) 528 529 Pass *llvm::createLoopSimplifyCFGPass() { 530 return new LoopSimplifyCFGLegacyPass(); 531 } 532