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(false)); 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 87 // Whether or not the current loop will still exist after terminator constant 88 // folding will be done. In theory, there are two ways how it can happen: 89 // 1. Loop's latch(es) become unreachable from loop header; 90 // 2. Loop's header becomes unreachable from method entry. 91 // In practice, the second situation is impossible because we only modify the 92 // current loop and its preheader and do not affect preheader's reachibility 93 // from any other block. So this variable set to true means that loop's latch 94 // has become unreachable from loop header. 95 bool DeleteCurrentLoop = false; 96 97 // The blocks of the original loop that will still be reachable from entry 98 // after the constant folding. 99 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks; 100 // The blocks of the original loop that will become unreachable from entry 101 // after the constant folding. 102 SmallPtrSet<BasicBlock *, 8> DeadLoopBlocks; 103 // The exits of the original loop that will still be reachable from entry 104 // after the constant folding. 105 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks; 106 // The exits of the original loop that will become unreachable from entry 107 // after the constant folding. 108 SmallVector<BasicBlock *, 8> DeadExitBlocks; 109 // The blocks that will still be a part of the current loop after folding. 110 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding; 111 // The blocks that have terminators with constant condition that can be 112 // folded. Note: fold candidates should be in L but not in any of its 113 // subloops to avoid complex LI updates. 114 SmallVector<BasicBlock *, 8> FoldCandidates; 115 116 void dump() const { 117 dbgs() << "Constant terminator folding for loop " << L << "\n"; 118 dbgs() << "After terminator constant-folding, the loop will"; 119 if (!DeleteCurrentLoop) 120 dbgs() << " not"; 121 dbgs() << " be destroyed\n"; 122 auto PrintOutVector = [&](const char *Message, 123 const SmallVectorImpl<BasicBlock *> &S) { 124 dbgs() << Message << "\n"; 125 for (const BasicBlock *BB : S) 126 dbgs() << "\t" << BB->getName() << "\n"; 127 }; 128 auto PrintOutSet = [&](const char *Message, 129 const SmallPtrSetImpl<BasicBlock *> &S) { 130 dbgs() << Message << "\n"; 131 for (const BasicBlock *BB : S) 132 dbgs() << "\t" << BB->getName() << "\n"; 133 }; 134 PrintOutVector("Blocks in which we can constant-fold terminator:", 135 FoldCandidates); 136 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks); 137 PrintOutSet("Dead blocks from the original loop:", DeadLoopBlocks); 138 PrintOutSet("Live exit blocks:", LiveExitBlocks); 139 PrintOutVector("Dead exit blocks:", DeadExitBlocks); 140 if (!DeleteCurrentLoop) 141 PrintOutSet("The following blocks will still be part of the loop:", 142 BlocksInLoopAfterFolding); 143 } 144 145 /// Fill all information about status of blocks and exits of the current loop 146 /// if constant folding of all branches will be done. 147 void analyze() { 148 LoopBlocksDFS DFS(&L); 149 DFS.perform(&LI); 150 assert(DFS.isComplete() && "DFS is expected to be finished"); 151 152 // Collect live and dead loop blocks and exits. 153 LiveLoopBlocks.insert(L.getHeader()); 154 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) { 155 BasicBlock *BB = *I; 156 157 // If a loop block wasn't marked as live so far, then it's dead. 158 if (!LiveLoopBlocks.count(BB)) { 159 DeadLoopBlocks.insert(BB); 160 continue; 161 } 162 163 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB); 164 165 // If a block has only one live successor, it's a candidate on constant 166 // folding. Only handle blocks from current loop: branches in child loops 167 // are skipped because if they can be folded, they should be folded during 168 // the processing of child loops. 169 if (TheOnlySucc && LI.getLoopFor(BB) == &L) 170 FoldCandidates.push_back(BB); 171 172 // Handle successors. 173 for (BasicBlock *Succ : successors(BB)) 174 if (!TheOnlySucc || TheOnlySucc == Succ) { 175 if (L.contains(Succ)) 176 LiveLoopBlocks.insert(Succ); 177 else 178 LiveExitBlocks.insert(Succ); 179 } 180 } 181 182 // Sanity check: amount of dead and live loop blocks should match the total 183 // number of blocks in loop. 184 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() && 185 "Malformed block sets?"); 186 187 // Now, all exit blocks that are not marked as live are dead. 188 SmallVector<BasicBlock *, 8> ExitBlocks; 189 L.getExitBlocks(ExitBlocks); 190 for (auto *ExitBlock : ExitBlocks) 191 if (!LiveExitBlocks.count(ExitBlock)) 192 DeadExitBlocks.push_back(ExitBlock); 193 194 // Whether or not the edge From->To will still be present in graph after the 195 // folding. 196 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) { 197 if (!LiveLoopBlocks.count(From)) 198 return false; 199 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From); 200 return !TheOnlySucc || TheOnlySucc == To; 201 }; 202 203 // The loop will not be destroyed if its latch is live. 204 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader()); 205 206 // If we are going to delete the current loop completely, no extra analysis 207 // is needed. 208 if (DeleteCurrentLoop) 209 return; 210 211 // Otherwise, we should check which blocks will still be a part of the 212 // current loop after the transform. 213 BlocksInLoopAfterFolding.insert(L.getLoopLatch()); 214 // If the loop is live, then we should compute what blocks are still in 215 // loop after all branch folding has been done. A block is in loop if 216 // it has a live edge to another block that is in the loop; by definition, 217 // latch is in the loop. 218 auto BlockIsInLoop = [&](BasicBlock *BB) { 219 return any_of(successors(BB), [&](BasicBlock *Succ) { 220 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ); 221 }); 222 }; 223 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) { 224 BasicBlock *BB = *I; 225 if (BlockIsInLoop(BB)) 226 BlocksInLoopAfterFolding.insert(BB); 227 } 228 229 // Sanity check: header must be in loop. 230 assert(BlocksInLoopAfterFolding.count(L.getHeader()) && 231 "Header not in loop?"); 232 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() && 233 "All blocks that stay in loop should be live!"); 234 } 235 236 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the 237 /// unconditional branches. 238 void foldTerminators() { 239 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 240 241 for (BasicBlock *BB : FoldCandidates) { 242 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!"); 243 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB); 244 assert(TheOnlySucc && "Should have one live successor!"); 245 246 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName() 247 << " with an unconditional branch to the block " 248 << TheOnlySucc->getName() << "\n"); 249 250 SmallPtrSet<BasicBlock *, 2> DeadSuccessors; 251 // Remove all BB's successors except for the live one. 252 unsigned TheOnlySuccDuplicates = 0; 253 for (auto *Succ : successors(BB)) 254 if (Succ != TheOnlySucc) { 255 DeadSuccessors.insert(Succ); 256 // If our successor lies in a different loop, we don't want to remove 257 // the one-input Phi because it is a LCSSA Phi. 258 bool PreserveLCSSAPhi = !L.contains(Succ); 259 Succ->removePredecessor(BB, PreserveLCSSAPhi); 260 } else 261 ++TheOnlySuccDuplicates; 262 263 assert(TheOnlySuccDuplicates > 0 && "Should be!"); 264 // If TheOnlySucc was BB's successor more than once, after transform it 265 // will be its successor only once. Remove redundant inputs from 266 // TheOnlySucc's Phis. 267 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc); 268 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup) 269 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi); 270 271 IRBuilder<> Builder(BB->getContext()); 272 Instruction *Term = BB->getTerminator(); 273 Builder.SetInsertPoint(Term); 274 Builder.CreateBr(TheOnlySucc); 275 Term->eraseFromParent(); 276 277 for (auto *DeadSucc : DeadSuccessors) 278 DTU.deleteEdge(BB, DeadSucc); 279 280 ++NumTerminatorsFolded; 281 } 282 } 283 284 public: 285 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT) 286 : L(L), LI(LI), DT(DT) {} 287 bool run() { 288 assert(L.getLoopLatch() && "Should be single latch!"); 289 290 // Collect all available information about status of blocks after constant 291 // folding. 292 analyze(); 293 294 LLVM_DEBUG(dbgs() << "In function " << L.getHeader()->getParent()->getName() 295 << ": "); 296 297 // Nothing to constant-fold. 298 if (FoldCandidates.empty()) { 299 LLVM_DEBUG( 300 dbgs() << "No constant terminator folding candidates found in loop " 301 << L.getHeader()->getName() << "\n"); 302 return false; 303 } 304 305 // TODO: Support deletion of the current loop. 306 if (DeleteCurrentLoop) { 307 LLVM_DEBUG( 308 dbgs() 309 << "Give up constant terminator folding in loop " 310 << L.getHeader()->getName() 311 << ": we don't currently support deletion of the current loop.\n"); 312 return false; 313 } 314 315 // TODO: Support deletion of dead loop blocks. 316 if (!DeadLoopBlocks.empty()) { 317 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop " 318 << L.getHeader()->getName() 319 << ": we don't currently" 320 " support deletion of dead in-loop blocks.\n"); 321 return false; 322 } 323 324 // TODO: Support dead loop exits. 325 if (!DeadExitBlocks.empty()) { 326 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop " 327 << L.getHeader()->getName() 328 << ": we don't currently support dead loop exits.\n"); 329 return false; 330 } 331 332 // TODO: Support blocks that are not dead, but also not in loop after the 333 // folding. 334 if (BlocksInLoopAfterFolding.size() != L.getNumBlocks()) { 335 LLVM_DEBUG( 336 dbgs() << "Give up constant terminator folding in loop " 337 << L.getHeader()->getName() 338 << ": we don't currently" 339 " support blocks that are not dead, but will stop " 340 "being a part of the loop after constant-folding.\n"); 341 return false; 342 } 343 344 // Dump analysis results. 345 LLVM_DEBUG(dump()); 346 347 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size() 348 << " terminators in loop " << L.getHeader()->getName() 349 << "\n"); 350 351 // Make the actual transforms. 352 foldTerminators(); 353 354 #ifndef NDEBUG 355 // Make sure that we have preserved all data structures after the transform. 356 DT.verify(); 357 assert(DT.isReachableFromEntry(L.getHeader())); 358 LI.verify(DT); 359 #endif 360 361 return true; 362 } 363 }; 364 365 /// Turn branches and switches with known constant conditions into unconditional 366 /// branches. 367 static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI) { 368 if (!EnableTermFolding) 369 return false; 370 371 // To keep things simple, only process loops with single latch. We 372 // canonicalize most loops to this form. We can support multi-latch if needed. 373 if (!L.getLoopLatch()) 374 return false; 375 376 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT); 377 return BranchFolder.run(); 378 } 379 380 static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT, 381 LoopInfo &LI, MemorySSAUpdater *MSSAU) { 382 bool Changed = false; 383 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 384 // Copy blocks into a temporary array to avoid iterator invalidation issues 385 // as we remove them. 386 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks()); 387 388 for (auto &Block : Blocks) { 389 // Attempt to merge blocks in the trivial case. Don't modify blocks which 390 // belong to other loops. 391 BasicBlock *Succ = cast_or_null<BasicBlock>(Block); 392 if (!Succ) 393 continue; 394 395 BasicBlock *Pred = Succ->getSinglePredecessor(); 396 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L) 397 continue; 398 399 // Merge Succ into Pred and delete it. 400 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU); 401 402 Changed = true; 403 } 404 405 return Changed; 406 } 407 408 static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI, 409 ScalarEvolution &SE, MemorySSAUpdater *MSSAU) { 410 bool Changed = false; 411 412 // Constant-fold terminators with known constant conditions. 413 Changed |= constantFoldTerminators(L, DT, LI); 414 415 // Eliminate unconditional branches by merging blocks into their predecessors. 416 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU); 417 418 if (Changed) 419 SE.forgetTopmostLoop(&L); 420 421 return Changed; 422 } 423 424 PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM, 425 LoopStandardAnalysisResults &AR, 426 LPMUpdater &) { 427 Optional<MemorySSAUpdater> MSSAU; 428 if (EnableMSSALoopDependency && AR.MSSA) 429 MSSAU = MemorySSAUpdater(AR.MSSA); 430 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE, 431 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr)) 432 return PreservedAnalyses::all(); 433 434 return getLoopPassPreservedAnalyses(); 435 } 436 437 namespace { 438 class LoopSimplifyCFGLegacyPass : public LoopPass { 439 public: 440 static char ID; // Pass ID, replacement for typeid 441 LoopSimplifyCFGLegacyPass() : LoopPass(ID) { 442 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry()); 443 } 444 445 bool runOnLoop(Loop *L, LPPassManager &) override { 446 if (skipLoop(L)) 447 return false; 448 449 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 450 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 451 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 452 Optional<MemorySSAUpdater> MSSAU; 453 if (EnableMSSALoopDependency) { 454 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA(); 455 MSSAU = MemorySSAUpdater(MSSA); 456 if (VerifyMemorySSA) 457 MSSA->verifyMemorySSA(); 458 } 459 return simplifyLoopCFG(*L, DT, LI, SE, 460 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr); 461 } 462 463 void getAnalysisUsage(AnalysisUsage &AU) const override { 464 if (EnableMSSALoopDependency) { 465 AU.addRequired<MemorySSAWrapperPass>(); 466 AU.addPreserved<MemorySSAWrapperPass>(); 467 } 468 AU.addPreserved<DependenceAnalysisWrapperPass>(); 469 getLoopAnalysisUsage(AU); 470 } 471 }; 472 } 473 474 char LoopSimplifyCFGLegacyPass::ID = 0; 475 INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg", 476 "Simplify loop CFG", false, false) 477 INITIALIZE_PASS_DEPENDENCY(LoopPass) 478 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 479 INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg", 480 "Simplify loop CFG", false, false) 481 482 Pass *llvm::createLoopSimplifyCFGPass() { 483 return new LoopSimplifyCFGLegacyPass(); 484 } 485