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