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