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/CatchPad instructions are special in that their result value is not 88 // available along their unwind edge. The code below tests to see whether 89 // DomBB 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 if (auto *CPI = dyn_cast<CatchPadInst>(&Inst)) 95 DomBB = CPI->getNormalDest(); 96 97 DomTreeNode *DomNode = DT.getNode(DomBB); 98 99 SmallVector<PHINode *, 16> AddedPHIs; 100 SmallVector<PHINode *, 8> PostProcessPHIs; 101 102 SSAUpdater SSAUpdate; 103 SSAUpdate.Initialize(Inst.getType(), Inst.getName()); 104 105 // Insert the LCSSA phi's into all of the exit blocks dominated by the 106 // value, and add them to the Phi's map. 107 for (SmallVectorImpl<BasicBlock *>::const_iterator BBI = ExitBlocks.begin(), 108 BBE = ExitBlocks.end(); 109 BBI != BBE; ++BBI) { 110 BasicBlock *ExitBB = *BBI; 111 if (!DT.dominates(DomNode, DT.getNode(ExitBB))) 112 continue; 113 114 // If we already inserted something for this BB, don't reprocess it. 115 if (SSAUpdate.HasValueForBlock(ExitBB)) 116 continue; 117 118 PHINode *PN = PHINode::Create(Inst.getType(), PredCache.size(ExitBB), 119 Inst.getName() + ".lcssa", ExitBB->begin()); 120 121 // Add inputs from inside the loop for this PHI. 122 for (BasicBlock *Pred : PredCache.get(ExitBB)) { 123 PN->addIncoming(&Inst, Pred); 124 125 // If the exit block has a predecessor not within the loop, arrange for 126 // the incoming value use corresponding to that predecessor to be 127 // rewritten in terms of a different LCSSA PHI. 128 if (!L.contains(Pred)) 129 UsesToRewrite.push_back( 130 &PN->getOperandUse(PN->getOperandNumForIncomingValue( 131 PN->getNumIncomingValues() - 1))); 132 } 133 134 AddedPHIs.push_back(PN); 135 136 // Remember that this phi makes the value alive in this block. 137 SSAUpdate.AddAvailableValue(ExitBB, PN); 138 139 // LoopSimplify might fail to simplify some loops (e.g. when indirect 140 // branches are involved). In such situations, it might happen that an exit 141 // for Loop L1 is the header of a disjoint Loop L2. Thus, when we create 142 // PHIs in such an exit block, we are also inserting PHIs into L2's header. 143 // This could break LCSSA form for L2 because these inserted PHIs can also 144 // have uses outside of L2. Remember all PHIs in such situation as to 145 // revisit than later on. FIXME: Remove this if indirectbr support into 146 // LoopSimplify gets improved. 147 if (auto *OtherLoop = LI->getLoopFor(ExitBB)) 148 if (!L.contains(OtherLoop)) 149 PostProcessPHIs.push_back(PN); 150 } 151 152 // Rewrite all uses outside the loop in terms of the new PHIs we just 153 // inserted. 154 for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) { 155 // If this use is in an exit block, rewrite to use the newly inserted PHI. 156 // This is required for correctness because SSAUpdate doesn't handle uses in 157 // the same block. It assumes the PHI we inserted is at the end of the 158 // block. 159 Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser()); 160 BasicBlock *UserBB = User->getParent(); 161 if (PHINode *PN = dyn_cast<PHINode>(User)) 162 UserBB = PN->getIncomingBlock(*UsesToRewrite[i]); 163 164 if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) { 165 // Tell the VHs that the uses changed. This updates SCEV's caches. 166 if (UsesToRewrite[i]->get()->hasValueHandle()) 167 ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i], UserBB->begin()); 168 UsesToRewrite[i]->set(UserBB->begin()); 169 continue; 170 } 171 172 // Otherwise, do full PHI insertion. 173 SSAUpdate.RewriteUse(*UsesToRewrite[i]); 174 } 175 176 // Post process PHI instructions that were inserted into another disjoint loop 177 // and update their exits properly. 178 for (auto *I : PostProcessPHIs) { 179 if (I->use_empty()) 180 continue; 181 182 BasicBlock *PHIBB = I->getParent(); 183 Loop *OtherLoop = LI->getLoopFor(PHIBB); 184 SmallVector<BasicBlock *, 8> EBs; 185 OtherLoop->getExitBlocks(EBs); 186 if (EBs.empty()) 187 continue; 188 189 // Recurse and re-process each PHI instruction. FIXME: we should really 190 // convert this entire thing to a worklist approach where we process a 191 // vector of instructions... 192 processInstruction(*OtherLoop, *I, DT, EBs, PredCache, LI); 193 } 194 195 // Remove PHI nodes that did not have any uses rewritten. 196 for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) { 197 if (AddedPHIs[i]->use_empty()) 198 AddedPHIs[i]->eraseFromParent(); 199 } 200 201 return true; 202 } 203 204 /// Return true if the specified block dominates at least 205 /// one of the blocks in the specified list. 206 static bool 207 blockDominatesAnExit(BasicBlock *BB, 208 DominatorTree &DT, 209 const SmallVectorImpl<BasicBlock *> &ExitBlocks) { 210 DomTreeNode *DomNode = DT.getNode(BB); 211 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 212 if (DT.dominates(DomNode, DT.getNode(ExitBlocks[i]))) 213 return true; 214 215 return false; 216 } 217 218 bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI, 219 ScalarEvolution *SE) { 220 bool Changed = false; 221 222 // Get the set of exiting blocks. 223 SmallVector<BasicBlock *, 8> ExitBlocks; 224 L.getExitBlocks(ExitBlocks); 225 226 if (ExitBlocks.empty()) 227 return false; 228 229 PredIteratorCache PredCache; 230 231 // Look at all the instructions in the loop, checking to see if they have uses 232 // outside the loop. If so, rewrite those uses. 233 for (Loop::block_iterator BBI = L.block_begin(), BBE = L.block_end(); 234 BBI != BBE; ++BBI) { 235 BasicBlock *BB = *BBI; 236 237 // For large loops, avoid use-scanning by using dominance information: In 238 // particular, if a block does not dominate any of the loop exits, then none 239 // of the values defined in the block could be used outside the loop. 240 if (!blockDominatesAnExit(BB, DT, ExitBlocks)) 241 continue; 242 243 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 244 // Reject two common cases fast: instructions with no uses (like stores) 245 // and instructions with one use that is in the same block as this. 246 if (I->use_empty() || 247 (I->hasOneUse() && I->user_back()->getParent() == BB && 248 !isa<PHINode>(I->user_back()))) 249 continue; 250 251 Changed |= processInstruction(L, *I, DT, ExitBlocks, PredCache, LI); 252 } 253 } 254 255 // If we modified the code, remove any caches about the loop from SCEV to 256 // avoid dangling entries. 257 // FIXME: This is a big hammer, can we clear the cache more selectively? 258 if (SE && Changed) 259 SE->forgetLoop(&L); 260 261 assert(L.isLCSSAForm(DT)); 262 263 return Changed; 264 } 265 266 /// Process a loop nest depth first. 267 bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, 268 ScalarEvolution *SE) { 269 bool Changed = false; 270 271 // Recurse depth-first through inner loops. 272 for (Loop::iterator I = L.begin(), E = L.end(); I != E; ++I) 273 Changed |= formLCSSARecursively(**I, DT, LI, SE); 274 275 Changed |= formLCSSA(L, DT, LI, SE); 276 return Changed; 277 } 278 279 namespace { 280 struct LCSSA : public FunctionPass { 281 static char ID; // Pass identification, replacement for typeid 282 LCSSA() : FunctionPass(ID) { 283 initializeLCSSAPass(*PassRegistry::getPassRegistry()); 284 } 285 286 // Cached analysis information for the current function. 287 DominatorTree *DT; 288 LoopInfo *LI; 289 ScalarEvolution *SE; 290 291 bool runOnFunction(Function &F) override; 292 293 /// This transformation requires natural loop information & requires that 294 /// loop preheaders be inserted into the CFG. It maintains both of these, 295 /// as well as the CFG. It also requires dominator information. 296 void getAnalysisUsage(AnalysisUsage &AU) const override { 297 AU.setPreservesCFG(); 298 299 AU.addRequired<DominatorTreeWrapperPass>(); 300 AU.addRequired<LoopInfoWrapperPass>(); 301 AU.addPreservedID(LoopSimplifyID); 302 AU.addPreserved<AAResultsWrapperPass>(); 303 AU.addPreserved<GlobalsAAWrapperPass>(); 304 AU.addPreserved<ScalarEvolutionWrapperPass>(); 305 AU.addPreserved<SCEVAAWrapperPass>(); 306 } 307 }; 308 } 309 310 char LCSSA::ID = 0; 311 INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false) 312 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 313 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 314 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 315 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 316 INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false) 317 318 Pass *llvm::createLCSSAPass() { return new LCSSA(); } 319 char &llvm::LCSSAID = LCSSA::ID; 320 321 322 /// Process all loops in the function, inner-most out. 323 bool LCSSA::runOnFunction(Function &F) { 324 bool Changed = false; 325 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 326 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 327 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 328 SE = SEWP ? &SEWP->getSE() : nullptr; 329 330 // Simplify each loop nest in the function. 331 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 332 Changed |= formLCSSARecursively(**I, *DT, LI, SE); 333 334 return Changed; 335 } 336 337