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