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