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