LLVM API Documentation

LoopRotation.cpp
Go to the documentation of this file.
00001 //===- LoopRotation.cpp - Loop Rotation 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 file implements Loop Rotation Pass.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "loop-rotate"
00015 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/ADT/Statistic.h"
00017 #include "llvm/Analysis/CodeMetrics.h"
00018 #include "llvm/Analysis/InstructionSimplify.h"
00019 #include "llvm/Analysis/LoopPass.h"
00020 #include "llvm/Analysis/ScalarEvolution.h"
00021 #include "llvm/Analysis/TargetTransformInfo.h"
00022 #include "llvm/Analysis/ValueTracking.h"
00023 #include "llvm/IR/CFG.h"
00024 #include "llvm/IR/Dominators.h"
00025 #include "llvm/IR/Function.h"
00026 #include "llvm/IR/IntrinsicInst.h"
00027 #include "llvm/Support/Debug.h"
00028 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00029 #include "llvm/Transforms/Utils/Local.h"
00030 #include "llvm/Transforms/Utils/SSAUpdater.h"
00031 #include "llvm/Transforms/Utils/ValueMapper.h"
00032 using namespace llvm;
00033 
00034 #define MAX_HEADER_SIZE 16
00035 
00036 STATISTIC(NumRotated, "Number of loops rotated");
00037 namespace {
00038 
00039   class LoopRotate : public LoopPass {
00040   public:
00041     static char ID; // Pass ID, replacement for typeid
00042     LoopRotate() : LoopPass(ID) {
00043       initializeLoopRotatePass(*PassRegistry::getPassRegistry());
00044     }
00045 
00046     // LCSSA form makes instruction renaming easier.
00047     void getAnalysisUsage(AnalysisUsage &AU) const override {
00048       AU.addPreserved<DominatorTreeWrapperPass>();
00049       AU.addRequired<LoopInfo>();
00050       AU.addPreserved<LoopInfo>();
00051       AU.addRequiredID(LoopSimplifyID);
00052       AU.addPreservedID(LoopSimplifyID);
00053       AU.addRequiredID(LCSSAID);
00054       AU.addPreservedID(LCSSAID);
00055       AU.addPreserved<ScalarEvolution>();
00056       AU.addRequired<TargetTransformInfo>();
00057     }
00058 
00059     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
00060     bool simplifyLoopLatch(Loop *L);
00061     bool rotateLoop(Loop *L, bool SimplifiedLatch);
00062 
00063   private:
00064     LoopInfo *LI;
00065     const TargetTransformInfo *TTI;
00066   };
00067 }
00068 
00069 char LoopRotate::ID = 0;
00070 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
00071 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
00072 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
00073 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
00074 INITIALIZE_PASS_DEPENDENCY(LCSSA)
00075 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
00076 
00077 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
00078 
00079 /// Rotate Loop L as many times as possible. Return true if
00080 /// the loop is rotated at least once.
00081 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
00082   if (skipOptnoneFunction(L))
00083     return false;
00084 
00085   // Save the loop metadata.
00086   MDNode *LoopMD = L->getLoopID();
00087 
00088   LI = &getAnalysis<LoopInfo>();
00089   TTI = &getAnalysis<TargetTransformInfo>();
00090 
00091   // Simplify the loop latch before attempting to rotate the header
00092   // upward. Rotation may not be needed if the loop tail can be folded into the
00093   // loop exit.
00094   bool SimplifiedLatch = simplifyLoopLatch(L);
00095 
00096   // One loop can be rotated multiple times.
00097   bool MadeChange = false;
00098   while (rotateLoop(L, SimplifiedLatch)) {
00099     MadeChange = true;
00100     SimplifiedLatch = false;
00101   }
00102 
00103   // Restore the loop metadata.
00104   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
00105   if ((MadeChange || SimplifiedLatch) && LoopMD)
00106     L->setLoopID(LoopMD);
00107 
00108   return MadeChange;
00109 }
00110 
00111 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
00112 /// old header into the preheader.  If there were uses of the values produced by
00113 /// these instruction that were outside of the loop, we have to insert PHI nodes
00114 /// to merge the two values.  Do this now.
00115 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
00116                                             BasicBlock *OrigPreheader,
00117                                             ValueToValueMapTy &ValueMap) {
00118   // Remove PHI node entries that are no longer live.
00119   BasicBlock::iterator I, E = OrigHeader->end();
00120   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
00121     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
00122 
00123   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
00124   // as necessary.
00125   SSAUpdater SSA;
00126   for (I = OrigHeader->begin(); I != E; ++I) {
00127     Value *OrigHeaderVal = I;
00128 
00129     // If there are no uses of the value (e.g. because it returns void), there
00130     // is nothing to rewrite.
00131     if (OrigHeaderVal->use_empty())
00132       continue;
00133 
00134     Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
00135 
00136     // The value now exits in two versions: the initial value in the preheader
00137     // and the loop "next" value in the original header.
00138     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
00139     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
00140     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
00141 
00142     // Visit each use of the OrigHeader instruction.
00143     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
00144          UE = OrigHeaderVal->use_end(); UI != UE; ) {
00145       // Grab the use before incrementing the iterator.
00146       Use &U = *UI;
00147 
00148       // Increment the iterator before removing the use from the list.
00149       ++UI;
00150 
00151       // SSAUpdater can't handle a non-PHI use in the same block as an
00152       // earlier def. We can easily handle those cases manually.
00153       Instruction *UserInst = cast<Instruction>(U.getUser());
00154       if (!isa<PHINode>(UserInst)) {
00155         BasicBlock *UserBB = UserInst->getParent();
00156 
00157         // The original users in the OrigHeader are already using the
00158         // original definitions.
00159         if (UserBB == OrigHeader)
00160           continue;
00161 
00162         // Users in the OrigPreHeader need to use the value to which the
00163         // original definitions are mapped.
00164         if (UserBB == OrigPreheader) {
00165           U = OrigPreHeaderVal;
00166           continue;
00167         }
00168       }
00169 
00170       // Anything else can be handled by SSAUpdater.
00171       SSA.RewriteUse(U);
00172     }
00173   }
00174 }
00175 
00176 /// Determine whether the instructions in this range my be safely and cheaply
00177 /// speculated. This is not an important enough situation to develop complex
00178 /// heuristics. We handle a single arithmetic instruction along with any type
00179 /// conversions.
00180 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
00181                                   BasicBlock::iterator End) {
00182   bool seenIncrement = false;
00183   for (BasicBlock::iterator I = Begin; I != End; ++I) {
00184 
00185     if (!isSafeToSpeculativelyExecute(I))
00186       return false;
00187 
00188     if (isa<DbgInfoIntrinsic>(I))
00189       continue;
00190 
00191     switch (I->getOpcode()) {
00192     default:
00193       return false;
00194     case Instruction::GetElementPtr:
00195       // GEPs are cheap if all indices are constant.
00196       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
00197         return false;
00198       // fall-thru to increment case
00199     case Instruction::Add:
00200     case Instruction::Sub:
00201     case Instruction::And:
00202     case Instruction::Or:
00203     case Instruction::Xor:
00204     case Instruction::Shl:
00205     case Instruction::LShr:
00206     case Instruction::AShr:
00207       if (seenIncrement)
00208         return false;
00209       seenIncrement = true;
00210       break;
00211     case Instruction::Trunc:
00212     case Instruction::ZExt:
00213     case Instruction::SExt:
00214       // ignore type conversions
00215       break;
00216     }
00217   }
00218   return true;
00219 }
00220 
00221 /// Fold the loop tail into the loop exit by speculating the loop tail
00222 /// instructions. Typically, this is a single post-increment. In the case of a
00223 /// simple 2-block loop, hoisting the increment can be much better than
00224 /// duplicating the entire loop header. In the cast of loops with early exits,
00225 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
00226 /// canonical form so downstream passes can handle it.
00227 ///
00228 /// I don't believe this invalidates SCEV.
00229 bool LoopRotate::simplifyLoopLatch(Loop *L) {
00230   BasicBlock *Latch = L->getLoopLatch();
00231   if (!Latch || Latch->hasAddressTaken())
00232     return false;
00233 
00234   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
00235   if (!Jmp || !Jmp->isUnconditional())
00236     return false;
00237 
00238   BasicBlock *LastExit = Latch->getSinglePredecessor();
00239   if (!LastExit || !L->isLoopExiting(LastExit))
00240     return false;
00241 
00242   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
00243   if (!BI)
00244     return false;
00245 
00246   if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
00247     return false;
00248 
00249   DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
00250         << LastExit->getName() << "\n");
00251 
00252   // Hoist the instructions from Latch into LastExit.
00253   LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
00254 
00255   unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
00256   BasicBlock *Header = Jmp->getSuccessor(0);
00257   assert(Header == L->getHeader() && "expected a backward branch");
00258 
00259   // Remove Latch from the CFG so that LastExit becomes the new Latch.
00260   BI->setSuccessor(FallThruPath, Header);
00261   Latch->replaceSuccessorsPhiUsesWith(LastExit);
00262   Jmp->eraseFromParent();
00263 
00264   // Nuke the Latch block.
00265   assert(Latch->empty() && "unable to evacuate Latch");
00266   LI->removeBlock(Latch);
00267   if (DominatorTreeWrapperPass *DTWP =
00268           getAnalysisIfAvailable<DominatorTreeWrapperPass>())
00269     DTWP->getDomTree().eraseNode(Latch);
00270   Latch->eraseFromParent();
00271   return true;
00272 }
00273 
00274 /// Rotate loop LP. Return true if the loop is rotated.
00275 ///
00276 /// \param SimplifiedLatch is true if the latch was just folded into the final
00277 /// loop exit. In this case we may want to rotate even though the new latch is
00278 /// now an exiting branch. This rotation would have happened had the latch not
00279 /// been simplified. However, if SimplifiedLatch is false, then we avoid
00280 /// rotating loops in which the latch exits to avoid excessive or endless
00281 /// rotation. LoopRotate should be repeatable and converge to a canonical
00282 /// form. This property is satisfied because simplifying the loop latch can only
00283 /// happen once across multiple invocations of the LoopRotate pass.
00284 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
00285   // If the loop has only one block then there is not much to rotate.
00286   if (L->getBlocks().size() == 1)
00287     return false;
00288 
00289   BasicBlock *OrigHeader = L->getHeader();
00290   BasicBlock *OrigLatch = L->getLoopLatch();
00291 
00292   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
00293   if (BI == 0 || BI->isUnconditional())
00294     return false;
00295 
00296   // If the loop header is not one of the loop exiting blocks then
00297   // either this loop is already rotated or it is not
00298   // suitable for loop rotation transformations.
00299   if (!L->isLoopExiting(OrigHeader))
00300     return false;
00301 
00302   // If the loop latch already contains a branch that leaves the loop then the
00303   // loop is already rotated.
00304   if (OrigLatch == 0)
00305     return false;
00306 
00307   // Rotate if either the loop latch does *not* exit the loop, or if the loop
00308   // latch was just simplified.
00309   if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
00310     return false;
00311 
00312   // Check size of original header and reject loop if it is very big or we can't
00313   // duplicate blocks inside it.
00314   {
00315     CodeMetrics Metrics;
00316     Metrics.analyzeBasicBlock(OrigHeader, *TTI);
00317     if (Metrics.notDuplicatable) {
00318       DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
00319             << " instructions: "; L->dump());
00320       return false;
00321     }
00322     if (Metrics.NumInsts > MAX_HEADER_SIZE)
00323       return false;
00324   }
00325 
00326   // Now, this loop is suitable for rotation.
00327   BasicBlock *OrigPreheader = L->getLoopPreheader();
00328 
00329   // If the loop could not be converted to canonical form, it must have an
00330   // indirectbr in it, just give up.
00331   if (OrigPreheader == 0)
00332     return false;
00333 
00334   // Anything ScalarEvolution may know about this loop or the PHI nodes
00335   // in its header will soon be invalidated.
00336   if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
00337     SE->forgetLoop(L);
00338 
00339   DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
00340 
00341   // Find new Loop header. NewHeader is a Header's one and only successor
00342   // that is inside loop.  Header's other successor is outside the
00343   // loop.  Otherwise loop is not suitable for rotation.
00344   BasicBlock *Exit = BI->getSuccessor(0);
00345   BasicBlock *NewHeader = BI->getSuccessor(1);
00346   if (L->contains(Exit))
00347     std::swap(Exit, NewHeader);
00348   assert(NewHeader && "Unable to determine new loop header");
00349   assert(L->contains(NewHeader) && !L->contains(Exit) &&
00350          "Unable to determine loop header and exit blocks");
00351 
00352   // This code assumes that the new header has exactly one predecessor.
00353   // Remove any single-entry PHI nodes in it.
00354   assert(NewHeader->getSinglePredecessor() &&
00355          "New header doesn't have one pred!");
00356   FoldSingleEntryPHINodes(NewHeader);
00357 
00358   // Begin by walking OrigHeader and populating ValueMap with an entry for
00359   // each Instruction.
00360   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
00361   ValueToValueMapTy ValueMap;
00362 
00363   // For PHI nodes, the value available in OldPreHeader is just the
00364   // incoming value from OldPreHeader.
00365   for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
00366     ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
00367 
00368   // For the rest of the instructions, either hoist to the OrigPreheader if
00369   // possible or create a clone in the OldPreHeader if not.
00370   TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
00371   while (I != E) {
00372     Instruction *Inst = I++;
00373 
00374     // If the instruction's operands are invariant and it doesn't read or write
00375     // memory, then it is safe to hoist.  Doing this doesn't change the order of
00376     // execution in the preheader, but does prevent the instruction from
00377     // executing in each iteration of the loop.  This means it is safe to hoist
00378     // something that might trap, but isn't safe to hoist something that reads
00379     // memory (without proving that the loop doesn't write).
00380     if (L->hasLoopInvariantOperands(Inst) &&
00381         !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
00382         !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
00383         !isa<AllocaInst>(Inst)) {
00384       Inst->moveBefore(LoopEntryBranch);
00385       continue;
00386     }
00387 
00388     // Otherwise, create a duplicate of the instruction.
00389     Instruction *C = Inst->clone();
00390 
00391     // Eagerly remap the operands of the instruction.
00392     RemapInstruction(C, ValueMap,
00393                      RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
00394 
00395     // With the operands remapped, see if the instruction constant folds or is
00396     // otherwise simplifyable.  This commonly occurs because the entry from PHI
00397     // nodes allows icmps and other instructions to fold.
00398     Value *V = SimplifyInstruction(C);
00399     if (V && LI->replacementPreservesLCSSAForm(C, V)) {
00400       // If so, then delete the temporary instruction and stick the folded value
00401       // in the map.
00402       delete C;
00403       ValueMap[Inst] = V;
00404     } else {
00405       // Otherwise, stick the new instruction into the new block!
00406       C->setName(Inst->getName());
00407       C->insertBefore(LoopEntryBranch);
00408       ValueMap[Inst] = C;
00409     }
00410   }
00411 
00412   // Along with all the other instructions, we just cloned OrigHeader's
00413   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
00414   // successors by duplicating their incoming values for OrigHeader.
00415   TerminatorInst *TI = OrigHeader->getTerminator();
00416   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
00417     for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
00418          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
00419       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
00420 
00421   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
00422   // OrigPreHeader's old terminator (the original branch into the loop), and
00423   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
00424   LoopEntryBranch->eraseFromParent();
00425 
00426   // If there were any uses of instructions in the duplicated block outside the
00427   // loop, update them, inserting PHI nodes as required
00428   RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
00429 
00430   // NewHeader is now the header of the loop.
00431   L->moveToHeader(NewHeader);
00432   assert(L->getHeader() == NewHeader && "Latch block is our new header");
00433 
00434 
00435   // At this point, we've finished our major CFG changes.  As part of cloning
00436   // the loop into the preheader we've simplified instructions and the
00437   // duplicated conditional branch may now be branching on a constant.  If it is
00438   // branching on a constant and if that constant means that we enter the loop,
00439   // then we fold away the cond branch to an uncond branch.  This simplifies the
00440   // loop in cases important for nested loops, and it also means we don't have
00441   // to split as many edges.
00442   BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
00443   assert(PHBI->isConditional() && "Should be clone of BI condbr!");
00444   if (!isa<ConstantInt>(PHBI->getCondition()) ||
00445       PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
00446           != NewHeader) {
00447     // The conditional branch can't be folded, handle the general case.
00448     // Update DominatorTree to reflect the CFG change we just made.  Then split
00449     // edges as necessary to preserve LoopSimplify form.
00450     if (DominatorTreeWrapperPass *DTWP =
00451             getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
00452       DominatorTree &DT = DTWP->getDomTree();
00453       // Everything that was dominated by the old loop header is now dominated
00454       // by the original loop preheader. Conceptually the header was merged
00455       // into the preheader, even though we reuse the actual block as a new
00456       // loop latch.
00457       DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
00458       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
00459                                                    OrigHeaderNode->end());
00460       DomTreeNode *OrigPreheaderNode = DT.getNode(OrigPreheader);
00461       for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
00462         DT.changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
00463 
00464       assert(DT.getNode(Exit)->getIDom() == OrigPreheaderNode);
00465       assert(DT.getNode(NewHeader)->getIDom() == OrigPreheaderNode);
00466 
00467       // Update OrigHeader to be dominated by the new header block.
00468       DT.changeImmediateDominator(OrigHeader, OrigLatch);
00469     }
00470 
00471     // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
00472     // thus is not a preheader anymore.
00473     // Split the edge to form a real preheader.
00474     BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
00475     NewPH->setName(NewHeader->getName() + ".lr.ph");
00476 
00477     // Preserve canonical loop form, which means that 'Exit' should have only
00478     // one predecessor. Note that Exit could be an exit block for multiple
00479     // nested loops, causing both of the edges to now be critical and need to
00480     // be split.
00481     SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
00482     bool SplitLatchEdge = false;
00483     for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
00484                                                  PE = ExitPreds.end();
00485          PI != PE; ++PI) {
00486       // We only need to split loop exit edges.
00487       Loop *PredLoop = LI->getLoopFor(*PI);
00488       if (!PredLoop || PredLoop->contains(Exit))
00489         continue;
00490       SplitLatchEdge |= L->getLoopLatch() == *PI;
00491       BasicBlock *ExitSplit = SplitCriticalEdge(*PI, Exit, this);
00492       ExitSplit->moveBefore(Exit);
00493     }
00494     assert(SplitLatchEdge &&
00495            "Despite splitting all preds, failed to split latch exit?");
00496   } else {
00497     // We can fold the conditional branch in the preheader, this makes things
00498     // simpler. The first step is to remove the extra edge to the Exit block.
00499     Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
00500     BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
00501     NewBI->setDebugLoc(PHBI->getDebugLoc());
00502     PHBI->eraseFromParent();
00503 
00504     // With our CFG finalized, update DomTree if it is available.
00505     if (DominatorTreeWrapperPass *DTWP =
00506             getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
00507       DominatorTree &DT = DTWP->getDomTree();
00508       // Update OrigHeader to be dominated by the new header block.
00509       DT.changeImmediateDominator(NewHeader, OrigPreheader);
00510       DT.changeImmediateDominator(OrigHeader, OrigLatch);
00511 
00512       // Brute force incremental dominator tree update. Call
00513       // findNearestCommonDominator on all CFG predecessors of each child of the
00514       // original header.
00515       DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
00516       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
00517                                                    OrigHeaderNode->end());
00518       bool Changed;
00519       do {
00520         Changed = false;
00521         for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
00522           DomTreeNode *Node = HeaderChildren[I];
00523           BasicBlock *BB = Node->getBlock();
00524 
00525           pred_iterator PI = pred_begin(BB);
00526           BasicBlock *NearestDom = *PI;
00527           for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
00528             NearestDom = DT.findNearestCommonDominator(NearestDom, *PI);
00529 
00530           // Remember if this changes the DomTree.
00531           if (Node->getIDom()->getBlock() != NearestDom) {
00532             DT.changeImmediateDominator(BB, NearestDom);
00533             Changed = true;
00534           }
00535         }
00536 
00537       // If the dominator changed, this may have an effect on other
00538       // predecessors, continue until we reach a fixpoint.
00539       } while (Changed);
00540     }
00541   }
00542 
00543   assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
00544   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
00545 
00546   // Now that the CFG and DomTree are in a consistent state again, try to merge
00547   // the OrigHeader block into OrigLatch.  This will succeed if they are
00548   // connected by an unconditional branch.  This is just a cleanup so the
00549   // emitted code isn't too gross in this common case.
00550   MergeBlockIntoPredecessor(OrigHeader, this);
00551 
00552   DEBUG(dbgs() << "LoopRotation: into "; L->dump());
00553 
00554   ++NumRotated;
00555   return true;
00556 }