]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Scalar/LoopRotation.cpp
MFV r313071:
[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   }
331
332   // Along with all the other instructions, we just cloned OrigHeader's
333   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
334   // successors by duplicating their incoming values for OrigHeader.
335   TerminatorInst *TI = OrigHeader->getTerminator();
336   for (BasicBlock *SuccBB : TI->successors())
337     for (BasicBlock::iterator BI = SuccBB->begin();
338          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
339       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
340
341   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
342   // OrigPreHeader's old terminator (the original branch into the loop), and
343   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
344   LoopEntryBranch->eraseFromParent();
345
346   // If there were any uses of instructions in the duplicated block outside the
347   // loop, update them, inserting PHI nodes as required
348   RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
349
350   // NewHeader is now the header of the loop.
351   L->moveToHeader(NewHeader);
352   assert(L->getHeader() == NewHeader && "Latch block is our new header");
353
354   // At this point, we've finished our major CFG changes.  As part of cloning
355   // the loop into the preheader we've simplified instructions and the
356   // duplicated conditional branch may now be branching on a constant.  If it is
357   // branching on a constant and if that constant means that we enter the loop,
358   // then we fold away the cond branch to an uncond branch.  This simplifies the
359   // loop in cases important for nested loops, and it also means we don't have
360   // to split as many edges.
361   BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
362   assert(PHBI->isConditional() && "Should be clone of BI condbr!");
363   if (!isa<ConstantInt>(PHBI->getCondition()) ||
364       PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
365           NewHeader) {
366     // The conditional branch can't be folded, handle the general case.
367     // Update DominatorTree to reflect the CFG change we just made.  Then split
368     // edges as necessary to preserve LoopSimplify form.
369     if (DT) {
370       // Everything that was dominated by the old loop header is now dominated
371       // by the original loop preheader. Conceptually the header was merged
372       // into the preheader, even though we reuse the actual block as a new
373       // loop latch.
374       DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
375       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
376                                                    OrigHeaderNode->end());
377       DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
378       for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
379         DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
380
381       assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
382       assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
383
384       // Update OrigHeader to be dominated by the new header block.
385       DT->changeImmediateDominator(OrigHeader, OrigLatch);
386     }
387
388     // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
389     // thus is not a preheader anymore.
390     // Split the edge to form a real preheader.
391     BasicBlock *NewPH = SplitCriticalEdge(
392         OrigPreheader, NewHeader,
393         CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
394     NewPH->setName(NewHeader->getName() + ".lr.ph");
395
396     // Preserve canonical loop form, which means that 'Exit' should have only
397     // one predecessor. Note that Exit could be an exit block for multiple
398     // nested loops, causing both of the edges to now be critical and need to
399     // be split.
400     SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
401     bool SplitLatchEdge = false;
402     for (BasicBlock *ExitPred : ExitPreds) {
403       // We only need to split loop exit edges.
404       Loop *PredLoop = LI->getLoopFor(ExitPred);
405       if (!PredLoop || PredLoop->contains(Exit))
406         continue;
407       if (isa<IndirectBrInst>(ExitPred->getTerminator()))
408         continue;
409       SplitLatchEdge |= L->getLoopLatch() == ExitPred;
410       BasicBlock *ExitSplit = SplitCriticalEdge(
411           ExitPred, Exit,
412           CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
413       ExitSplit->moveBefore(Exit);
414     }
415     assert(SplitLatchEdge &&
416            "Despite splitting all preds, failed to split latch exit?");
417   } else {
418     // We can fold the conditional branch in the preheader, this makes things
419     // simpler. The first step is to remove the extra edge to the Exit block.
420     Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
421     BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
422     NewBI->setDebugLoc(PHBI->getDebugLoc());
423     PHBI->eraseFromParent();
424
425     // With our CFG finalized, update DomTree if it is available.
426     if (DT) {
427       // Update OrigHeader to be dominated by the new header block.
428       DT->changeImmediateDominator(NewHeader, OrigPreheader);
429       DT->changeImmediateDominator(OrigHeader, OrigLatch);
430
431       // Brute force incremental dominator tree update. Call
432       // findNearestCommonDominator on all CFG predecessors of each child of the
433       // original header.
434       DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
435       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
436                                                    OrigHeaderNode->end());
437       bool Changed;
438       do {
439         Changed = false;
440         for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
441           DomTreeNode *Node = HeaderChildren[I];
442           BasicBlock *BB = Node->getBlock();
443
444           pred_iterator PI = pred_begin(BB);
445           BasicBlock *NearestDom = *PI;
446           for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
447             NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
448
449           // Remember if this changes the DomTree.
450           if (Node->getIDom()->getBlock() != NearestDom) {
451             DT->changeImmediateDominator(BB, NearestDom);
452             Changed = true;
453           }
454         }
455
456         // If the dominator changed, this may have an effect on other
457         // predecessors, continue until we reach a fixpoint.
458       } while (Changed);
459     }
460   }
461
462   assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
463   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
464
465   // Now that the CFG and DomTree are in a consistent state again, try to merge
466   // the OrigHeader block into OrigLatch.  This will succeed if they are
467   // connected by an unconditional branch.  This is just a cleanup so the
468   // emitted code isn't too gross in this common case.
469   MergeBlockIntoPredecessor(OrigHeader, DT, LI);
470
471   DEBUG(dbgs() << "LoopRotation: into "; L->dump());
472
473   ++NumRotated;
474   return true;
475 }
476
477 /// Determine whether the instructions in this range may be safely and cheaply
478 /// speculated. This is not an important enough situation to develop complex
479 /// heuristics. We handle a single arithmetic instruction along with any type
480 /// conversions.
481 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
482                                   BasicBlock::iterator End, Loop *L) {
483   bool seenIncrement = false;
484   bool MultiExitLoop = false;
485
486   if (!L->getExitingBlock())
487     MultiExitLoop = true;
488
489   for (BasicBlock::iterator I = Begin; I != End; ++I) {
490
491     if (!isSafeToSpeculativelyExecute(&*I))
492       return false;
493
494     if (isa<DbgInfoIntrinsic>(I))
495       continue;
496
497     switch (I->getOpcode()) {
498     default:
499       return false;
500     case Instruction::GetElementPtr:
501       // GEPs are cheap if all indices are constant.
502       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
503         return false;
504     // fall-thru to increment case
505     case Instruction::Add:
506     case Instruction::Sub:
507     case Instruction::And:
508     case Instruction::Or:
509     case Instruction::Xor:
510     case Instruction::Shl:
511     case Instruction::LShr:
512     case Instruction::AShr: {
513       Value *IVOpnd =
514           !isa<Constant>(I->getOperand(0))
515               ? I->getOperand(0)
516               : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
517       if (!IVOpnd)
518         return false;
519
520       // If increment operand is used outside of the loop, this speculation
521       // could cause extra live range interference.
522       if (MultiExitLoop) {
523         for (User *UseI : IVOpnd->users()) {
524           auto *UserInst = cast<Instruction>(UseI);
525           if (!L->contains(UserInst))
526             return false;
527         }
528       }
529
530       if (seenIncrement)
531         return false;
532       seenIncrement = true;
533       break;
534     }
535     case Instruction::Trunc:
536     case Instruction::ZExt:
537     case Instruction::SExt:
538       // ignore type conversions
539       break;
540     }
541   }
542   return true;
543 }
544
545 /// Fold the loop tail into the loop exit by speculating the loop tail
546 /// instructions. Typically, this is a single post-increment. In the case of a
547 /// simple 2-block loop, hoisting the increment can be much better than
548 /// duplicating the entire loop header. In the case of loops with early exits,
549 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
550 /// canonical form so downstream passes can handle it.
551 ///
552 /// I don't believe this invalidates SCEV.
553 bool LoopRotate::simplifyLoopLatch(Loop *L) {
554   BasicBlock *Latch = L->getLoopLatch();
555   if (!Latch || Latch->hasAddressTaken())
556     return false;
557
558   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
559   if (!Jmp || !Jmp->isUnconditional())
560     return false;
561
562   BasicBlock *LastExit = Latch->getSinglePredecessor();
563   if (!LastExit || !L->isLoopExiting(LastExit))
564     return false;
565
566   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
567   if (!BI)
568     return false;
569
570   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
571     return false;
572
573   DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
574                << LastExit->getName() << "\n");
575
576   // Hoist the instructions from Latch into LastExit.
577   LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
578                                  Latch->begin(), Jmp->getIterator());
579
580   unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
581   BasicBlock *Header = Jmp->getSuccessor(0);
582   assert(Header == L->getHeader() && "expected a backward branch");
583
584   // Remove Latch from the CFG so that LastExit becomes the new Latch.
585   BI->setSuccessor(FallThruPath, Header);
586   Latch->replaceSuccessorsPhiUsesWith(LastExit);
587   Jmp->eraseFromParent();
588
589   // Nuke the Latch block.
590   assert(Latch->empty() && "unable to evacuate Latch");
591   LI->removeBlock(Latch);
592   if (DT)
593     DT->eraseNode(Latch);
594   Latch->eraseFromParent();
595   return true;
596 }
597
598 /// Rotate \c L, and return true if any modification was made.
599 bool LoopRotate::processLoop(Loop *L) {
600   // Save the loop metadata.
601   MDNode *LoopMD = L->getLoopID();
602
603   // Simplify the loop latch before attempting to rotate the header
604   // upward. Rotation may not be needed if the loop tail can be folded into the
605   // loop exit.
606   bool SimplifiedLatch = simplifyLoopLatch(L);
607
608   bool MadeChange = rotateLoop(L, SimplifiedLatch);
609   assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
610          "Loop latch should be exiting after loop-rotate.");
611
612   // Restore the loop metadata.
613   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
614   if ((MadeChange || SimplifiedLatch) && LoopMD)
615     L->setLoopID(LoopMD);
616
617   return MadeChange;
618 }
619
620 LoopRotatePass::LoopRotatePass() {}
621
622 PreservedAnalyses LoopRotatePass::run(Loop &L, AnalysisManager<Loop> &AM) {
623   auto &FAM = AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
624   Function *F = L.getHeader()->getParent();
625
626   auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
627   const auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F);
628   auto *AC = FAM.getCachedResult<AssumptionAnalysis>(*F);
629   assert((LI && TTI && AC) && "Analyses for loop rotation not available");
630
631   // Optional analyses.
632   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
633   auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
634   LoopRotate LR(DefaultRotationThreshold, LI, TTI, AC, DT, SE);
635
636   bool Changed = LR.processLoop(&L);
637   if (!Changed)
638     return PreservedAnalyses::all();
639   return getLoopPassPreservedAnalyses();
640 }
641
642 namespace {
643
644 class LoopRotateLegacyPass : public LoopPass {
645   unsigned MaxHeaderSize;
646
647 public:
648   static char ID; // Pass ID, replacement for typeid
649   LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
650     initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry());
651     if (SpecifiedMaxHeaderSize == -1)
652       MaxHeaderSize = DefaultRotationThreshold;
653     else
654       MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
655   }
656
657   // LCSSA form makes instruction renaming easier.
658   void getAnalysisUsage(AnalysisUsage &AU) const override {
659     AU.addRequired<AssumptionCacheTracker>();
660     AU.addRequired<TargetTransformInfoWrapperPass>();
661     getLoopAnalysisUsage(AU);
662   }
663
664   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
665     if (skipLoop(L))
666       return false;
667     Function &F = *L->getHeader()->getParent();
668
669     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
670     const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
671     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
672     auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
673     auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
674     auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
675     auto *SE = SEWP ? &SEWP->getSE() : nullptr;
676     LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE);
677     return LR.processLoop(L);
678   }
679 };
680 }
681
682 char LoopRotateLegacyPass::ID = 0;
683 INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
684                       false, false)
685 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
686 INITIALIZE_PASS_DEPENDENCY(LoopPass)
687 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
688 INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
689                     false)
690
691 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
692   return new LoopRotateLegacyPass(MaxHeaderSize);
693 }