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