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