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