1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===// 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 pass transforms loops by placing phi nodes at the end of the loops for 10 // all values that are live across the loop boundary. For example, it turns 11 // the left into the right code: 12 // 13 // for (...) for (...) 14 // if (c) if (c) 15 // X1 = ... X1 = ... 16 // else else 17 // X2 = ... X2 = ... 18 // X3 = phi(X1, X2) X3 = phi(X1, X2) 19 // ... = X3 + 4 X4 = phi(X3) 20 // ... = X4 + 4 21 // 22 // This is still valid LLVM; the extra phi nodes are purely redundant, and will 23 // be trivially eliminated by InstCombine. The major benefit of this 24 // transformation is that it makes many other loop optimizations, such as 25 // LoopUnswitching, simpler. 26 // 27 //===----------------------------------------------------------------------===// 28 29 #include "llvm/Transforms/Utils/LCSSA.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/Statistic.h" 32 #include "llvm/Analysis/AliasAnalysis.h" 33 #include "llvm/Analysis/BasicAliasAnalysis.h" 34 #include "llvm/Analysis/BranchProbabilityInfo.h" 35 #include "llvm/Analysis/GlobalsModRef.h" 36 #include "llvm/Analysis/LoopInfo.h" 37 #include "llvm/Analysis/LoopPass.h" 38 #include "llvm/Analysis/MemorySSA.h" 39 #include "llvm/Analysis/ScalarEvolution.h" 40 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 41 #include "llvm/IR/DebugInfo.h" 42 #include "llvm/IR/Dominators.h" 43 #include "llvm/IR/IRBuilder.h" 44 #include "llvm/IR/Instructions.h" 45 #include "llvm/IR/IntrinsicInst.h" 46 #include "llvm/IR/PredIteratorCache.h" 47 #include "llvm/InitializePasses.h" 48 #include "llvm/Pass.h" 49 #include "llvm/Support/CommandLine.h" 50 #include "llvm/Transforms/Utils.h" 51 #include "llvm/Transforms/Utils/LoopUtils.h" 52 #include "llvm/Transforms/Utils/SSAUpdater.h" 53 using namespace llvm; 54 55 #define DEBUG_TYPE "lcssa" 56 57 STATISTIC(NumLCSSA, "Number of live out of a loop variables"); 58 59 #ifdef EXPENSIVE_CHECKS 60 static bool VerifyLoopLCSSA = true; 61 #else 62 static bool VerifyLoopLCSSA = false; 63 #endif 64 static cl::opt<bool, true> 65 VerifyLoopLCSSAFlag("verify-loop-lcssa", cl::location(VerifyLoopLCSSA), 66 cl::Hidden, 67 cl::desc("Verify loop lcssa form (time consuming)")); 68 69 /// Return true if the specified block is in the list. 70 static bool isExitBlock(BasicBlock *BB, 71 const SmallVectorImpl<BasicBlock *> &ExitBlocks) { 72 return is_contained(ExitBlocks, BB); 73 } 74 75 /// For every instruction from the worklist, check to see if it has any uses 76 /// that are outside the current loop. If so, insert LCSSA PHI nodes and 77 /// rewrite the uses. 78 bool llvm::formLCSSAForInstructions(SmallVectorImpl<Instruction *> &Worklist, 79 const DominatorTree &DT, const LoopInfo &LI, 80 ScalarEvolution *SE, IRBuilderBase &Builder, 81 SmallVectorImpl<PHINode *> *PHIsToRemove) { 82 SmallVector<Use *, 16> UsesToRewrite; 83 SmallSetVector<PHINode *, 16> LocalPHIsToRemove; 84 PredIteratorCache PredCache; 85 bool Changed = false; 86 87 IRBuilderBase::InsertPointGuard InsertPtGuard(Builder); 88 89 // Cache the Loop ExitBlocks across this loop. We expect to get a lot of 90 // instructions within the same loops, computing the exit blocks is 91 // expensive, and we're not mutating the loop structure. 92 SmallDenseMap<Loop*, SmallVector<BasicBlock *,1>> LoopExitBlocks; 93 94 while (!Worklist.empty()) { 95 UsesToRewrite.clear(); 96 97 Instruction *I = Worklist.pop_back_val(); 98 assert(!I->getType()->isTokenTy() && "Tokens shouldn't be in the worklist"); 99 BasicBlock *InstBB = I->getParent(); 100 Loop *L = LI.getLoopFor(InstBB); 101 assert(L && "Instruction belongs to a BB that's not part of a loop"); 102 if (!LoopExitBlocks.count(L)) 103 L->getExitBlocks(LoopExitBlocks[L]); 104 assert(LoopExitBlocks.count(L)); 105 const SmallVectorImpl<BasicBlock *> &ExitBlocks = LoopExitBlocks[L]; 106 107 if (ExitBlocks.empty()) 108 continue; 109 110 for (Use &U : I->uses()) { 111 Instruction *User = cast<Instruction>(U.getUser()); 112 BasicBlock *UserBB = User->getParent(); 113 114 // Skip uses in unreachable blocks. 115 if (!DT.isReachableFromEntry(UserBB)) 116 continue; 117 118 // For practical purposes, we consider that the use in a PHI 119 // occurs in the respective predecessor block. For more info, 120 // see the `phi` doc in LangRef and the LCSSA doc. 121 if (auto *PN = dyn_cast<PHINode>(User)) 122 UserBB = PN->getIncomingBlock(U); 123 124 if (InstBB != UserBB && !L->contains(UserBB)) 125 UsesToRewrite.push_back(&U); 126 } 127 128 // If there are no uses outside the loop, exit with no change. 129 if (UsesToRewrite.empty()) 130 continue; 131 132 ++NumLCSSA; // We are applying the transformation 133 134 // Invoke instructions are special in that their result value is not 135 // available along their unwind edge. The code below tests to see whether 136 // DomBB dominates the value, so adjust DomBB to the normal destination 137 // block, which is effectively where the value is first usable. 138 BasicBlock *DomBB = InstBB; 139 if (auto *Inv = dyn_cast<InvokeInst>(I)) 140 DomBB = Inv->getNormalDest(); 141 142 const DomTreeNode *DomNode = DT.getNode(DomBB); 143 144 SmallVector<PHINode *, 16> AddedPHIs; 145 SmallVector<PHINode *, 8> PostProcessPHIs; 146 147 SmallVector<PHINode *, 4> InsertedPHIs; 148 SSAUpdater SSAUpdate(&InsertedPHIs); 149 SSAUpdate.Initialize(I->getType(), I->getName()); 150 151 // Force re-computation of I, as some users now need to use the new PHI 152 // node. 153 if (SE) 154 SE->forgetValue(I); 155 156 // Insert the LCSSA phi's into all of the exit blocks dominated by the 157 // value, and add them to the Phi's map. 158 for (BasicBlock *ExitBB : ExitBlocks) { 159 if (!DT.dominates(DomNode, DT.getNode(ExitBB))) 160 continue; 161 162 // If we already inserted something for this BB, don't reprocess it. 163 if (SSAUpdate.HasValueForBlock(ExitBB)) 164 continue; 165 Builder.SetInsertPoint(&ExitBB->front()); 166 PHINode *PN = Builder.CreatePHI(I->getType(), PredCache.size(ExitBB), 167 I->getName() + ".lcssa"); 168 // Get the debug location from the original instruction. 169 PN->setDebugLoc(I->getDebugLoc()); 170 171 // Add inputs from inside the loop for this PHI. This is valid 172 // because `I` dominates `ExitBB` (checked above). This implies 173 // that every incoming block/edge is dominated by `I` as well, 174 // i.e. we can add uses of `I` to those incoming edges/append to the incoming 175 // blocks without violating the SSA dominance property. 176 for (BasicBlock *Pred : PredCache.get(ExitBB)) { 177 PN->addIncoming(I, Pred); 178 179 // If the exit block has a predecessor not within the loop, arrange for 180 // the incoming value use corresponding to that predecessor to be 181 // rewritten in terms of a different LCSSA PHI. 182 if (!L->contains(Pred)) 183 UsesToRewrite.push_back( 184 &PN->getOperandUse(PN->getOperandNumForIncomingValue( 185 PN->getNumIncomingValues() - 1))); 186 } 187 188 AddedPHIs.push_back(PN); 189 190 // Remember that this phi makes the value alive in this block. 191 SSAUpdate.AddAvailableValue(ExitBB, PN); 192 193 // LoopSimplify might fail to simplify some loops (e.g. when indirect 194 // branches are involved). In such situations, it might happen that an 195 // exit for Loop L1 is the header of a disjoint Loop L2. Thus, when we 196 // create PHIs in such an exit block, we are also inserting PHIs into L2's 197 // header. This could break LCSSA form for L2 because these inserted PHIs 198 // can also have uses outside of L2. Remember all PHIs in such situation 199 // as to revisit than later on. FIXME: Remove this if indirectbr support 200 // into LoopSimplify gets improved. 201 if (auto *OtherLoop = LI.getLoopFor(ExitBB)) 202 if (!L->contains(OtherLoop)) 203 PostProcessPHIs.push_back(PN); 204 } 205 206 // Rewrite all uses outside the loop in terms of the new PHIs we just 207 // inserted. 208 for (Use *UseToRewrite : UsesToRewrite) { 209 Instruction *User = cast<Instruction>(UseToRewrite->getUser()); 210 BasicBlock *UserBB = User->getParent(); 211 212 // For practical purposes, we consider that the use in a PHI 213 // occurs in the respective predecessor block. For more info, 214 // see the `phi` doc in LangRef and the LCSSA doc. 215 if (auto *PN = dyn_cast<PHINode>(User)) 216 UserBB = PN->getIncomingBlock(*UseToRewrite); 217 218 // If this use is in an exit block, rewrite to use the newly inserted PHI. 219 // This is required for correctness because SSAUpdate doesn't handle uses 220 // in the same block. It assumes the PHI we inserted is at the end of the 221 // block. 222 if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) { 223 UseToRewrite->set(&UserBB->front()); 224 continue; 225 } 226 227 // If we added a single PHI, it must dominate all uses and we can directly 228 // rename it. 229 if (AddedPHIs.size() == 1) { 230 UseToRewrite->set(AddedPHIs[0]); 231 continue; 232 } 233 234 // Otherwise, do full PHI insertion. 235 SSAUpdate.RewriteUse(*UseToRewrite); 236 } 237 238 SmallVector<DbgValueInst *, 4> DbgValues; 239 llvm::findDbgValues(DbgValues, I); 240 241 // Update pre-existing debug value uses that reside outside the loop. 242 for (auto DVI : DbgValues) { 243 BasicBlock *UserBB = DVI->getParent(); 244 if (InstBB == UserBB || L->contains(UserBB)) 245 continue; 246 // We currently only handle debug values residing in blocks that were 247 // traversed while rewriting the uses. If we inserted just a single PHI, 248 // we will handle all relevant debug values. 249 Value *V = AddedPHIs.size() == 1 ? AddedPHIs[0] 250 : SSAUpdate.FindValueForBlock(UserBB); 251 if (V) 252 DVI->replaceVariableLocationOp(I, V); 253 } 254 255 // SSAUpdater might have inserted phi-nodes inside other loops. We'll need 256 // to post-process them to keep LCSSA form. 257 for (PHINode *InsertedPN : InsertedPHIs) { 258 if (auto *OtherLoop = LI.getLoopFor(InsertedPN->getParent())) 259 if (!L->contains(OtherLoop)) 260 PostProcessPHIs.push_back(InsertedPN); 261 } 262 263 // Post process PHI instructions that were inserted into another disjoint 264 // loop and update their exits properly. 265 for (auto *PostProcessPN : PostProcessPHIs) 266 if (!PostProcessPN->use_empty()) 267 Worklist.push_back(PostProcessPN); 268 269 // Keep track of PHI nodes that we want to remove because they did not have 270 // any uses rewritten. 271 for (PHINode *PN : AddedPHIs) 272 if (PN->use_empty()) 273 LocalPHIsToRemove.insert(PN); 274 275 Changed = true; 276 } 277 278 // Remove PHI nodes that did not have any uses rewritten or add them to 279 // PHIsToRemove, so the caller can remove them after some additional cleanup. 280 // We need to redo the use_empty() check here, because even if the PHI node 281 // wasn't used when added to LocalPHIsToRemove, later added PHI nodes can be 282 // using it. This cleanup is not guaranteed to handle trees/cycles of PHI 283 // nodes that only are used by each other. Such situations has only been 284 // noticed when the input IR contains unreachable code, and leaving some extra 285 // redundant PHI nodes in such situations is considered a minor problem. 286 if (PHIsToRemove) { 287 PHIsToRemove->append(LocalPHIsToRemove.begin(), LocalPHIsToRemove.end()); 288 } else { 289 for (PHINode *PN : LocalPHIsToRemove) 290 if (PN->use_empty()) 291 PN->eraseFromParent(); 292 } 293 return Changed; 294 } 295 296 // Compute the set of BasicBlocks in the loop `L` dominating at least one exit. 297 static void computeBlocksDominatingExits( 298 Loop &L, const DominatorTree &DT, SmallVector<BasicBlock *, 8> &ExitBlocks, 299 SmallSetVector<BasicBlock *, 8> &BlocksDominatingExits) { 300 // We start from the exit blocks, as every block trivially dominates itself 301 // (not strictly). 302 SmallVector<BasicBlock *, 8> BBWorklist(ExitBlocks); 303 304 while (!BBWorklist.empty()) { 305 BasicBlock *BB = BBWorklist.pop_back_val(); 306 307 // Check if this is a loop header. If this is the case, we're done. 308 if (L.getHeader() == BB) 309 continue; 310 311 // Otherwise, add its immediate predecessor in the dominator tree to the 312 // worklist, unless we visited it already. 313 BasicBlock *IDomBB = DT.getNode(BB)->getIDom()->getBlock(); 314 315 // Exit blocks can have an immediate dominator not belonging to the 316 // loop. For an exit block to be immediately dominated by another block 317 // outside the loop, it implies not all paths from that dominator, to the 318 // exit block, go through the loop. 319 // Example: 320 // 321 // |---- A 322 // | | 323 // | B<-- 324 // | | | 325 // |---> C -- 326 // | 327 // D 328 // 329 // C is the exit block of the loop and it's immediately dominated by A, 330 // which doesn't belong to the loop. 331 if (!L.contains(IDomBB)) 332 continue; 333 334 if (BlocksDominatingExits.insert(IDomBB)) 335 BBWorklist.push_back(IDomBB); 336 } 337 } 338 339 bool llvm::formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI, 340 ScalarEvolution *SE) { 341 bool Changed = false; 342 343 #ifdef EXPENSIVE_CHECKS 344 // Verify all sub-loops are in LCSSA form already. 345 for (Loop *SubLoop: L) { 346 (void)SubLoop; // Silence unused variable warning. 347 assert(SubLoop->isRecursivelyLCSSAForm(DT, *LI) && "Subloop not in LCSSA!"); 348 } 349 #endif 350 351 SmallVector<BasicBlock *, 8> ExitBlocks; 352 L.getExitBlocks(ExitBlocks); 353 if (ExitBlocks.empty()) 354 return false; 355 356 SmallSetVector<BasicBlock *, 8> BlocksDominatingExits; 357 358 // We want to avoid use-scanning leveraging dominance informations. 359 // If a block doesn't dominate any of the loop exits, the none of the values 360 // defined in the loop can be used outside. 361 // We compute the set of blocks fullfilling the conditions in advance 362 // walking the dominator tree upwards until we hit a loop header. 363 computeBlocksDominatingExits(L, DT, ExitBlocks, BlocksDominatingExits); 364 365 SmallVector<Instruction *, 8> Worklist; 366 367 // Look at all the instructions in the loop, checking to see if they have uses 368 // outside the loop. If so, put them into the worklist to rewrite those uses. 369 for (BasicBlock *BB : BlocksDominatingExits) { 370 // Skip blocks that are part of any sub-loops, they must be in LCSSA 371 // already. 372 if (LI->getLoopFor(BB) != &L) 373 continue; 374 for (Instruction &I : *BB) { 375 // Reject two common cases fast: instructions with no uses (like stores) 376 // and instructions with one use that is in the same block as this. 377 if (I.use_empty() || 378 (I.hasOneUse() && I.user_back()->getParent() == BB && 379 !isa<PHINode>(I.user_back()))) 380 continue; 381 382 // Tokens cannot be used in PHI nodes, so we skip over them. 383 // We can run into tokens which are live out of a loop with catchswitch 384 // instructions in Windows EH if the catchswitch has one catchpad which 385 // is inside the loop and another which is not. 386 if (I.getType()->isTokenTy()) 387 continue; 388 389 Worklist.push_back(&I); 390 } 391 } 392 393 IRBuilder<> Builder(L.getHeader()->getContext()); 394 Changed = formLCSSAForInstructions(Worklist, DT, *LI, SE, Builder); 395 396 // If we modified the code, remove any caches about the loop from SCEV to 397 // avoid dangling entries. 398 // FIXME: This is a big hammer, can we clear the cache more selectively? 399 if (SE && Changed) 400 SE->forgetLoop(&L); 401 402 assert(L.isLCSSAForm(DT)); 403 404 return Changed; 405 } 406 407 /// Process a loop nest depth first. 408 bool llvm::formLCSSARecursively(Loop &L, const DominatorTree &DT, 409 const LoopInfo *LI, ScalarEvolution *SE) { 410 bool Changed = false; 411 412 // Recurse depth-first through inner loops. 413 for (Loop *SubLoop : L.getSubLoops()) 414 Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE); 415 416 Changed |= formLCSSA(L, DT, LI, SE); 417 return Changed; 418 } 419 420 /// Process all loops in the function, inner-most out. 421 static bool formLCSSAOnAllLoops(const LoopInfo *LI, const DominatorTree &DT, 422 ScalarEvolution *SE) { 423 bool Changed = false; 424 for (const auto &L : *LI) 425 Changed |= formLCSSARecursively(*L, DT, LI, SE); 426 return Changed; 427 } 428 429 namespace { 430 struct LCSSAWrapperPass : public FunctionPass { 431 static char ID; // Pass identification, replacement for typeid 432 LCSSAWrapperPass() : FunctionPass(ID) { 433 initializeLCSSAWrapperPassPass(*PassRegistry::getPassRegistry()); 434 } 435 436 // Cached analysis information for the current function. 437 DominatorTree *DT; 438 LoopInfo *LI; 439 ScalarEvolution *SE; 440 441 bool runOnFunction(Function &F) override; 442 void verifyAnalysis() const override { 443 // This check is very expensive. On the loop intensive compiles it may cause 444 // up to 10x slowdown. Currently it's disabled by default. LPPassManager 445 // always does limited form of the LCSSA verification. Similar reasoning 446 // was used for the LoopInfo verifier. 447 if (VerifyLoopLCSSA) { 448 assert(all_of(*LI, 449 [&](Loop *L) { 450 return L->isRecursivelyLCSSAForm(*DT, *LI); 451 }) && 452 "LCSSA form is broken!"); 453 } 454 }; 455 456 /// This transformation requires natural loop information & requires that 457 /// loop preheaders be inserted into the CFG. It maintains both of these, 458 /// as well as the CFG. It also requires dominator information. 459 void getAnalysisUsage(AnalysisUsage &AU) const override { 460 AU.setPreservesCFG(); 461 462 AU.addRequired<DominatorTreeWrapperPass>(); 463 AU.addRequired<LoopInfoWrapperPass>(); 464 AU.addPreservedID(LoopSimplifyID); 465 AU.addPreserved<AAResultsWrapperPass>(); 466 AU.addPreserved<BasicAAWrapperPass>(); 467 AU.addPreserved<GlobalsAAWrapperPass>(); 468 AU.addPreserved<ScalarEvolutionWrapperPass>(); 469 AU.addPreserved<SCEVAAWrapperPass>(); 470 AU.addPreserved<BranchProbabilityInfoWrapperPass>(); 471 AU.addPreserved<MemorySSAWrapperPass>(); 472 473 // This is needed to perform LCSSA verification inside LPPassManager 474 AU.addRequired<LCSSAVerificationPass>(); 475 AU.addPreserved<LCSSAVerificationPass>(); 476 } 477 }; 478 } 479 480 char LCSSAWrapperPass::ID = 0; 481 INITIALIZE_PASS_BEGIN(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass", 482 false, false) 483 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 484 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 485 INITIALIZE_PASS_DEPENDENCY(LCSSAVerificationPass) 486 INITIALIZE_PASS_END(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass", 487 false, false) 488 489 Pass *llvm::createLCSSAPass() { return new LCSSAWrapperPass(); } 490 char &llvm::LCSSAID = LCSSAWrapperPass::ID; 491 492 /// Transform \p F into loop-closed SSA form. 493 bool LCSSAWrapperPass::runOnFunction(Function &F) { 494 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 495 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 496 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 497 SE = SEWP ? &SEWP->getSE() : nullptr; 498 499 return formLCSSAOnAllLoops(LI, *DT, SE); 500 } 501 502 PreservedAnalyses LCSSAPass::run(Function &F, FunctionAnalysisManager &AM) { 503 auto &LI = AM.getResult<LoopAnalysis>(F); 504 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 505 auto *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(F); 506 if (!formLCSSAOnAllLoops(&LI, DT, SE)) 507 return PreservedAnalyses::all(); 508 509 PreservedAnalyses PA; 510 PA.preserveSet<CFGAnalyses>(); 511 PA.preserve<ScalarEvolutionAnalysis>(); 512 // BPI maps terminators to probabilities, since we don't modify the CFG, no 513 // updates are needed to preserve it. 514 PA.preserve<BranchProbabilityAnalysis>(); 515 PA.preserve<MemorySSAAnalysis>(); 516 return PA; 517 } 518