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



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.