LoopSimplify.cpp revision dfa5f83c8ea9fa577c5a42407c3fd8b6c789a6dd
1//===- LoopPreheaders.cpp - Loop Preheader Insertion Pass -----------------===// 2// 3// Insert Loop pre-headers and exit blocks into the CFG for each function in the 4// module. This pass updates loop information and dominator information. 5// 6// Loop pre-header insertion guarantees that there is a single, non-critical 7// entry edge from outside of the loop to the loop header. This simplifies a 8// number of analyses and transformations, such as LICM. 9// 10// Loop exit-block insertion guarantees that all exit blocks from the loop 11// (blocks which are outside of the loop that have predecessors inside of the 12// loop) are dominated by the loop header. This simplifies transformations such 13// as store-sinking that are built into LICM. 14// 15// Note that the simplifycfg pass will clean up blocks which are split out but 16// end up being unnecessary, so usage of this pass does not neccesarily 17// pessimize generated code. 18// 19//===----------------------------------------------------------------------===// 20 21#include "llvm/Transforms/Scalar.h" 22#include "llvm/Analysis/Dominators.h" 23#include "llvm/Analysis/LoopInfo.h" 24#include "llvm/Function.h" 25#include "llvm/iTerminators.h" 26#include "llvm/iPHINode.h" 27#include "llvm/Constant.h" 28#include "llvm/Support/CFG.h" 29#include "Support/SetOperations.h" 30#include "Support/Statistic.h" 31#include "Support/DepthFirstIterator.h" 32 33namespace { 34 Statistic<> NumInserted("preheaders", "Number of pre-header nodes inserted"); 35 36 struct Preheaders : public FunctionPass { 37 virtual bool runOnFunction(Function &F); 38 39 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 40 // We need loop information to identify the loops... 41 AU.addRequired<LoopInfo>(); 42 AU.addRequired<DominatorSet>(); 43 44 AU.addPreserved<LoopInfo>(); 45 AU.addPreserved<DominatorSet>(); 46 AU.addPreserved<ImmediateDominators>(); 47 AU.addPreserved<DominatorTree>(); 48 AU.addPreserved<DominanceFrontier>(); 49 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added.... 50 } 51 private: 52 bool ProcessLoop(Loop *L); 53 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix, 54 const std::vector<BasicBlock*> &Preds); 55 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit); 56 void InsertPreheaderForLoop(Loop *L); 57 }; 58 59 RegisterOpt<Preheaders> X("preheaders", "Natural loop pre-header insertion"); 60} 61 62// Publically exposed interface to pass... 63const PassInfo *LoopPreheadersID = X.getPassInfo(); 64Pass *createLoopPreheaderInsertionPass() { return new Preheaders(); } 65 66 67/// runOnFunction - Run down all loops in the CFG (recursively, but we could do 68/// it in any convenient order) inserting preheaders... 69/// 70bool Preheaders::runOnFunction(Function &F) { 71 bool Changed = false; 72 LoopInfo &LI = getAnalysis<LoopInfo>(); 73 74 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i) 75 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]); 76 77 return Changed; 78} 79 80 81/// ProcessLoop - Walk the loop structure in depth first order, ensuring that 82/// all loops have preheaders. 83/// 84bool Preheaders::ProcessLoop(Loop *L) { 85 bool Changed = false; 86 87 // Does the loop already have a preheader? If so, don't modify the loop... 88 if (L->getLoopPreheader() == 0) { 89 InsertPreheaderForLoop(L); 90 NumInserted++; 91 Changed = true; 92 } 93 94 // Regardless of whether or not we added a preheader to the loop we must 95 // guarantee that the preheader dominates all exit nodes. If there are any 96 // exit nodes not dominated, split them now. 97 DominatorSet &DS = getAnalysis<DominatorSet>(); 98 BasicBlock *Header = L->getHeader(); 99 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i) 100 if (!DS.dominates(Header, L->getExitBlocks()[i])) { 101 RewriteLoopExitBlock(L, L->getExitBlocks()[i]); 102 assert(DS.dominates(Header, L->getExitBlocks()[i]) && 103 "RewriteLoopExitBlock failed?"); 104 NumInserted++; 105 Changed = true; 106 } 107 108 const std::vector<Loop*> &SubLoops = L->getSubLoops(); 109 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) 110 Changed |= ProcessLoop(SubLoops[i]); 111 return Changed; 112} 113 114/// SplitBlockPredecessors - Split the specified block into two blocks. We want 115/// to move the predecessors specified in the Preds list to point to the new 116/// block, leaving the remaining predecessors pointing to BB. This method 117/// updates the SSA PHINode's, but no other analyses. 118/// 119BasicBlock *Preheaders::SplitBlockPredecessors(BasicBlock *BB, 120 const char *Suffix, 121 const std::vector<BasicBlock*> &Preds) { 122 123 // Create new basic block, insert right before the original block... 124 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB); 125 126 // The preheader first gets an unconditional branch to the loop header... 127 BranchInst *BI = new BranchInst(BB); 128 NewBB->getInstList().push_back(BI); 129 130 // For every PHI node in the block, insert a PHI node into NewBB where the 131 // incoming values from the out of loop edges are moved to NewBB. We have two 132 // possible cases here. If the loop is dead, we just insert dummy entries 133 // into the PHI nodes for the new edge. If the loop is not dead, we move the 134 // incoming edges in BB into new PHI nodes in NewBB. 135 // 136 if (!Preds.empty()) { // Is the loop not obviously dead? 137 for (BasicBlock::iterator I = BB->begin(); 138 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 139 140 // Create the new PHI node, insert it into NewBB at the end of the block 141 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI); 142 143 // Move all of the edges from blocks outside the loop to the new PHI 144 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 145 Value *V = PN->removeIncomingValue(Preds[i]); 146 NewPHI->addIncoming(V, Preds[i]); 147 } 148 149 // Add an incoming value to the PHI node in the loop for the preheader 150 // edge 151 PN->addIncoming(NewPHI, NewBB); 152 } 153 154 // Now that the PHI nodes are updated, actually move the edges from 155 // Preds to point to NewBB instead of BB. 156 // 157 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 158 TerminatorInst *TI = Preds[i]->getTerminator(); 159 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) 160 if (TI->getSuccessor(s) == BB) 161 TI->setSuccessor(s, NewBB); 162 } 163 164 } else { // Otherwise the loop is dead... 165 for (BasicBlock::iterator I = BB->begin(); 166 PHINode *PN = dyn_cast<PHINode>(I); ++I) 167 // Insert dummy values as the incoming value... 168 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB); 169 } 170 return NewBB; 171} 172 173// ChangeExitBlock - This recursive function is used to change any exit blocks 174// that use OldExit to use NewExit instead. This is recursive because children 175// may need to be processed as well. 176// 177static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) { 178 if (L->hasExitBlock(OldExit)) { 179 L->changeExitBlock(OldExit, NewExit); 180 const std::vector<Loop*> &SubLoops = L->getSubLoops(); 181 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) 182 ChangeExitBlock(SubLoops[i], OldExit, NewExit); 183 } 184} 185 186 187/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a 188/// preheader, this method is called to insert one. This method has two phases: 189/// preheader insertion and analysis updating. 190/// 191void Preheaders::InsertPreheaderForLoop(Loop *L) { 192 BasicBlock *Header = L->getHeader(); 193 194 // Compute the set of predecessors of the loop that are not in the loop. 195 std::vector<BasicBlock*> OutsideBlocks; 196 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header); 197 PI != PE; ++PI) 198 if (!L->contains(*PI)) // Coming in from outside the loop? 199 OutsideBlocks.push_back(*PI); // Keep track of it... 200 201 // Split out the loop pre-header 202 BasicBlock *NewBB = 203 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks); 204 205 //===--------------------------------------------------------------------===// 206 // Update analysis results now that we have preformed the transformation 207 // 208 209 // We know that we have loop information to update... update it now. 210 if (Loop *Parent = L->getParentLoop()) 211 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>()); 212 213 // If the header for the loop used to be an exit node for another loop, then 214 // we need to update this to know that the loop-preheader is now the exit 215 // node. Note that the only loop that could have our header as an exit node 216 // is a sibling loop, ie, one with the same parent loop, or one if it's 217 // children. 218 // 219 const std::vector<Loop*> *ParentSubLoops; 220 if (Loop *Parent = L->getParentLoop()) 221 ParentSubLoops = &Parent->getSubLoops(); 222 else // Must check top-level loops... 223 ParentSubLoops = &getAnalysis<LoopInfo>().getTopLevelLoops(); 224 225 // Loop over all sibling loops, performing the substitution (recursively to 226 // include child loops)... 227 for (unsigned i = 0, e = ParentSubLoops->size(); i != e; ++i) 228 ChangeExitBlock((*ParentSubLoops)[i], Header, NewBB); 229 230 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info 231 { 232 // The blocks that dominate NewBB are the blocks that dominate Header, 233 // minus Header, plus NewBB. 234 DominatorSet::DomSetType DomSet = DS.getDominators(Header); 235 DomSet.insert(NewBB); // We dominate ourself 236 DomSet.erase(Header); // Header does not dominate us... 237 DS.addBasicBlock(NewBB, DomSet); 238 239 // The newly created basic block dominates all nodes dominated by Header. 240 for (Function::iterator I = Header->getParent()->begin(), 241 E = Header->getParent()->end(); I != E; ++I) 242 if (DS.dominates(Header, I)) 243 DS.addDominator(I, NewBB); 244 } 245 246 // Update immediate dominator information if we have it... 247 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) { 248 // Whatever i-dominated the header node now immediately dominates NewBB 249 ID->addNewBlock(NewBB, ID->get(Header)); 250 251 // The preheader now is the immediate dominator for the header node... 252 ID->setImmediateDominator(Header, NewBB); 253 } 254 255 // Update DominatorTree information if it is active. 256 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) { 257 // The immediate dominator of the preheader is the immediate dominator of 258 // the old header. 259 // 260 DominatorTree::Node *HeaderNode = DT->getNode(Header); 261 DominatorTree::Node *PHNode = DT->createNewNode(NewBB, 262 HeaderNode->getIDom()); 263 264 // Change the header node so that PNHode is the new immediate dominator 265 DT->changeImmediateDominator(HeaderNode, PHNode); 266 } 267 268 // Update dominance frontier information... 269 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) { 270 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates 271 // everything that Header does, and it strictly dominates Header in 272 // addition. 273 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?"); 274 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second; 275 NewDFSet.erase(Header); 276 DF->addBasicBlock(NewBB, NewDFSet); 277 278 // Now we must loop over all of the dominance frontiers in the function, 279 // replacing occurrences of Header with NewBB in some cases. If a block 280 // dominates a (now) predecessor of NewBB, but did not strictly dominate 281 // Header, it will have Header in it's DF set, but should now have NewBB in 282 // its set. 283 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) { 284 // Get all of the dominators of the predecessor... 285 const DominatorSet::DomSetType &PredDoms = 286 DS.getDominators(OutsideBlocks[i]); 287 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(), 288 PDE = PredDoms.end(); PDI != PDE; ++PDI) { 289 BasicBlock *PredDom = *PDI; 290 // If the loop header is in DF(PredDom), then PredDom didn't dominate 291 // the header but did dominate a predecessor outside of the loop. Now 292 // we change this entry to include the preheader in the DF instead of 293 // the header. 294 DominanceFrontier::iterator DFI = DF->find(PredDom); 295 assert(DFI != DF->end() && "No dominance frontier for node?"); 296 if (DFI->second.count(Header)) { 297 DF->removeFromFrontier(DFI, Header); 298 DF->addToFrontier(DFI, NewBB); 299 } 300 } 301 } 302 } 303} 304 305void Preheaders::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) { 306 DominatorSet &DS = getAnalysis<DominatorSet>(); 307 assert(!DS.dominates(L->getHeader(), Exit) && 308 "Loop already dominates exit block??"); 309 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit) 310 != L->getExitBlocks().end() && "Not a current exit block!"); 311 312 std::vector<BasicBlock*> LoopBlocks; 313 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) 314 if (L->contains(*I)) 315 LoopBlocks.push_back(*I); 316 317 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?"); 318 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks); 319 320 // Update Loop Information - we know that the new block will be in the parent 321 // loop of L. 322 if (Loop *Parent = L->getParentLoop()) 323 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>()); 324 325 // Replace any instances of Exit with NewBB in this and any nested loops... 326 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I) 327 if (I->hasExitBlock(Exit)) 328 I->changeExitBlock(Exit, NewBB); // Update exit block information 329 330 // Update dominator information... The blocks that dominate NewBB are the 331 // intersection of the dominators of predecessors, plus the block itself. 332 // The newly created basic block does not dominate anything except itself. 333 // 334 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(LoopBlocks[0]); 335 for (unsigned i = 1, e = LoopBlocks.size(); i != e; ++i) 336 set_intersect(NewBBDomSet, DS.getDominators(LoopBlocks[i])); 337 NewBBDomSet.insert(NewBB); // All blocks dominate themselves... 338 DS.addBasicBlock(NewBB, NewBBDomSet); 339 340 // Update immediate dominator information if we have it... 341 BasicBlock *NewBBIDom = 0; 342 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) { 343 // This block does not strictly dominate anything, so it is not an immediate 344 // dominator. To find the immediate dominator of the new exit node, we 345 // trace up the immediate dominators of a predecessor until we find a basic 346 // block that dominates the exit block. 347 // 348 BasicBlock *Dom = LoopBlocks[0]; // Some random predecessor... 349 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator... 350 assert(Dom != 0 && "No shared dominator found???"); 351 Dom = ID->get(Dom); 352 } 353 354 // Set the immediate dominator now... 355 ID->addNewBlock(NewBB, Dom); 356 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info... 357 } 358 359 // Update DominatorTree information if it is active. 360 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) { 361 // NewBB doesn't dominate anything, so just create a node and link it into 362 // its immediate dominator. If we don't have ImmediateDominator info 363 // around, calculate the idom as above. 364 DominatorTree::Node *NewBBIDomNode; 365 if (NewBBIDom) { 366 NewBBIDomNode = DT->getNode(NewBBIDom); 367 } else { 368 NewBBIDomNode = DT->getNode(LoopBlocks[0]); // Random pred 369 while (!NewBBDomSet.count(NewBBIDomNode->getNode())) { 370 NewBBIDomNode = NewBBIDomNode->getIDom(); 371 assert(NewBBIDomNode && "No shared dominator found??"); 372 } 373 } 374 375 // Create the new dominator tree node... 376 DT->createNewNode(NewBB, NewBBIDomNode); 377 } 378 379 // Update dominance frontier information... 380 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) { 381 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it 382 // does dominate itself (and there is an edge (NewBB -> Exit)). 383 DominanceFrontier::DomSetType NewDFSet; 384 NewDFSet.insert(Exit); 385 DF->addBasicBlock(NewBB, NewDFSet); 386 387 // Now we must loop over all of the dominance frontiers in the function, 388 // replacing occurrences of Exit with NewBB in some cases. If a block 389 // dominates a (now) predecessor of NewBB, but did not strictly dominate 390 // Exit, it will have Exit in it's DF set, but should now have NewBB in its 391 // set. 392 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) { 393 // Get all of the dominators of the predecessor... 394 const DominatorSet::DomSetType &PredDoms =DS.getDominators(LoopBlocks[i]); 395 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(), 396 PDE = PredDoms.end(); PDI != PDE; ++PDI) { 397 BasicBlock *PredDom = *PDI; 398 // Make sure to only rewrite blocks that are part of the loop... 399 if (L->contains(PredDom)) { 400 // If the exit node is in DF(PredDom), then PredDom didn't dominate 401 // Exit but did dominate a predecessor inside of the loop. Now we 402 // change this entry to include NewBB in the DF instead of Exit. 403 DominanceFrontier::iterator DFI = DF->find(PredDom); 404 assert(DFI != DF->end() && "No dominance frontier for node?"); 405 if (DFI->second.count(Exit)) { 406 DF->removeFromFrontier(DFI, Exit); 407 DF->addToFrontier(DFI, NewBB); 408 } 409 } 410 } 411 } 412 } 413} 414