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