LLVM API Documentation

LoopSimplify.cpp

Go to the documentation of this file.
00001 //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass performs several transformations to transform natural loops into a
00011 // simpler form, which makes subsequent analyses and transformations simpler and
00012 // more effective.
00013 //
00014 // Loop pre-header insertion guarantees that there is a single, non-critical
00015 // entry edge from outside of the loop to the loop header.  This simplifies a
00016 // number of analyses and transformations, such as LICM.
00017 //
00018 // Loop exit-block insertion guarantees that all exit blocks from the loop
00019 // (blocks which are outside of the loop that have predecessors inside of the
00020 // loop) only have predecessors from inside of the loop (and are thus dominated
00021 // by the loop header).  This simplifies transformations such as store-sinking
00022 // that are built into LICM.
00023 //
00024 // This pass also guarantees that loops will have exactly one backedge.
00025 //
00026 // Note that the simplifycfg pass will clean up blocks which are split out but
00027 // end up being unnecessary, so usage of this pass should not pessimize
00028 // generated code.
00029 //
00030 // This pass obviously modifies the CFG, but updates loop information and
00031 // dominator information.
00032 //
00033 //===----------------------------------------------------------------------===//
00034 
00035 #define DEBUG_TYPE "loopsimplify"
00036 #include "llvm/Transforms/Scalar.h"
00037 #include "llvm/Constants.h"
00038 #include "llvm/Instructions.h"
00039 #include "llvm/Function.h"
00040 #include "llvm/LLVMContext.h"
00041 #include "llvm/Type.h"
00042 #include "llvm/Analysis/AliasAnalysis.h"
00043 #include "llvm/Analysis/Dominators.h"
00044 #include "llvm/Analysis/LoopInfo.h"
00045 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00046 #include "llvm/Transforms/Utils/Local.h"
00047 #include "llvm/Support/CFG.h"
00048 #include "llvm/Support/Compiler.h"
00049 #include "llvm/ADT/SetOperations.h"
00050 #include "llvm/ADT/SetVector.h"
00051 #include "llvm/ADT/Statistic.h"
00052 #include "llvm/ADT/DepthFirstIterator.h"
00053 using namespace llvm;
00054 
00055 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
00056 STATISTIC(NumNested  , "Number of nested loops split out");
00057 
00058 namespace {
00059   struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
00060     static char ID; // Pass identification, replacement for typeid
00061     LoopSimplify() : FunctionPass(&ID) {}
00062 
00063     // AA - If we have an alias analysis object to update, this is it, otherwise
00064     // this is null.
00065     AliasAnalysis *AA;
00066     LoopInfo *LI;
00067     DominatorTree *DT;
00068     virtual bool runOnFunction(Function &F);
00069 
00070     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00071       // We need loop information to identify the loops...
00072       AU.addRequired<LoopInfo>();
00073       AU.addRequired<DominatorTree>();
00074 
00075       AU.addPreserved<LoopInfo>();
00076       AU.addPreserved<DominatorTree>();
00077       AU.addPreserved<DominanceFrontier>();
00078       AU.addPreserved<AliasAnalysis>();
00079       AU.addPreservedID(BreakCriticalEdgesID);  // No critical edges added.
00080     }
00081 
00082     /// verifyAnalysis() - Verify loop nest.
00083     void verifyAnalysis() const {
00084 #ifndef NDEBUG
00085       LoopInfo *NLI = &getAnalysis<LoopInfo>();
00086       for (LoopInfo::iterator I = NLI->begin(), E = NLI->end(); I != E; ++I) 
00087         (*I)->verifyLoop();
00088 #endif  
00089     }
00090 
00091   private:
00092     bool ProcessLoop(Loop *L);
00093     BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
00094     BasicBlock *InsertPreheaderForLoop(Loop *L);
00095     Loop *SeparateNestedLoop(Loop *L);
00096     void InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader);
00097     void PlaceSplitBlockCarefully(BasicBlock *NewBB,
00098                                   SmallVectorImpl<BasicBlock*> &SplitPreds,
00099                                   Loop *L);
00100   };
00101 }
00102 
00103 char LoopSimplify::ID = 0;
00104 static RegisterPass<LoopSimplify>
00105 X("loopsimplify", "Canonicalize natural loops", true);
00106 
00107 // Publically exposed interface to pass...
00108 const PassInfo *const llvm::LoopSimplifyID = &X;
00109 FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
00110 
00111 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
00112 /// it in any convenient order) inserting preheaders...
00113 ///
00114 bool LoopSimplify::runOnFunction(Function &F) {
00115   bool Changed = false;
00116   LI = &getAnalysis<LoopInfo>();
00117   AA = getAnalysisIfAvailable<AliasAnalysis>();
00118   DT = &getAnalysis<DominatorTree>();
00119 
00120   // Check to see that no blocks (other than the header) in loops have
00121   // predecessors that are not in loops.  This is not valid for natural loops,
00122   // but can occur if the blocks are unreachable.  Since they are unreachable we
00123   // can just shamelessly destroy their terminators to make them not branch into
00124   // the loop!
00125   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00126     // This case can only occur for unreachable blocks.  Blocks that are
00127     // unreachable can't be in loops, so filter those blocks out.
00128     if (LI->getLoopFor(BB)) continue;
00129     
00130     bool BlockUnreachable = false;
00131     TerminatorInst *TI = BB->getTerminator();
00132 
00133     // Check to see if any successors of this block are non-loop-header loops
00134     // that are not the header.
00135     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
00136       // If this successor is not in a loop, BB is clearly ok.
00137       Loop *L = LI->getLoopFor(TI->getSuccessor(i));
00138       if (!L) continue;
00139       
00140       // If the succ is the loop header, and if L is a top-level loop, then this
00141       // is an entrance into a loop through the header, which is also ok.
00142       if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
00143         continue;
00144       
00145       // Otherwise, this is an entrance into a loop from some place invalid.
00146       // Either the loop structure is invalid and this is not a natural loop (in
00147       // which case the compiler is buggy somewhere else) or BB is unreachable.
00148       BlockUnreachable = true;
00149       break;
00150     }
00151     
00152     // If this block is ok, check the next one.
00153     if (!BlockUnreachable) continue;
00154     
00155     // Otherwise, this block is dead.  To clean up the CFG and to allow later
00156     // loop transformations to ignore this case, we delete the edges into the
00157     // loop by replacing the terminator.
00158     
00159     // Remove PHI entries from the successors.
00160     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
00161       TI->getSuccessor(i)->removePredecessor(BB);
00162    
00163     // Add a new unreachable instruction before the old terminator.
00164     new UnreachableInst(TI->getContext(), TI);
00165     
00166     // Delete the dead terminator.
00167     if (AA) AA->deleteValue(TI);
00168     if (!TI->use_empty())
00169       TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
00170     TI->eraseFromParent();
00171     Changed |= true;
00172   }
00173   
00174   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
00175     Changed |= ProcessLoop(*I);
00176 
00177   return Changed;
00178 }
00179 
00180 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
00181 /// all loops have preheaders.
00182 ///
00183 bool LoopSimplify::ProcessLoop(Loop *L) {
00184   bool Changed = false;
00185 ReprocessLoop:
00186   
00187   // Canonicalize inner loops before outer loops.  Inner loop canonicalization
00188   // can provide work for the outer loop to canonicalize.
00189   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
00190     Changed |= ProcessLoop(*I);
00191   
00192   assert(L->getBlocks()[0] == L->getHeader() &&
00193          "Header isn't first block in loop?");
00194 
00195   // Does the loop already have a preheader?  If so, don't insert one.
00196   BasicBlock *Preheader = L->getLoopPreheader();
00197   if (!Preheader) {
00198     Preheader = InsertPreheaderForLoop(L);
00199     NumInserted++;
00200     Changed = true;
00201   }
00202 
00203   // Next, check to make sure that all exit nodes of the loop only have
00204   // predecessors that are inside of the loop.  This check guarantees that the
00205   // loop preheader/header will dominate the exit blocks.  If the exit block has
00206   // predecessors from outside of the loop, split the edge now.
00207   SmallVector<BasicBlock*, 8> ExitBlocks;
00208   L->getExitBlocks(ExitBlocks);
00209     
00210   SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
00211   for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
00212          E = ExitBlockSet.end(); I != E; ++I) {
00213     BasicBlock *ExitBlock = *I;
00214     for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
00215          PI != PE; ++PI)
00216       // Must be exactly this loop: no subloops, parent loops, or non-loop preds
00217       // allowed.
00218       if (!L->contains(*PI)) {
00219         RewriteLoopExitBlock(L, ExitBlock);
00220         NumInserted++;
00221         Changed = true;
00222         break;
00223       }
00224   }
00225 
00226   // If the header has more than two predecessors at this point (from the
00227   // preheader and from multiple backedges), we must adjust the loop.
00228   unsigned NumBackedges = L->getNumBackEdges();
00229   if (NumBackedges != 1) {
00230     // If this is really a nested loop, rip it out into a child loop.  Don't do
00231     // this for loops with a giant number of backedges, just factor them into a
00232     // common backedge instead.
00233     if (NumBackedges < 8) {
00234       if (Loop *NL = SeparateNestedLoop(L)) {
00235         ++NumNested;
00236         // This is a big restructuring change, reprocess the whole loop.
00237         ProcessLoop(NL);
00238         Changed = true;
00239         // GCC doesn't tail recursion eliminate this.
00240         goto ReprocessLoop;
00241       }
00242     }
00243 
00244     // If we either couldn't, or didn't want to, identify nesting of the loops,
00245     // insert a new block that all backedges target, then make it jump to the
00246     // loop header.
00247     InsertUniqueBackedgeBlock(L, Preheader);
00248     NumInserted++;
00249     Changed = true;
00250   }
00251 
00252   // Scan over the PHI nodes in the loop header.  Since they now have only two
00253   // incoming values (the loop is canonicalized), we may have simplified the PHI
00254   // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
00255   PHINode *PN;
00256   for (BasicBlock::iterator I = L->getHeader()->begin();
00257        (PN = dyn_cast<PHINode>(I++)); )
00258     if (Value *V = PN->hasConstantValue()) {
00259       if (AA) AA->deleteValue(PN);
00260       PN->replaceAllUsesWith(V);
00261       PN->eraseFromParent();
00262     }
00263 
00264   // If this loop has muliple exits and the exits all go to the same
00265   // block, attempt to merge the exits. This helps several passes, such
00266   // as LoopRotation, which do not support loops with multiple exits.
00267   // SimplifyCFG also does this (and this code uses the same utility
00268   // function), however this code is loop-aware, where SimplifyCFG is
00269   // not. That gives it the advantage of being able to hoist
00270   // loop-invariant instructions out of the way to open up more
00271   // opportunities, and the disadvantage of having the responsibility
00272   // to preserve dominator information.
00273   if (ExitBlocks.size() > 1 && L->getUniqueExitBlock()) {
00274     SmallVector<BasicBlock*, 8> ExitingBlocks;
00275     L->getExitingBlocks(ExitingBlocks);
00276     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
00277       BasicBlock *ExitingBlock = ExitingBlocks[i];
00278       if (!ExitingBlock->getSinglePredecessor()) continue;
00279       BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
00280       if (!BI || !BI->isConditional()) continue;
00281       CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
00282       if (!CI || CI->getParent() != ExitingBlock) continue;
00283 
00284       // Attempt to hoist out all instructions except for the
00285       // comparison and the branch.
00286       bool AllInvariant = true;
00287       for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
00288         Instruction *Inst = I++;
00289         if (Inst == CI)
00290           continue;
00291         if (!L->makeLoopInvariant(Inst, Changed, Preheader->getTerminator())) {
00292           AllInvariant = false;
00293           break;
00294         }
00295       }
00296       if (!AllInvariant) continue;
00297 
00298       // The block has now been cleared of all instructions except for
00299       // a comparison and a conditional branch. SimplifyCFG may be able
00300       // to fold it now.
00301       if (!FoldBranchToCommonDest(BI)) continue;
00302 
00303       // Success. The block is now dead, so remove it from the loop,
00304       // update the dominator tree and dominance frontier, and delete it.
00305       assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock));
00306       Changed = true;
00307       LI->removeBlock(ExitingBlock);
00308 
00309       DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>();
00310       DomTreeNode *Node = DT->getNode(ExitingBlock);
00311       const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
00312         Node->getChildren();
00313       for (unsigned k = 0, g = Children.size(); k != g; ++k) {
00314         DT->changeImmediateDominator(Children[k], Node->getIDom());
00315         if (DF) DF->changeImmediateDominator(Children[k]->getBlock(),
00316                                              Node->getIDom()->getBlock(),
00317                                              DT);
00318       }
00319       DT->eraseNode(ExitingBlock);
00320       if (DF) DF->removeBlock(ExitingBlock);
00321 
00322       BI->getSuccessor(0)->removePredecessor(ExitingBlock);
00323       BI->getSuccessor(1)->removePredecessor(ExitingBlock);
00324       ExitingBlock->eraseFromParent();
00325     }
00326   }
00327 
00328   return Changed;
00329 }
00330 
00331 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
00332 /// preheader, this method is called to insert one.  This method has two phases:
00333 /// preheader insertion and analysis updating.
00334 ///
00335 BasicBlock *LoopSimplify::InsertPreheaderForLoop(Loop *L) {
00336   BasicBlock *Header = L->getHeader();
00337 
00338   // Compute the set of predecessors of the loop that are not in the loop.
00339   SmallVector<BasicBlock*, 8> OutsideBlocks;
00340   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
00341        PI != PE; ++PI)
00342     if (!L->contains(*PI))           // Coming in from outside the loop?
00343       OutsideBlocks.push_back(*PI);  // Keep track of it...
00344 
00345   // Split out the loop pre-header.
00346   BasicBlock *NewBB =
00347     SplitBlockPredecessors(Header, &OutsideBlocks[0], OutsideBlocks.size(),
00348                            ".preheader", this);
00349   
00350 
00351   //===--------------------------------------------------------------------===//
00352   //  Update analysis results now that we have performed the transformation
00353   //
00354 
00355   // We know that we have loop information to update... update it now.
00356   if (Loop *Parent = L->getParentLoop())
00357     Parent->addBasicBlockToLoop(NewBB, LI->getBase());
00358 
00359   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
00360   // code layout too horribly.
00361   PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
00362 
00363   return NewBB;
00364 }
00365 
00366 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
00367 /// blocks.  This method is used to split exit blocks that have predecessors
00368 /// outside of the loop.
00369 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
00370   SmallVector<BasicBlock*, 8> LoopBlocks;
00371   for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
00372     if (L->contains(*I))
00373       LoopBlocks.push_back(*I);
00374 
00375   assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
00376   BasicBlock *NewBB = SplitBlockPredecessors(Exit, &LoopBlocks[0], 
00377                                              LoopBlocks.size(), ".loopexit",
00378                                              this);
00379 
00380   // Update Loop Information - we know that the new block will be in whichever
00381   // loop the Exit block is in.  Note that it may not be in that immediate loop,
00382   // if the successor is some other loop header.  In that case, we continue 
00383   // walking up the loop tree to find a loop that contains both the successor
00384   // block and the predecessor block.
00385   Loop *SuccLoop = LI->getLoopFor(Exit);
00386   while (SuccLoop && !SuccLoop->contains(L->getHeader()))
00387     SuccLoop = SuccLoop->getParentLoop();
00388   if (SuccLoop)
00389     SuccLoop->addBasicBlockToLoop(NewBB, LI->getBase());
00390 
00391   return NewBB;
00392 }
00393 
00394 /// AddBlockAndPredsToSet - Add the specified block, and all of its
00395 /// predecessors, to the specified set, if it's not already in there.  Stop
00396 /// predecessor traversal when we reach StopBlock.
00397 static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
00398                                   std::set<BasicBlock*> &Blocks) {
00399   std::vector<BasicBlock *> WorkList;
00400   WorkList.push_back(InputBB);
00401   do {
00402     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
00403     if (Blocks.insert(BB).second && BB != StopBlock)
00404       // If BB is not already processed and it is not a stop block then
00405       // insert its predecessor in the work list
00406       for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
00407         BasicBlock *WBB = *I;
00408         WorkList.push_back(WBB);
00409       }
00410   } while(!WorkList.empty());
00411 }
00412 
00413 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
00414 /// PHI node that tells us how to partition the loops.
00415 static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT,
00416                                         AliasAnalysis *AA) {
00417   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
00418     PHINode *PN = cast<PHINode>(I);
00419     ++I;
00420     if (Value *V = PN->hasConstantValue())
00421       if (!isa<Instruction>(V) || DT->dominates(cast<Instruction>(V), PN)) {
00422         // This is a degenerate PHI already, don't modify it!
00423         PN->replaceAllUsesWith(V);
00424         if (AA) AA->deleteValue(PN);
00425         PN->eraseFromParent();
00426         continue;
00427       }
00428 
00429     // Scan this PHI node looking for a use of the PHI node by itself.
00430     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00431       if (PN->getIncomingValue(i) == PN &&
00432           L->contains(PN->getIncomingBlock(i)))
00433         // We found something tasty to remove.
00434         return PN;
00435   }
00436   return 0;
00437 }
00438 
00439 // PlaceSplitBlockCarefully - If the block isn't already, move the new block to
00440 // right after some 'outside block' block.  This prevents the preheader from
00441 // being placed inside the loop body, e.g. when the loop hasn't been rotated.
00442 void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
00443                                        SmallVectorImpl<BasicBlock*> &SplitPreds,
00444                                             Loop *L) {
00445   // Check to see if NewBB is already well placed.
00446   Function::iterator BBI = NewBB; --BBI;
00447   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
00448     if (&*BBI == SplitPreds[i])
00449       return;
00450   }
00451   
00452   // If it isn't already after an outside block, move it after one.  This is
00453   // always good as it makes the uncond branch from the outside block into a
00454   // fall-through.
00455   
00456   // Figure out *which* outside block to put this after.  Prefer an outside
00457   // block that neighbors a BB actually in the loop.
00458   BasicBlock *FoundBB = 0;
00459   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
00460     Function::iterator BBI = SplitPreds[i];
00461     if (++BBI != NewBB->getParent()->end() && 
00462         L->contains(BBI)) {
00463       FoundBB = SplitPreds[i];
00464       break;
00465     }
00466   }
00467   
00468   // If our heuristic for a *good* bb to place this after doesn't find
00469   // anything, just pick something.  It's likely better than leaving it within
00470   // the loop.
00471   if (!FoundBB)
00472     FoundBB = SplitPreds[0];
00473   NewBB->moveAfter(FoundBB);
00474 }
00475 
00476 
00477 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
00478 /// them out into a nested loop.  This is important for code that looks like
00479 /// this:
00480 ///
00481 ///  Loop:
00482 ///     ...
00483 ///     br cond, Loop, Next
00484 ///     ...
00485 ///     br cond2, Loop, Out
00486 ///
00487 /// To identify this common case, we look at the PHI nodes in the header of the
00488 /// loop.  PHI nodes with unchanging values on one backedge correspond to values
00489 /// that change in the "outer" loop, but not in the "inner" loop.
00490 ///
00491 /// If we are able to separate out a loop, return the new outer loop that was
00492 /// created.
00493 ///
00494 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
00495   PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
00496   if (PN == 0) return 0;  // No known way to partition.
00497 
00498   // Pull out all predecessors that have varying values in the loop.  This
00499   // handles the case when a PHI node has multiple instances of itself as
00500   // arguments.
00501   SmallVector<BasicBlock*, 8> OuterLoopPreds;
00502   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00503     if (PN->getIncomingValue(i) != PN ||
00504         !L->contains(PN->getIncomingBlock(i)))
00505       OuterLoopPreds.push_back(PN->getIncomingBlock(i));
00506 
00507   BasicBlock *Header = L->getHeader();
00508   BasicBlock *NewBB = SplitBlockPredecessors(Header, &OuterLoopPreds[0],
00509                                              OuterLoopPreds.size(),
00510                                              ".outer", this);
00511 
00512   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
00513   // code layout too horribly.
00514   PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
00515   
00516   // Create the new outer loop.
00517   Loop *NewOuter = new Loop();
00518 
00519   // Change the parent loop to use the outer loop as its child now.
00520   if (Loop *Parent = L->getParentLoop())
00521     Parent->replaceChildLoopWith(L, NewOuter);
00522   else
00523     LI->changeTopLevelLoop(L, NewOuter);
00524 
00525   // This block is going to be our new header block: add it to this loop and all
00526   // parent loops.
00527   NewOuter->addBasicBlockToLoop(NewBB, LI->getBase());
00528 
00529   // L is now a subloop of our outer loop.
00530   NewOuter->addChildLoop(L);
00531 
00532   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00533        I != E; ++I)
00534     NewOuter->addBlockEntry(*I);
00535 
00536   // Determine which blocks should stay in L and which should be moved out to
00537   // the Outer loop now.
00538   std::set<BasicBlock*> BlocksInL;
00539   for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
00540     if (DT->dominates(Header, *PI))
00541       AddBlockAndPredsToSet(*PI, Header, BlocksInL);
00542 
00543 
00544   // Scan all of the loop children of L, moving them to OuterLoop if they are
00545   // not part of the inner loop.
00546   const std::vector<Loop*> &SubLoops = L->getSubLoops();
00547   for (size_t I = 0; I != SubLoops.size(); )
00548     if (BlocksInL.count(SubLoops[I]->getHeader()))
00549       ++I;   // Loop remains in L
00550     else
00551       NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
00552 
00553   // Now that we know which blocks are in L and which need to be moved to
00554   // OuterLoop, move any blocks that need it.
00555   for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
00556     BasicBlock *BB = L->getBlocks()[i];
00557     if (!BlocksInL.count(BB)) {
00558       // Move this block to the parent, updating the exit blocks sets
00559       L->removeBlockFromLoop(BB);
00560       if ((*LI)[BB] == L)
00561         LI->changeLoopFor(BB, NewOuter);
00562       --i;
00563     }
00564   }
00565 
00566   return NewOuter;
00567 }
00568 
00569 
00570 
00571 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
00572 /// has more than one backedge in it.  If this occurs, revector all of these
00573 /// backedges to target a new basic block and have that block branch to the loop
00574 /// header.  This ensures that loops have exactly one backedge.
00575 ///
00576 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader) {
00577   assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
00578 
00579   // Get information about the loop
00580   BasicBlock *Header = L->getHeader();
00581   Function *F = Header->getParent();
00582 
00583   // Figure out which basic blocks contain back-edges to the loop header.
00584   std::vector<BasicBlock*> BackedgeBlocks;
00585   for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
00586     if (*I != Preheader) BackedgeBlocks.push_back(*I);
00587 
00588   // Create and insert the new backedge block...
00589   BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
00590                                            Header->getName()+".backedge", F);
00591   BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
00592 
00593   // Move the new backedge block to right after the last backedge block.
00594   Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
00595   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
00596 
00597   // Now that the block has been inserted into the function, create PHI nodes in
00598   // the backedge block which correspond to any PHI nodes in the header block.
00599   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00600     PHINode *PN = cast<PHINode>(I);
00601     PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".be",
00602                                      BETerminator);
00603     NewPN->reserveOperandSpace(BackedgeBlocks.size());
00604     if (AA) AA->copyValue(PN, NewPN);
00605 
00606     // Loop over the PHI node, moving all entries except the one for the
00607     // preheader over to the new PHI node.
00608     unsigned PreheaderIdx = ~0U;
00609     bool HasUniqueIncomingValue = true;
00610     Value *UniqueValue = 0;
00611     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00612       BasicBlock *IBB = PN->getIncomingBlock(i);
00613       Value *IV = PN->getIncomingValue(i);
00614       if (IBB == Preheader) {
00615         PreheaderIdx = i;
00616       } else {
00617         NewPN->addIncoming(IV, IBB);
00618         if (HasUniqueIncomingValue) {
00619           if (UniqueValue == 0)
00620             UniqueValue = IV;
00621           else if (UniqueValue != IV)
00622             HasUniqueIncomingValue = false;
00623         }
00624       }
00625     }
00626 
00627     // Delete all of the incoming values from the old PN except the preheader's
00628     assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
00629     if (PreheaderIdx != 0) {
00630       PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
00631       PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
00632     }
00633     // Nuke all entries except the zero'th.
00634     for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
00635       PN->removeIncomingValue(e-i, false);
00636 
00637     // Finally, add the newly constructed PHI node as the entry for the BEBlock.
00638     PN->addIncoming(NewPN, BEBlock);
00639 
00640     // As an optimization, if all incoming values in the new PhiNode (which is a
00641     // subset of the incoming values of the old PHI node) have the same value,
00642     // eliminate the PHI Node.
00643     if (HasUniqueIncomingValue) {
00644       NewPN->replaceAllUsesWith(UniqueValue);
00645       if (AA) AA->deleteValue(NewPN);
00646       BEBlock->getInstList().erase(NewPN);
00647     }
00648   }
00649 
00650   // Now that all of the PHI nodes have been inserted and adjusted, modify the
00651   // backedge blocks to just to the BEBlock instead of the header.
00652   for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
00653     TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
00654     for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
00655       if (TI->getSuccessor(Op) == Header)
00656         TI->setSuccessor(Op, BEBlock);
00657   }
00658 
00659   //===--- Update all analyses which we must preserve now -----------------===//
00660 
00661   // Update Loop Information - we know that this block is now in the current
00662   // loop and all parent loops.
00663   L->addBasicBlockToLoop(BEBlock, LI->getBase());
00664 
00665   // Update dominator information
00666   DT->splitBlock(BEBlock);
00667   if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>())
00668     DF->splitBlock(BEBlock);
00669 }