LoopSimplify.cpp revision 7b714321df4d286018d594c9c9f132f343dbabdc
1//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This pass performs several transformations to transform natural loops into a 11// simpler form, which makes subsequent analyses and transformations simpler and 12// more effective. 13// 14// Loop pre-header insertion guarantees that there is a single, non-critical 15// entry edge from outside of the loop to the loop header. This simplifies a 16// number of analyses and transformations, such as LICM. 17// 18// Loop exit-block insertion guarantees that all exit blocks from the loop 19// (blocks which are outside of the loop that have predecessors inside of the 20// loop) only have predecessors from inside of the loop (and are thus dominated 21// by the loop header). This simplifies transformations such as store-sinking 22// that are built into LICM. 23// 24// This pass also guarantees that loops will have exactly one backedge. 25// 26// Note that the simplifycfg pass will clean up blocks which are split out but 27// end up being unnecessary, so usage of this pass should not pessimize 28// generated code. 29// 30// This pass obviously modifies the CFG, but updates loop information and 31// dominator information. 32// 33//===----------------------------------------------------------------------===// 34 35#define DEBUG_TYPE "loopsimplify" 36#include "llvm/Transforms/Scalar.h" 37#include "llvm/Constant.h" 38#include "llvm/Instructions.h" 39#include "llvm/Function.h" 40#include "llvm/Type.h" 41#include "llvm/Analysis/AliasAnalysis.h" 42#include "llvm/Analysis/Dominators.h" 43#include "llvm/Analysis/LoopInfo.h" 44#include "llvm/Support/CFG.h" 45#include "llvm/Support/Compiler.h" 46#include "llvm/ADT/SetOperations.h" 47#include "llvm/ADT/SetVector.h" 48#include "llvm/ADT/Statistic.h" 49#include "llvm/ADT/DepthFirstIterator.h" 50using namespace llvm; 51 52STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted"); 53STATISTIC(NumNested , "Number of nested loops split out"); 54 55namespace { 56 struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass { 57 static char ID; // Pass identification, replacement for typeid 58 LoopSimplify() : FunctionPass((intptr_t)&ID) {} 59 60 // AA - If we have an alias analysis object to update, this is it, otherwise 61 // this is null. 62 AliasAnalysis *AA; 63 LoopInfo *LI; 64 DominatorTree *DT; 65 virtual bool runOnFunction(Function &F); 66 67 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 68 // We need loop information to identify the loops... 69 AU.addRequired<LoopInfo>(); 70 AU.addRequired<DominatorTree>(); 71 72 AU.addPreserved<LoopInfo>(); 73 AU.addPreserved<DominatorTree>(); 74 AU.addPreserved<DominanceFrontier>(); 75 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added. 76 } 77 78 /// verifyAnalysis() - Verify loop nest. 79 void verifyAnalysis() const { 80#ifndef NDEBUG 81 LoopInfo *NLI = &getAnalysis<LoopInfo>(); 82 for (LoopInfo::iterator I = NLI->begin(), E = NLI->end(); I != E; ++I) 83 (*I)->verifyLoop(); 84#endif 85 } 86 87 private: 88 bool ProcessLoop(Loop *L); 89 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix, 90 const std::vector<BasicBlock*> &Preds); 91 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit); 92 void InsertPreheaderForLoop(Loop *L); 93 Loop *SeparateNestedLoop(Loop *L); 94 void InsertUniqueBackedgeBlock(Loop *L); 95 void PlaceSplitBlockCarefully(BasicBlock *NewBB, 96 std::vector<BasicBlock*> &SplitPreds, 97 Loop *L); 98 }; 99 100 char LoopSimplify::ID = 0; 101 RegisterPass<LoopSimplify> 102 X("loopsimplify", "Canonicalize natural loops", true); 103} 104 105// Publically exposed interface to pass... 106const PassInfo *llvm::LoopSimplifyID = X.getPassInfo(); 107FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); } 108 109/// runOnFunction - Run down all loops in the CFG (recursively, but we could do 110/// it in any convenient order) inserting preheaders... 111/// 112bool LoopSimplify::runOnFunction(Function &F) { 113 bool Changed = false; 114 LI = &getAnalysis<LoopInfo>(); 115 AA = getAnalysisToUpdate<AliasAnalysis>(); 116 DT = &getAnalysis<DominatorTree>(); 117 118 // Check to see that no blocks (other than the header) in loops have 119 // predecessors that are not in loops. This is not valid for natural loops, 120 // but can occur if the blocks are unreachable. Since they are unreachable we 121 // can just shamelessly destroy their terminators to make them not branch into 122 // the loop! 123 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 124 // This case can only occur for unreachable blocks. Blocks that are 125 // unreachable can't be in loops, so filter those blocks out. 126 if (LI->getLoopFor(BB)) continue; 127 128 bool BlockUnreachable = false; 129 TerminatorInst *TI = BB->getTerminator(); 130 131 // Check to see if any successors of this block are non-loop-header loops 132 // that are not the header. 133 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 134 // If this successor is not in a loop, BB is clearly ok. 135 Loop *L = LI->getLoopFor(TI->getSuccessor(i)); 136 if (!L) continue; 137 138 // If the succ is the loop header, and if L is a top-level loop, then this 139 // is an entrance into a loop through the header, which is also ok. 140 if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0) 141 continue; 142 143 // Otherwise, this is an entrance into a loop from some place invalid. 144 // Either the loop structure is invalid and this is not a natural loop (in 145 // which case the compiler is buggy somewhere else) or BB is unreachable. 146 BlockUnreachable = true; 147 break; 148 } 149 150 // If this block is ok, check the next one. 151 if (!BlockUnreachable) continue; 152 153 // Otherwise, this block is dead. To clean up the CFG and to allow later 154 // loop transformations to ignore this case, we delete the edges into the 155 // loop by replacing the terminator. 156 157 // Remove PHI entries from the successors. 158 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 159 TI->getSuccessor(i)->removePredecessor(BB); 160 161 // Add a new unreachable instruction. 162 new UnreachableInst(TI); 163 164 // Delete the dead terminator. 165 if (AA) AA->deleteValue(&BB->back()); 166 BB->getInstList().pop_back(); 167 Changed |= true; 168 } 169 170 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 171 Changed |= ProcessLoop(*I); 172 173 return Changed; 174} 175 176/// ProcessLoop - Walk the loop structure in depth first order, ensuring that 177/// all loops have preheaders. 178/// 179bool LoopSimplify::ProcessLoop(Loop *L) { 180 bool Changed = false; 181ReprocessLoop: 182 183 // Canonicalize inner loops before outer loops. Inner loop canonicalization 184 // can provide work for the outer loop to canonicalize. 185 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 186 Changed |= ProcessLoop(*I); 187 188 assert(L->getBlocks()[0] == L->getHeader() && 189 "Header isn't first block in loop?"); 190 191 // Does the loop already have a preheader? If so, don't insert one. 192 if (L->getLoopPreheader() == 0) { 193 InsertPreheaderForLoop(L); 194 NumInserted++; 195 Changed = true; 196 } 197 198 // Next, check to make sure that all exit nodes of the loop only have 199 // predecessors that are inside of the loop. This check guarantees that the 200 // loop preheader/header will dominate the exit blocks. If the exit block has 201 // predecessors from outside of the loop, split the edge now. 202 SmallVector<BasicBlock*, 8> ExitBlocks; 203 L->getExitBlocks(ExitBlocks); 204 205 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end()); 206 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(), 207 E = ExitBlockSet.end(); I != E; ++I) { 208 BasicBlock *ExitBlock = *I; 209 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock); 210 PI != PE; ++PI) 211 // Must be exactly this loop: no subloops, parent loops, or non-loop preds 212 // allowed. 213 if (!L->contains(*PI)) { 214 RewriteLoopExitBlock(L, ExitBlock); 215 NumInserted++; 216 Changed = true; 217 break; 218 } 219 } 220 221 // If the header has more than two predecessors at this point (from the 222 // preheader and from multiple backedges), we must adjust the loop. 223 unsigned NumBackedges = L->getNumBackEdges(); 224 if (NumBackedges != 1) { 225 // If this is really a nested loop, rip it out into a child loop. Don't do 226 // this for loops with a giant number of backedges, just factor them into a 227 // common backedge instead. 228 if (NumBackedges < 8) { 229 if (Loop *NL = SeparateNestedLoop(L)) { 230 ++NumNested; 231 // This is a big restructuring change, reprocess the whole loop. 232 ProcessLoop(NL); 233 Changed = true; 234 // GCC doesn't tail recursion eliminate this. 235 goto ReprocessLoop; 236 } 237 } 238 239 // If we either couldn't, or didn't want to, identify nesting of the loops, 240 // insert a new block that all backedges target, then make it jump to the 241 // loop header. 242 InsertUniqueBackedgeBlock(L); 243 NumInserted++; 244 Changed = true; 245 } 246 247 // Scan over the PHI nodes in the loop header. Since they now have only two 248 // incoming values (the loop is canonicalized), we may have simplified the PHI 249 // down to 'X = phi [X, Y]', which should be replaced with 'Y'. 250 PHINode *PN; 251 for (BasicBlock::iterator I = L->getHeader()->begin(); 252 (PN = dyn_cast<PHINode>(I++)); ) 253 if (Value *V = PN->hasConstantValue()) { 254 PN->replaceAllUsesWith(V); 255 PN->eraseFromParent(); 256 } 257 258 return Changed; 259} 260 261/// SplitBlockPredecessors - Split the specified block into two blocks. We want 262/// to move the predecessors specified in the Preds list to point to the new 263/// block, leaving the remaining predecessors pointing to BB. This method 264/// updates the SSA PHINode's, but no other analyses. 265/// 266BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB, 267 const char *Suffix, 268 const std::vector<BasicBlock*> &Preds) { 269 270 // Create new basic block, insert right before the original block... 271 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB); 272 273 // The preheader first gets an unconditional branch to the loop header... 274 BranchInst *BI = new BranchInst(BB, NewBB); 275 276 // For every PHI node in the block, insert a PHI node into NewBB where the 277 // incoming values from the out of loop edges are moved to NewBB. We have two 278 // possible cases here. If the loop is dead, we just insert dummy entries 279 // into the PHI nodes for the new edge. If the loop is not dead, we move the 280 // incoming edges in BB into new PHI nodes in NewBB. 281 // 282 if (!Preds.empty()) { // Is the loop not obviously dead? 283 // Check to see if the values being merged into the new block need PHI 284 // nodes. If so, insert them. 285 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) { 286 PHINode *PN = cast<PHINode>(I); 287 ++I; 288 289 // Check to see if all of the values coming in are the same. If so, we 290 // don't need to create a new PHI node. 291 Value *InVal = PN->getIncomingValueForBlock(Preds[0]); 292 for (unsigned i = 1, e = Preds.size(); i != e; ++i) 293 if (InVal != PN->getIncomingValueForBlock(Preds[i])) { 294 InVal = 0; 295 break; 296 } 297 298 // If the values coming into the block are not the same, we need a PHI. 299 if (InVal == 0) { 300 // Create the new PHI node, insert it into NewBB at the end of the block 301 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI); 302 if (AA) AA->copyValue(PN, NewPHI); 303 304 // Move all of the edges from blocks outside the loop to the new PHI 305 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 306 Value *V = PN->removeIncomingValue(Preds[i], false); 307 NewPHI->addIncoming(V, Preds[i]); 308 } 309 InVal = NewPHI; 310 } else { 311 // Remove all of the edges coming into the PHI nodes from outside of the 312 // block. 313 for (unsigned i = 0, e = Preds.size(); i != e; ++i) 314 PN->removeIncomingValue(Preds[i], false); 315 } 316 317 // Add an incoming value to the PHI node in the loop for the preheader 318 // edge. 319 PN->addIncoming(InVal, NewBB); 320 321 // Can we eliminate this phi node now? 322 if (Value *V = PN->hasConstantValue(true)) { 323 Instruction *I = dyn_cast<Instruction>(V); 324 // If I is in NewBB, the Dominator call will fail, because NewBB isn't 325 // registered in DominatorTree yet. Handle this case explicitly. 326 if (!I || (I->getParent() != NewBB && 327 getAnalysis<DominatorTree>().dominates(I, PN))) { 328 PN->replaceAllUsesWith(V); 329 if (AA) AA->deleteValue(PN); 330 BB->getInstList().erase(PN); 331 } 332 } 333 } 334 335 // Now that the PHI nodes are updated, actually move the edges from 336 // Preds to point to NewBB instead of BB. 337 // 338 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 339 TerminatorInst *TI = Preds[i]->getTerminator(); 340 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) 341 if (TI->getSuccessor(s) == BB) 342 TI->setSuccessor(s, NewBB); 343 } 344 345 } else { // Otherwise the loop is dead... 346 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) { 347 PHINode *PN = cast<PHINode>(I); 348 // Insert dummy values as the incoming value... 349 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB); 350 } 351 } 352 353 return NewBB; 354} 355 356/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a 357/// preheader, this method is called to insert one. This method has two phases: 358/// preheader insertion and analysis updating. 359/// 360void LoopSimplify::InsertPreheaderForLoop(Loop *L) { 361 BasicBlock *Header = L->getHeader(); 362 363 // Compute the set of predecessors of the loop that are not in the loop. 364 std::vector<BasicBlock*> OutsideBlocks; 365 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header); 366 PI != PE; ++PI) 367 if (!L->contains(*PI)) // Coming in from outside the loop? 368 OutsideBlocks.push_back(*PI); // Keep track of it... 369 370 // Split out the loop pre-header. 371 BasicBlock *NewBB = 372 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks); 373 374 375 //===--------------------------------------------------------------------===// 376 // Update analysis results now that we have performed the transformation 377 // 378 379 // We know that we have loop information to update... update it now. 380 if (Loop *Parent = L->getParentLoop()) 381 Parent->addBasicBlockToLoop(NewBB, *LI); 382 383 DT->splitBlock(NewBB); 384 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) 385 DF->splitBlock(NewBB); 386 387 // Make sure that NewBB is put someplace intelligent, which doesn't mess up 388 // code layout too horribly. 389 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L); 390} 391 392/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit 393/// blocks. This method is used to split exit blocks that have predecessors 394/// outside of the loop. 395BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) { 396 std::vector<BasicBlock*> LoopBlocks; 397 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) 398 if (L->contains(*I)) 399 LoopBlocks.push_back(*I); 400 401 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?"); 402 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks); 403 404 // Update Loop Information - we know that the new block will be in whichever 405 // loop the Exit block is in. Note that it may not be in that immediate loop, 406 // if the successor is some other loop header. In that case, we continue 407 // walking up the loop tree to find a loop that contains both the successor 408 // block and the predecessor block. 409 Loop *SuccLoop = LI->getLoopFor(Exit); 410 while (SuccLoop && !SuccLoop->contains(L->getHeader())) 411 SuccLoop = SuccLoop->getParentLoop(); 412 if (SuccLoop) 413 SuccLoop->addBasicBlockToLoop(NewBB, *LI); 414 415 // Update Dominator Information 416 DT->splitBlock(NewBB); 417 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) 418 DF->splitBlock(NewBB); 419 420 return NewBB; 421} 422 423/// AddBlockAndPredsToSet - Add the specified block, and all of its 424/// predecessors, to the specified set, if it's not already in there. Stop 425/// predecessor traversal when we reach StopBlock. 426static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock, 427 std::set<BasicBlock*> &Blocks) { 428 std::vector<BasicBlock *> WorkList; 429 WorkList.push_back(InputBB); 430 do { 431 BasicBlock *BB = WorkList.back(); WorkList.pop_back(); 432 if (Blocks.insert(BB).second && BB != StopBlock) 433 // If BB is not already processed and it is not a stop block then 434 // insert its predecessor in the work list 435 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 436 BasicBlock *WBB = *I; 437 WorkList.push_back(WBB); 438 } 439 } while(!WorkList.empty()); 440} 441 442/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a 443/// PHI node that tells us how to partition the loops. 444static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT, 445 AliasAnalysis *AA) { 446 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) { 447 PHINode *PN = cast<PHINode>(I); 448 ++I; 449 if (Value *V = PN->hasConstantValue()) 450 if (!isa<Instruction>(V) || DT->dominates(cast<Instruction>(V), PN)) { 451 // This is a degenerate PHI already, don't modify it! 452 PN->replaceAllUsesWith(V); 453 if (AA) AA->deleteValue(PN); 454 PN->eraseFromParent(); 455 continue; 456 } 457 458 // Scan this PHI node looking for a use of the PHI node by itself. 459 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 460 if (PN->getIncomingValue(i) == PN && 461 L->contains(PN->getIncomingBlock(i))) 462 // We found something tasty to remove. 463 return PN; 464 } 465 return 0; 466} 467 468// PlaceSplitBlockCarefully - If the block isn't already, move the new block to 469// right after some 'outside block' block. This prevents the preheader from 470// being placed inside the loop body, e.g. when the loop hasn't been rotated. 471void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB, 472 std::vector<BasicBlock*>&SplitPreds, 473 Loop *L) { 474 // Check to see if NewBB is already well placed. 475 Function::iterator BBI = NewBB; --BBI; 476 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) { 477 if (&*BBI == SplitPreds[i]) 478 return; 479 } 480 481 // If it isn't already after an outside block, move it after one. This is 482 // always good as it makes the uncond branch from the outside block into a 483 // fall-through. 484 485 // Figure out *which* outside block to put this after. Prefer an outside 486 // block that neighbors a BB actually in the loop. 487 BasicBlock *FoundBB = 0; 488 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) { 489 Function::iterator BBI = SplitPreds[i]; 490 if (++BBI != NewBB->getParent()->end() && 491 L->contains(BBI)) { 492 FoundBB = SplitPreds[i]; 493 break; 494 } 495 } 496 497 // If our heuristic for a *good* bb to place this after doesn't find 498 // anything, just pick something. It's likely better than leaving it within 499 // the loop. 500 if (!FoundBB) 501 FoundBB = SplitPreds[0]; 502 NewBB->moveAfter(FoundBB); 503} 504 505 506/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of 507/// them out into a nested loop. This is important for code that looks like 508/// this: 509/// 510/// Loop: 511/// ... 512/// br cond, Loop, Next 513/// ... 514/// br cond2, Loop, Out 515/// 516/// To identify this common case, we look at the PHI nodes in the header of the 517/// loop. PHI nodes with unchanging values on one backedge correspond to values 518/// that change in the "outer" loop, but not in the "inner" loop. 519/// 520/// If we are able to separate out a loop, return the new outer loop that was 521/// created. 522/// 523Loop *LoopSimplify::SeparateNestedLoop(Loop *L) { 524 PHINode *PN = FindPHIToPartitionLoops(L, DT, AA); 525 if (PN == 0) return 0; // No known way to partition. 526 527 // Pull out all predecessors that have varying values in the loop. This 528 // handles the case when a PHI node has multiple instances of itself as 529 // arguments. 530 std::vector<BasicBlock*> OuterLoopPreds; 531 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 532 if (PN->getIncomingValue(i) != PN || 533 !L->contains(PN->getIncomingBlock(i))) 534 OuterLoopPreds.push_back(PN->getIncomingBlock(i)); 535 536 BasicBlock *Header = L->getHeader(); 537 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds); 538 539 // Update dominator information 540 DT->splitBlock(NewBB); 541 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) 542 DF->splitBlock(NewBB); 543 544 // Make sure that NewBB is put someplace intelligent, which doesn't mess up 545 // code layout too horribly. 546 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L); 547 548 // Create the new outer loop. 549 Loop *NewOuter = new Loop(); 550 551 // Change the parent loop to use the outer loop as its child now. 552 if (Loop *Parent = L->getParentLoop()) 553 Parent->replaceChildLoopWith(L, NewOuter); 554 else 555 LI->changeTopLevelLoop(L, NewOuter); 556 557 // This block is going to be our new header block: add it to this loop and all 558 // parent loops. 559 NewOuter->addBasicBlockToLoop(NewBB, *LI); 560 561 // L is now a subloop of our outer loop. 562 NewOuter->addChildLoop(L); 563 564 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) 565 NewOuter->addBlockEntry(L->getBlocks()[i]); 566 567 // Determine which blocks should stay in L and which should be moved out to 568 // the Outer loop now. 569 std::set<BasicBlock*> BlocksInL; 570 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI) 571 if (DT->dominates(Header, *PI)) 572 AddBlockAndPredsToSet(*PI, Header, BlocksInL); 573 574 575 // Scan all of the loop children of L, moving them to OuterLoop if they are 576 // not part of the inner loop. 577 const std::vector<Loop*> &SubLoops = L->getSubLoops(); 578 for (size_t I = 0; I != SubLoops.size(); ) 579 if (BlocksInL.count(SubLoops[I]->getHeader())) 580 ++I; // Loop remains in L 581 else 582 NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I)); 583 584 // Now that we know which blocks are in L and which need to be moved to 585 // OuterLoop, move any blocks that need it. 586 for (unsigned i = 0; i != L->getBlocks().size(); ++i) { 587 BasicBlock *BB = L->getBlocks()[i]; 588 if (!BlocksInL.count(BB)) { 589 // Move this block to the parent, updating the exit blocks sets 590 L->removeBlockFromLoop(BB); 591 if ((*LI)[BB] == L) 592 LI->changeLoopFor(BB, NewOuter); 593 --i; 594 } 595 } 596 597 return NewOuter; 598} 599 600 601 602/// InsertUniqueBackedgeBlock - This method is called when the specified loop 603/// has more than one backedge in it. If this occurs, revector all of these 604/// backedges to target a new basic block and have that block branch to the loop 605/// header. This ensures that loops have exactly one backedge. 606/// 607void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) { 608 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!"); 609 610 // Get information about the loop 611 BasicBlock *Preheader = L->getLoopPreheader(); 612 BasicBlock *Header = L->getHeader(); 613 Function *F = Header->getParent(); 614 615 // Figure out which basic blocks contain back-edges to the loop header. 616 std::vector<BasicBlock*> BackedgeBlocks; 617 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I) 618 if (*I != Preheader) BackedgeBlocks.push_back(*I); 619 620 // Create and insert the new backedge block... 621 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F); 622 BranchInst *BETerminator = new BranchInst(Header, BEBlock); 623 624 // Move the new backedge block to right after the last backedge block. 625 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos; 626 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock); 627 628 // Now that the block has been inserted into the function, create PHI nodes in 629 // the backedge block which correspond to any PHI nodes in the header block. 630 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 631 PHINode *PN = cast<PHINode>(I); 632 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be", 633 BETerminator); 634 NewPN->reserveOperandSpace(BackedgeBlocks.size()); 635 if (AA) AA->copyValue(PN, NewPN); 636 637 // Loop over the PHI node, moving all entries except the one for the 638 // preheader over to the new PHI node. 639 unsigned PreheaderIdx = ~0U; 640 bool HasUniqueIncomingValue = true; 641 Value *UniqueValue = 0; 642 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 643 BasicBlock *IBB = PN->getIncomingBlock(i); 644 Value *IV = PN->getIncomingValue(i); 645 if (IBB == Preheader) { 646 PreheaderIdx = i; 647 } else { 648 NewPN->addIncoming(IV, IBB); 649 if (HasUniqueIncomingValue) { 650 if (UniqueValue == 0) 651 UniqueValue = IV; 652 else if (UniqueValue != IV) 653 HasUniqueIncomingValue = false; 654 } 655 } 656 } 657 658 // Delete all of the incoming values from the old PN except the preheader's 659 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??"); 660 if (PreheaderIdx != 0) { 661 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx)); 662 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx)); 663 } 664 // Nuke all entries except the zero'th. 665 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i) 666 PN->removeIncomingValue(e-i, false); 667 668 // Finally, add the newly constructed PHI node as the entry for the BEBlock. 669 PN->addIncoming(NewPN, BEBlock); 670 671 // As an optimization, if all incoming values in the new PhiNode (which is a 672 // subset of the incoming values of the old PHI node) have the same value, 673 // eliminate the PHI Node. 674 if (HasUniqueIncomingValue) { 675 NewPN->replaceAllUsesWith(UniqueValue); 676 if (AA) AA->deleteValue(NewPN); 677 BEBlock->getInstList().erase(NewPN); 678 } 679 } 680 681 // Now that all of the PHI nodes have been inserted and adjusted, modify the 682 // backedge blocks to just to the BEBlock instead of the header. 683 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) { 684 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator(); 685 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op) 686 if (TI->getSuccessor(Op) == Header) 687 TI->setSuccessor(Op, BEBlock); 688 } 689 690 //===--- Update all analyses which we must preserve now -----------------===// 691 692 // Update Loop Information - we know that this block is now in the current 693 // loop and all parent loops. 694 L->addBasicBlockToLoop(BEBlock, *LI); 695 696 // Update dominator information 697 DT->splitBlock(BEBlock); 698 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) 699 DF->splitBlock(BEBlock); 700} 701