1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===// 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 pass transforms loops by placing phi nodes at the end of the loops for 11 // all values that are live across the loop boundary. For example, it turns 12 // the left into the right code: 13 // 14 // for (...) for (...) 15 // if (c) if (c) 16 // X1 = ... X1 = ... 17 // else else 18 // X2 = ... X2 = ... 19 // X3 = phi(X1, X2) X3 = phi(X1, X2) 20 // ... = X3 + 4 X4 = phi(X3) 21 // ... = X4 + 4 22 // 23 // This is still valid LLVM; the extra phi nodes are purely redundant, and will 24 // be trivially eliminated by InstCombine. The major benefit of this 25 // transformation is that it makes many other loop optimizations, such as 26 // LoopUnswitching, simpler. 27 // 28 //===----------------------------------------------------------------------===// 29 30 #include "llvm/Transforms/Scalar.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/Analysis/AliasAnalysis.h" 34 #include "llvm/Analysis/GlobalsModRef.h" 35 #include "llvm/Analysis/LoopPass.h" 36 #include "llvm/Analysis/ScalarEvolution.h" 37 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/Dominators.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/Instructions.h" 42 #include "llvm/IR/PredIteratorCache.h" 43 #include "llvm/Pass.h" 44 #include "llvm/Transforms/Utils/LoopUtils.h" 45 #include "llvm/Transforms/Utils/SSAUpdater.h" 46 using namespace llvm; 47 48 #define DEBUG_TYPE "lcssa" 49 50 STATISTIC(NumLCSSA, "Number of live out of a loop variables"); 51 52 /// Return true if the specified block is in the list. 53 static bool isExitBlock(BasicBlock *BB, 54 const SmallVectorImpl<BasicBlock *> &ExitBlocks) { 55 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 56 if (ExitBlocks[i] == BB) 57 return true; 58 return false; 59 } 60 61 /// Given an instruction in the loop, check to see if it has any uses that are 62 /// outside the current loop. If so, insert LCSSA PHI nodes and rewrite the 63 /// uses. 64 static bool processInstruction(Loop &L, Instruction &Inst, DominatorTree &DT, 65 const SmallVectorImpl<BasicBlock *> &ExitBlocks, 66 PredIteratorCache &PredCache, LoopInfo *LI) { 67 SmallVector<Use *, 16> UsesToRewrite; 68 69 BasicBlock *InstBB = Inst.getParent(); 70 71 for (Use &U : Inst.uses()) { 72 Instruction *User = cast<Instruction>(U.getUser()); 73 BasicBlock *UserBB = User->getParent(); 74 if (PHINode *PN = dyn_cast<PHINode>(User)) 75 UserBB = PN->getIncomingBlock(U); 76 77 if (InstBB != UserBB && !L.contains(UserBB)) 78 UsesToRewrite.push_back(&U); 79 } 80 81 // If there are no uses outside the loop, exit with no change. 82 if (UsesToRewrite.empty()) 83 return false; 84 85 ++NumLCSSA; // We are applying the transformation 86 87 // Invoke instructions are special in that their result value is not available 88 // along their unwind edge. The code below tests to see whether DomBB 89 // dominates the value, so adjust DomBB to the normal destination block, 90 // which is effectively where the value is first usable. 91 BasicBlock *DomBB = Inst.getParent(); 92 if (InvokeInst *Inv = dyn_cast<InvokeInst>(&Inst)) 93 DomBB = Inv->getNormalDest(); 94 95 DomTreeNode *DomNode = DT.getNode(DomBB); 96 97 SmallVector<PHINode *, 16> AddedPHIs; 98 SmallVector<PHINode *, 8> PostProcessPHIs; 99 100 SSAUpdater SSAUpdate; 101 SSAUpdate.Initialize(Inst.getType(), Inst.getName()); 102 103 // Insert the LCSSA phi's into all of the exit blocks dominated by the 104 // value, and add them to the Phi's map. 105 for (BasicBlock *ExitBB : ExitBlocks) { 106 if (!DT.dominates(DomNode, DT.getNode(ExitBB))) 107 continue; 108 109 // If we already inserted something for this BB, don't reprocess it. 110 if (SSAUpdate.HasValueForBlock(ExitBB)) 111 continue; 112 113 PHINode *PN = PHINode::Create(Inst.getType(), PredCache.size(ExitBB), 114 Inst.getName() + ".lcssa", &ExitBB->front()); 115 116 // Add inputs from inside the loop for this PHI. 117 for (BasicBlock *Pred : PredCache.get(ExitBB)) { 118 PN->addIncoming(&Inst, Pred); 119 120 // If the exit block has a predecessor not within the loop, arrange for 121 // the incoming value use corresponding to that predecessor to be 122 // rewritten in terms of a different LCSSA PHI. 123 if (!L.contains(Pred)) 124 UsesToRewrite.push_back( 125 &PN->getOperandUse(PN->getOperandNumForIncomingValue( 126 PN->getNumIncomingValues() - 1))); 127 } 128 129 AddedPHIs.push_back(PN); 130 131 // Remember that this phi makes the value alive in this block. 132 SSAUpdate.AddAvailableValue(ExitBB, PN); 133 134 // LoopSimplify might fail to simplify some loops (e.g. when indirect 135 // branches are involved). In such situations, it might happen that an exit 136 // for Loop L1 is the header of a disjoint Loop L2. Thus, when we create 137 // PHIs in such an exit block, we are also inserting PHIs into L2's header. 138 // This could break LCSSA form for L2 because these inserted PHIs can also 139 // have uses outside of L2. Remember all PHIs in such situation as to 140 // revisit than later on. FIXME: Remove this if indirectbr support into 141 // LoopSimplify gets improved. 142 if (auto *OtherLoop = LI->getLoopFor(ExitBB)) 143 if (!L.contains(OtherLoop)) 144 PostProcessPHIs.push_back(PN); 145 } 146 147 // Rewrite all uses outside the loop in terms of the new PHIs we just 148 // inserted. 149 for (Use *UseToRewrite : UsesToRewrite) { 150 // If this use is in an exit block, rewrite to use the newly inserted PHI. 151 // This is required for correctness because SSAUpdate doesn't handle uses in 152 // the same block. It assumes the PHI we inserted is at the end of the 153 // block. 154 Instruction *User = cast<Instruction>(UseToRewrite->getUser()); 155 BasicBlock *UserBB = User->getParent(); 156 if (PHINode *PN = dyn_cast<PHINode>(User)) 157 UserBB = PN->getIncomingBlock(*UseToRewrite); 158 159 if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) { 160 // Tell the VHs that the uses changed. This updates SCEV's caches. 161 if (UseToRewrite->get()->hasValueHandle()) 162 ValueHandleBase::ValueIsRAUWd(*UseToRewrite, &UserBB->front()); 163 UseToRewrite->set(&UserBB->front()); 164 continue; 165 } 166 167 // Otherwise, do full PHI insertion. 168 SSAUpdate.RewriteUse(*UseToRewrite); 169 } 170 171 // Post process PHI instructions that were inserted into another disjoint loop 172 // and update their exits properly. 173 for (auto *I : PostProcessPHIs) { 174 if (I->use_empty()) 175 continue; 176 177 BasicBlock *PHIBB = I->getParent(); 178 Loop *OtherLoop = LI->getLoopFor(PHIBB); 179 SmallVector<BasicBlock *, 8> EBs; 180 OtherLoop->getExitBlocks(EBs); 181 if (EBs.empty()) 182 continue; 183 184 // Recurse and re-process each PHI instruction. FIXME: we should really 185 // convert this entire thing to a worklist approach where we process a 186 // vector of instructions... 187 processInstruction(*OtherLoop, *I, DT, EBs, PredCache, LI); 188 } 189 190 // Remove PHI nodes that did not have any uses rewritten. 191 for (PHINode *PN : AddedPHIs) 192 if (PN->use_empty()) 193 PN->eraseFromParent(); 194 195 return true; 196 } 197 198 /// Return true if the specified block dominates at least 199 /// one of the blocks in the specified list. 200 static bool 201 blockDominatesAnExit(BasicBlock *BB, 202 DominatorTree &DT, 203 const SmallVectorImpl<BasicBlock *> &ExitBlocks) { 204 DomTreeNode *DomNode = DT.getNode(BB); 205 for (BasicBlock *ExitBB : ExitBlocks) 206 if (DT.dominates(DomNode, DT.getNode(ExitBB))) 207 return true; 208 209 return false; 210 } 211 212 bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI, 213 ScalarEvolution *SE) { 214 bool Changed = false; 215 216 // Get the set of exiting blocks. 217 SmallVector<BasicBlock *, 8> ExitBlocks; 218 L.getExitBlocks(ExitBlocks); 219 220 if (ExitBlocks.empty()) 221 return false; 222 223 PredIteratorCache PredCache; 224 225 // Look at all the instructions in the loop, checking to see if they have uses 226 // outside the loop. If so, rewrite those uses. 227 for (BasicBlock *BB : L.blocks()) { 228 // For large loops, avoid use-scanning by using dominance information: In 229 // particular, if a block does not dominate any of the loop exits, then none 230 // of the values defined in the block could be used outside the loop. 231 if (!blockDominatesAnExit(BB, DT, ExitBlocks)) 232 continue; 233 234 for (Instruction &I : *BB) { 235 // Reject two common cases fast: instructions with no uses (like stores) 236 // and instructions with one use that is in the same block as this. 237 if (I.use_empty() || 238 (I.hasOneUse() && I.user_back()->getParent() == BB && 239 !isa<PHINode>(I.user_back()))) 240 continue; 241 242 Changed |= processInstruction(L, I, DT, ExitBlocks, PredCache, LI); 243 } 244 } 245 246 // If we modified the code, remove any caches about the loop from SCEV to 247 // avoid dangling entries. 248 // FIXME: This is a big hammer, can we clear the cache more selectively? 249 if (SE && Changed) 250 SE->forgetLoop(&L); 251 252 assert(L.isLCSSAForm(DT)); 253 254 return Changed; 255 } 256 257 /// Process a loop nest depth first. 258 bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, 259 ScalarEvolution *SE) { 260 bool Changed = false; 261 262 // Recurse depth-first through inner loops. 263 for (Loop *SubLoop : L.getSubLoops()) 264 Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE); 265 266 Changed |= formLCSSA(L, DT, LI, SE); 267 return Changed; 268 } 269 270 namespace { 271 struct LCSSA : public FunctionPass { 272 static char ID; // Pass identification, replacement for typeid 273 LCSSA() : FunctionPass(ID) { 274 initializeLCSSAPass(*PassRegistry::getPassRegistry()); 275 } 276 277 // Cached analysis information for the current function. 278 DominatorTree *DT; 279 LoopInfo *LI; 280 ScalarEvolution *SE; 281 282 bool runOnFunction(Function &F) override; 283 284 /// This transformation requires natural loop information & requires that 285 /// loop preheaders be inserted into the CFG. It maintains both of these, 286 /// as well as the CFG. It also requires dominator information. 287 void getAnalysisUsage(AnalysisUsage &AU) const override { 288 AU.setPreservesCFG(); 289 290 AU.addRequired<DominatorTreeWrapperPass>(); 291 AU.addRequired<LoopInfoWrapperPass>(); 292 AU.addPreservedID(LoopSimplifyID); 293 AU.addPreserved<AAResultsWrapperPass>(); 294 AU.addPreserved<GlobalsAAWrapperPass>(); 295 AU.addPreserved<ScalarEvolutionWrapperPass>(); 296 AU.addPreserved<SCEVAAWrapperPass>(); 297 } 298 }; 299 } 300 301 char LCSSA::ID = 0; 302 INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false) 303 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 304 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 305 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 306 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 307 INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false) 308 309 Pass *llvm::createLCSSAPass() { return new LCSSA(); } 310 char &llvm::LCSSAID = LCSSA::ID; 311 312 313 /// Process all loops in the function, inner-most out. 314 bool LCSSA::runOnFunction(Function &F) { 315 bool Changed = false; 316 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 317 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 318 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 319 SE = SEWP ? &SEWP->getSE() : nullptr; 320 321 // Simplify each loop nest in the function. 322 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 323 Changed |= formLCSSARecursively(**I, *DT, LI, SE); 324 325 return Changed; 326 } 327 328