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