[PM] Port ScalarEvolution to the new pass manager.
[oota-llvm.git] / lib / Transforms / Scalar / LoopRotation.cpp
1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Loop Rotation Pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/CodeMetrics.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Transforms/Utils/SSAUpdater.h"
35 #include "llvm/Transforms/Utils/ValueMapper.h"
36 using namespace llvm;
37
38 #define DEBUG_TYPE "loop-rotate"
39
40 static cl::opt<unsigned>
41 DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
42        cl::desc("The default maximum header size for automatic loop rotation"));
43
44 STATISTIC(NumRotated, "Number of loops rotated");
45 namespace {
46
47   class LoopRotate : public LoopPass {
48   public:
49     static char ID; // Pass ID, replacement for typeid
50     LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
51       initializeLoopRotatePass(*PassRegistry::getPassRegistry());
52       if (SpecifiedMaxHeaderSize == -1)
53         MaxHeaderSize = DefaultRotationThreshold;
54       else
55         MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
56     }
57
58     // LCSSA form makes instruction renaming easier.
59     void getAnalysisUsage(AnalysisUsage &AU) const override {
60       AU.addPreserved<AliasAnalysis>();
61       AU.addRequired<AssumptionCacheTracker>();
62       AU.addPreserved<DominatorTreeWrapperPass>();
63       AU.addRequired<LoopInfoWrapperPass>();
64       AU.addPreserved<LoopInfoWrapperPass>();
65       AU.addRequiredID(LoopSimplifyID);
66       AU.addPreservedID(LoopSimplifyID);
67       AU.addRequiredID(LCSSAID);
68       AU.addPreservedID(LCSSAID);
69       AU.addPreserved<ScalarEvolutionWrapperPass>();
70       AU.addRequired<TargetTransformInfoWrapperPass>();
71     }
72
73     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
74     bool simplifyLoopLatch(Loop *L);
75     bool rotateLoop(Loop *L, bool SimplifiedLatch);
76
77   private:
78     unsigned MaxHeaderSize;
79     LoopInfo *LI;
80     const TargetTransformInfo *TTI;
81     AssumptionCache *AC;
82     DominatorTree *DT;
83   };
84 }
85
86 char LoopRotate::ID = 0;
87 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
88 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
89 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
90 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
91 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
92 INITIALIZE_PASS_DEPENDENCY(LCSSA)
93 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
94
95 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
96   return new LoopRotate(MaxHeaderSize);
97 }
98
99 /// Rotate Loop L as many times as possible. Return true if
100 /// the loop is rotated at least once.
101 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
102   if (skipOptnoneFunction(L))
103     return false;
104
105   // Save the loop metadata.
106   MDNode *LoopMD = L->getLoopID();
107
108   Function &F = *L->getHeader()->getParent();
109
110   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
111   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
112   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
113   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
114   DT = DTWP ? &DTWP->getDomTree() : nullptr;
115
116   // Simplify the loop latch before attempting to rotate the header
117   // upward. Rotation may not be needed if the loop tail can be folded into the
118   // loop exit.
119   bool SimplifiedLatch = simplifyLoopLatch(L);
120
121   // One loop can be rotated multiple times.
122   bool MadeChange = false;
123   while (rotateLoop(L, SimplifiedLatch)) {
124     MadeChange = true;
125     SimplifiedLatch = false;
126   }
127
128   // Restore the loop metadata.
129   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
130   if ((MadeChange || SimplifiedLatch) && LoopMD)
131     L->setLoopID(LoopMD);
132
133   return MadeChange;
134 }
135
136 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
137 /// old header into the preheader.  If there were uses of the values produced by
138 /// these instruction that were outside of the loop, we have to insert PHI nodes
139 /// to merge the two values.  Do this now.
140 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
141                                             BasicBlock *OrigPreheader,
142                                             ValueToValueMapTy &ValueMap) {
143   // Remove PHI node entries that are no longer live.
144   BasicBlock::iterator I, E = OrigHeader->end();
145   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
146     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
147
148   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
149   // as necessary.
150   SSAUpdater SSA;
151   for (I = OrigHeader->begin(); I != E; ++I) {
152     Value *OrigHeaderVal = I;
153
154     // If there are no uses of the value (e.g. because it returns void), there
155     // is nothing to rewrite.
156     if (OrigHeaderVal->use_empty())
157       continue;
158
159     Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
160
161     // The value now exits in two versions: the initial value in the preheader
162     // and the loop "next" value in the original header.
163     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
164     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
165     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
166
167     // Visit each use of the OrigHeader instruction.
168     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
169          UE = OrigHeaderVal->use_end(); UI != UE; ) {
170       // Grab the use before incrementing the iterator.
171       Use &U = *UI;
172
173       // Increment the iterator before removing the use from the list.
174       ++UI;
175
176       // SSAUpdater can't handle a non-PHI use in the same block as an
177       // earlier def. We can easily handle those cases manually.
178       Instruction *UserInst = cast<Instruction>(U.getUser());
179       if (!isa<PHINode>(UserInst)) {
180         BasicBlock *UserBB = UserInst->getParent();
181
182         // The original users in the OrigHeader are already using the
183         // original definitions.
184         if (UserBB == OrigHeader)
185           continue;
186
187         // Users in the OrigPreHeader need to use the value to which the
188         // original definitions are mapped.
189         if (UserBB == OrigPreheader) {
190           U = OrigPreHeaderVal;
191           continue;
192         }
193       }
194
195       // Anything else can be handled by SSAUpdater.
196       SSA.RewriteUse(U);
197     }
198   }
199 }
200
201 /// Determine whether the instructions in this range may be safely and cheaply
202 /// speculated. This is not an important enough situation to develop complex
203 /// heuristics. We handle a single arithmetic instruction along with any type
204 /// conversions.
205 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
206                                   BasicBlock::iterator End, Loop *L) {
207   bool seenIncrement = false;
208   bool MultiExitLoop = false;
209
210   if (!L->getExitingBlock())
211     MultiExitLoop = true;
212
213   for (BasicBlock::iterator I = Begin; I != End; ++I) {
214
215     if (!isSafeToSpeculativelyExecute(I))
216       return false;
217
218     if (isa<DbgInfoIntrinsic>(I))
219       continue;
220
221     switch (I->getOpcode()) {
222     default:
223       return false;
224     case Instruction::GetElementPtr:
225       // GEPs are cheap if all indices are constant.
226       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
227         return false;
228       // fall-thru to increment case
229     case Instruction::Add:
230     case Instruction::Sub:
231     case Instruction::And:
232     case Instruction::Or:
233     case Instruction::Xor:
234     case Instruction::Shl:
235     case Instruction::LShr:
236     case Instruction::AShr: {
237       Value *IVOpnd = !isa<Constant>(I->getOperand(0))
238                           ? I->getOperand(0)
239                           : !isa<Constant>(I->getOperand(1))
240                                 ? I->getOperand(1)
241                                 : nullptr;
242       if (!IVOpnd)
243         return false;
244
245       // If increment operand is used outside of the loop, this speculation
246       // could cause extra live range interference.
247       if (MultiExitLoop) {
248         for (User *UseI : IVOpnd->users()) {
249           auto *UserInst = cast<Instruction>(UseI);
250           if (!L->contains(UserInst))
251             return false;
252         }
253       }
254
255       if (seenIncrement)
256         return false;
257       seenIncrement = true;
258       break;
259     }
260     case Instruction::Trunc:
261     case Instruction::ZExt:
262     case Instruction::SExt:
263       // ignore type conversions
264       break;
265     }
266   }
267   return true;
268 }
269
270 /// Fold the loop tail into the loop exit by speculating the loop tail
271 /// instructions. Typically, this is a single post-increment. In the case of a
272 /// simple 2-block loop, hoisting the increment can be much better than
273 /// duplicating the entire loop header. In the case of loops with early exits,
274 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
275 /// canonical form so downstream passes can handle it.
276 ///
277 /// I don't believe this invalidates SCEV.
278 bool LoopRotate::simplifyLoopLatch(Loop *L) {
279   BasicBlock *Latch = L->getLoopLatch();
280   if (!Latch || Latch->hasAddressTaken())
281     return false;
282
283   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
284   if (!Jmp || !Jmp->isUnconditional())
285     return false;
286
287   BasicBlock *LastExit = Latch->getSinglePredecessor();
288   if (!LastExit || !L->isLoopExiting(LastExit))
289     return false;
290
291   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
292   if (!BI)
293     return false;
294
295   if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
296     return false;
297
298   DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
299         << LastExit->getName() << "\n");
300
301   // Hoist the instructions from Latch into LastExit.
302   LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
303
304   unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
305   BasicBlock *Header = Jmp->getSuccessor(0);
306   assert(Header == L->getHeader() && "expected a backward branch");
307
308   // Remove Latch from the CFG so that LastExit becomes the new Latch.
309   BI->setSuccessor(FallThruPath, Header);
310   Latch->replaceSuccessorsPhiUsesWith(LastExit);
311   Jmp->eraseFromParent();
312
313   // Nuke the Latch block.
314   assert(Latch->empty() && "unable to evacuate Latch");
315   LI->removeBlock(Latch);
316   if (DT)
317     DT->eraseNode(Latch);
318   Latch->eraseFromParent();
319   return true;
320 }
321
322 /// Rotate loop LP. Return true if the loop is rotated.
323 ///
324 /// \param SimplifiedLatch is true if the latch was just folded into the final
325 /// loop exit. In this case we may want to rotate even though the new latch is
326 /// now an exiting branch. This rotation would have happened had the latch not
327 /// been simplified. However, if SimplifiedLatch is false, then we avoid
328 /// rotating loops in which the latch exits to avoid excessive or endless
329 /// rotation. LoopRotate should be repeatable and converge to a canonical
330 /// form. This property is satisfied because simplifying the loop latch can only
331 /// happen once across multiple invocations of the LoopRotate pass.
332 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
333   // If the loop has only one block then there is not much to rotate.
334   if (L->getBlocks().size() == 1)
335     return false;
336
337   BasicBlock *OrigHeader = L->getHeader();
338   BasicBlock *OrigLatch = L->getLoopLatch();
339
340   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
341   if (!BI || BI->isUnconditional())
342     return false;
343
344   // If the loop header is not one of the loop exiting blocks then
345   // either this loop is already rotated or it is not
346   // suitable for loop rotation transformations.
347   if (!L->isLoopExiting(OrigHeader))
348     return false;
349
350   // If the loop latch already contains a branch that leaves the loop then the
351   // loop is already rotated.
352   if (!OrigLatch)
353     return false;
354
355   // Rotate if either the loop latch does *not* exit the loop, or if the loop
356   // latch was just simplified.
357   if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
358     return false;
359
360   // Check size of original header and reject loop if it is very big or we can't
361   // duplicate blocks inside it.
362   {
363     SmallPtrSet<const Value *, 32> EphValues;
364     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
365
366     CodeMetrics Metrics;
367     Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
368     if (Metrics.notDuplicatable) {
369       DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
370             << " instructions: "; L->dump());
371       return false;
372     }
373     if (Metrics.NumInsts > MaxHeaderSize)
374       return false;
375   }
376
377   // Now, this loop is suitable for rotation.
378   BasicBlock *OrigPreheader = L->getLoopPreheader();
379
380   // If the loop could not be converted to canonical form, it must have an
381   // indirectbr in it, just give up.
382   if (!OrigPreheader)
383     return false;
384
385   // Anything ScalarEvolution may know about this loop or the PHI nodes
386   // in its header will soon be invalidated.
387   if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
388     SEWP->getSE().forgetLoop(L);
389
390   DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
391
392   // Find new Loop header. NewHeader is a Header's one and only successor
393   // that is inside loop.  Header's other successor is outside the
394   // loop.  Otherwise loop is not suitable for rotation.
395   BasicBlock *Exit = BI->getSuccessor(0);
396   BasicBlock *NewHeader = BI->getSuccessor(1);
397   if (L->contains(Exit))
398     std::swap(Exit, NewHeader);
399   assert(NewHeader && "Unable to determine new loop header");
400   assert(L->contains(NewHeader) && !L->contains(Exit) &&
401          "Unable to determine loop header and exit blocks");
402
403   // This code assumes that the new header has exactly one predecessor.
404   // Remove any single-entry PHI nodes in it.
405   assert(NewHeader->getSinglePredecessor() &&
406          "New header doesn't have one pred!");
407   FoldSingleEntryPHINodes(NewHeader);
408
409   // Begin by walking OrigHeader and populating ValueMap with an entry for
410   // each Instruction.
411   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
412   ValueToValueMapTy ValueMap;
413
414   // For PHI nodes, the value available in OldPreHeader is just the
415   // incoming value from OldPreHeader.
416   for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
417     ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
418
419   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
420
421   // For the rest of the instructions, either hoist to the OrigPreheader if
422   // possible or create a clone in the OldPreHeader if not.
423   TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
424   while (I != E) {
425     Instruction *Inst = I++;
426
427     // If the instruction's operands are invariant and it doesn't read or write
428     // memory, then it is safe to hoist.  Doing this doesn't change the order of
429     // execution in the preheader, but does prevent the instruction from
430     // executing in each iteration of the loop.  This means it is safe to hoist
431     // something that might trap, but isn't safe to hoist something that reads
432     // memory (without proving that the loop doesn't write).
433     if (L->hasLoopInvariantOperands(Inst) &&
434         !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
435         !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
436         !isa<AllocaInst>(Inst)) {
437       Inst->moveBefore(LoopEntryBranch);
438       continue;
439     }
440
441     // Otherwise, create a duplicate of the instruction.
442     Instruction *C = Inst->clone();
443
444     // Eagerly remap the operands of the instruction.
445     RemapInstruction(C, ValueMap,
446                      RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
447
448     // With the operands remapped, see if the instruction constant folds or is
449     // otherwise simplifyable.  This commonly occurs because the entry from PHI
450     // nodes allows icmps and other instructions to fold.
451     // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
452     Value *V = SimplifyInstruction(C, DL);
453     if (V && LI->replacementPreservesLCSSAForm(C, V)) {
454       // If so, then delete the temporary instruction and stick the folded value
455       // in the map.
456       delete C;
457       ValueMap[Inst] = V;
458     } else {
459       // Otherwise, stick the new instruction into the new block!
460       C->setName(Inst->getName());
461       C->insertBefore(LoopEntryBranch);
462       ValueMap[Inst] = C;
463     }
464   }
465
466   // Along with all the other instructions, we just cloned OrigHeader's
467   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
468   // successors by duplicating their incoming values for OrigHeader.
469   TerminatorInst *TI = OrigHeader->getTerminator();
470   for (BasicBlock *SuccBB : TI->successors())
471     for (BasicBlock::iterator BI = SuccBB->begin();
472          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
473       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
474
475   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
476   // OrigPreHeader's old terminator (the original branch into the loop), and
477   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
478   LoopEntryBranch->eraseFromParent();
479
480   // If there were any uses of instructions in the duplicated block outside the
481   // loop, update them, inserting PHI nodes as required
482   RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
483
484   // NewHeader is now the header of the loop.
485   L->moveToHeader(NewHeader);
486   assert(L->getHeader() == NewHeader && "Latch block is our new header");
487
488
489   // At this point, we've finished our major CFG changes.  As part of cloning
490   // the loop into the preheader we've simplified instructions and the
491   // duplicated conditional branch may now be branching on a constant.  If it is
492   // branching on a constant and if that constant means that we enter the loop,
493   // then we fold away the cond branch to an uncond branch.  This simplifies the
494   // loop in cases important for nested loops, and it also means we don't have
495   // to split as many edges.
496   BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
497   assert(PHBI->isConditional() && "Should be clone of BI condbr!");
498   if (!isa<ConstantInt>(PHBI->getCondition()) ||
499       PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
500           != NewHeader) {
501     // The conditional branch can't be folded, handle the general case.
502     // Update DominatorTree to reflect the CFG change we just made.  Then split
503     // edges as necessary to preserve LoopSimplify form.
504     if (DT) {
505       // Everything that was dominated by the old loop header is now dominated
506       // by the original loop preheader. Conceptually the header was merged
507       // into the preheader, even though we reuse the actual block as a new
508       // loop latch.
509       DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
510       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
511                                                    OrigHeaderNode->end());
512       DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
513       for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
514         DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
515
516       assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
517       assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
518
519       // Update OrigHeader to be dominated by the new header block.
520       DT->changeImmediateDominator(OrigHeader, OrigLatch);
521     }
522
523     // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
524     // thus is not a preheader anymore.
525     // Split the edge to form a real preheader.
526     BasicBlock *NewPH = SplitCriticalEdge(
527         OrigPreheader, NewHeader,
528         CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
529     NewPH->setName(NewHeader->getName() + ".lr.ph");
530
531     // Preserve canonical loop form, which means that 'Exit' should have only
532     // one predecessor. Note that Exit could be an exit block for multiple
533     // nested loops, causing both of the edges to now be critical and need to
534     // be split.
535     SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
536     bool SplitLatchEdge = false;
537     for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
538                                                  PE = ExitPreds.end();
539          PI != PE; ++PI) {
540       // We only need to split loop exit edges.
541       Loop *PredLoop = LI->getLoopFor(*PI);
542       if (!PredLoop || PredLoop->contains(Exit))
543         continue;
544       if (isa<IndirectBrInst>((*PI)->getTerminator()))
545         continue;
546       SplitLatchEdge |= L->getLoopLatch() == *PI;
547       BasicBlock *ExitSplit = SplitCriticalEdge(
548           *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
549       ExitSplit->moveBefore(Exit);
550     }
551     assert(SplitLatchEdge &&
552            "Despite splitting all preds, failed to split latch exit?");
553   } else {
554     // We can fold the conditional branch in the preheader, this makes things
555     // simpler. The first step is to remove the extra edge to the Exit block.
556     Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
557     BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
558     NewBI->setDebugLoc(PHBI->getDebugLoc());
559     PHBI->eraseFromParent();
560
561     // With our CFG finalized, update DomTree if it is available.
562     if (DT) {
563       // Update OrigHeader to be dominated by the new header block.
564       DT->changeImmediateDominator(NewHeader, OrigPreheader);
565       DT->changeImmediateDominator(OrigHeader, OrigLatch);
566
567       // Brute force incremental dominator tree update. Call
568       // findNearestCommonDominator on all CFG predecessors of each child of the
569       // original header.
570       DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
571       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
572                                                    OrigHeaderNode->end());
573       bool Changed;
574       do {
575         Changed = false;
576         for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
577           DomTreeNode *Node = HeaderChildren[I];
578           BasicBlock *BB = Node->getBlock();
579
580           pred_iterator PI = pred_begin(BB);
581           BasicBlock *NearestDom = *PI;
582           for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
583             NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
584
585           // Remember if this changes the DomTree.
586           if (Node->getIDom()->getBlock() != NearestDom) {
587             DT->changeImmediateDominator(BB, NearestDom);
588             Changed = true;
589           }
590         }
591
592       // If the dominator changed, this may have an effect on other
593       // predecessors, continue until we reach a fixpoint.
594       } while (Changed);
595     }
596   }
597
598   assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
599   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
600
601   // Now that the CFG and DomTree are in a consistent state again, try to merge
602   // the OrigHeader block into OrigLatch.  This will succeed if they are
603   // connected by an unconditional branch.  This is just a cleanup so the
604   // emitted code isn't too gross in this common case.
605   MergeBlockIntoPredecessor(OrigHeader, DT, LI);
606
607   DEBUG(dbgs() << "LoopRotation: into "; L->dump());
608
609   ++NumRotated;
610   return true;
611 }