1 //===----------------- LoopRotationUtils.cpp -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides utilities to convert a loop into a loop with bottom test.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Utils/LoopRotationUtils.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/Analysis/AssumptionCache.h"
16 #include "llvm/Analysis/BasicAliasAnalysis.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/DomTreeUpdater.h"
19 #include "llvm/Analysis/GlobalsModRef.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/MemorySSA.h"
23 #include "llvm/Analysis/MemorySSAUpdater.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/DebugInfo.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/Cloning.h"
39 #include "llvm/Transforms/Utils/Local.h"
40 #include "llvm/Transforms/Utils/LoopUtils.h"
41 #include "llvm/Transforms/Utils/SSAUpdater.h"
42 #include "llvm/Transforms/Utils/ValueMapper.h"
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "loop-rotate"
46 
47 STATISTIC(NumNotRotatedDueToHeaderSize,
48           "Number of loops not rotated due to the header size");
49 STATISTIC(NumInstrsHoisted,
50           "Number of instructions hoisted into loop preheader");
51 STATISTIC(NumInstrsDuplicated,
52           "Number of instructions cloned into loop preheader");
53 STATISTIC(NumRotated, "Number of loops rotated");
54 
55 static cl::opt<bool>
56     MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
57                 cl::desc("Allow loop rotation multiple times in order to reach "
58                          "a better latch exit"));
59 
60 namespace {
61 /// A simple loop rotation transformation.
62 class LoopRotate {
63   const unsigned MaxHeaderSize;
64   LoopInfo *LI;
65   const TargetTransformInfo *TTI;
66   AssumptionCache *AC;
67   DominatorTree *DT;
68   ScalarEvolution *SE;
69   MemorySSAUpdater *MSSAU;
70   const SimplifyQuery &SQ;
71   bool RotationOnly;
72   bool IsUtilMode;
73   bool PrepareForLTO;
74 
75 public:
76   LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
77              const TargetTransformInfo *TTI, AssumptionCache *AC,
78              DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
79              const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
80              bool PrepareForLTO)
81       : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
82         MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
83         IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
84   bool processLoop(Loop *L);
85 
86 private:
87   bool rotateLoop(Loop *L, bool SimplifiedLatch);
88   bool simplifyLoopLatch(Loop *L);
89 };
90 } // end anonymous namespace
91 
92 /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
93 /// previously exist in the map, and the value was inserted.
94 static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) {
95   bool Inserted = VM.insert({K, V}).second;
96   assert(Inserted);
97   (void)Inserted;
98 }
99 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
100 /// old header into the preheader.  If there were uses of the values produced by
101 /// these instruction that were outside of the loop, we have to insert PHI nodes
102 /// to merge the two values.  Do this now.
103 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
104                                             BasicBlock *OrigPreheader,
105                                             ValueToValueMapTy &ValueMap,
106                                             ScalarEvolution *SE,
107                                 SmallVectorImpl<PHINode*> *InsertedPHIs) {
108   // Remove PHI node entries that are no longer live.
109   BasicBlock::iterator I, E = OrigHeader->end();
110   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
111     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
112 
113   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
114   // as necessary.
115   SSAUpdater SSA(InsertedPHIs);
116   for (I = OrigHeader->begin(); I != E; ++I) {
117     Value *OrigHeaderVal = &*I;
118 
119     // If there are no uses of the value (e.g. because it returns void), there
120     // is nothing to rewrite.
121     if (OrigHeaderVal->use_empty())
122       continue;
123 
124     Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
125 
126     // The value now exits in two versions: the initial value in the preheader
127     // and the loop "next" value in the original header.
128     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
129     // Force re-computation of OrigHeaderVal, as some users now need to use the
130     // new PHI node.
131     if (SE)
132       SE->forgetValue(OrigHeaderVal);
133     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
134     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
135 
136     // Visit each use of the OrigHeader instruction.
137     for (Use &U : llvm::make_early_inc_range(OrigHeaderVal->uses())) {
138       // SSAUpdater can't handle a non-PHI use in the same block as an
139       // earlier def. We can easily handle those cases manually.
140       Instruction *UserInst = cast<Instruction>(U.getUser());
141       if (!isa<PHINode>(UserInst)) {
142         BasicBlock *UserBB = UserInst->getParent();
143 
144         // The original users in the OrigHeader are already using the
145         // original definitions.
146         if (UserBB == OrigHeader)
147           continue;
148 
149         // Users in the OrigPreHeader need to use the value to which the
150         // original definitions are mapped.
151         if (UserBB == OrigPreheader) {
152           U = OrigPreHeaderVal;
153           continue;
154         }
155       }
156 
157       // Anything else can be handled by SSAUpdater.
158       SSA.RewriteUse(U);
159     }
160 
161     // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
162     // intrinsics.
163     SmallVector<DbgValueInst *, 1> DbgValues;
164     llvm::findDbgValues(DbgValues, OrigHeaderVal);
165     for (auto &DbgValue : DbgValues) {
166       // The original users in the OrigHeader are already using the original
167       // definitions.
168       BasicBlock *UserBB = DbgValue->getParent();
169       if (UserBB == OrigHeader)
170         continue;
171 
172       // Users in the OrigPreHeader need to use the value to which the
173       // original definitions are mapped and anything else can be handled by
174       // the SSAUpdater. To avoid adding PHINodes, check if the value is
175       // available in UserBB, if not substitute undef.
176       Value *NewVal;
177       if (UserBB == OrigPreheader)
178         NewVal = OrigPreHeaderVal;
179       else if (SSA.HasValueForBlock(UserBB))
180         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
181       else
182         NewVal = UndefValue::get(OrigHeaderVal->getType());
183       DbgValue->replaceVariableLocationOp(OrigHeaderVal, NewVal);
184     }
185   }
186 }
187 
188 // Assuming both header and latch are exiting, look for a phi which is only
189 // used outside the loop (via a LCSSA phi) in the exit from the header.
190 // This means that rotating the loop can remove the phi.
191 static bool profitableToRotateLoopExitingLatch(Loop *L) {
192   BasicBlock *Header = L->getHeader();
193   BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
194   assert(BI && BI->isConditional() && "need header with conditional exit");
195   BasicBlock *HeaderExit = BI->getSuccessor(0);
196   if (L->contains(HeaderExit))
197     HeaderExit = BI->getSuccessor(1);
198 
199   for (auto &Phi : Header->phis()) {
200     // Look for uses of this phi in the loop/via exits other than the header.
201     if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
202           return cast<Instruction>(U)->getParent() != HeaderExit;
203         }))
204       continue;
205     return true;
206   }
207   return false;
208 }
209 
210 // Check that latch exit is deoptimizing (which means - very unlikely to happen)
211 // and there is another exit from the loop which is non-deoptimizing.
212 // If we rotate latch to that exit our loop has a better chance of being fully
213 // canonical.
214 //
215 // It can give false positives in some rare cases.
216 static bool canRotateDeoptimizingLatchExit(Loop *L) {
217   BasicBlock *Latch = L->getLoopLatch();
218   assert(Latch && "need latch");
219   BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
220   // Need normal exiting latch.
221   if (!BI || !BI->isConditional())
222     return false;
223 
224   BasicBlock *Exit = BI->getSuccessor(1);
225   if (L->contains(Exit))
226     Exit = BI->getSuccessor(0);
227 
228   // Latch exit is non-deoptimizing, no need to rotate.
229   if (!Exit->getPostdominatingDeoptimizeCall())
230     return false;
231 
232   SmallVector<BasicBlock *, 4> Exits;
233   L->getUniqueExitBlocks(Exits);
234   if (!Exits.empty()) {
235     // There is at least one non-deoptimizing exit.
236     //
237     // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
238     // as it can conservatively return false for deoptimizing exits with
239     // complex enough control flow down to deoptimize call.
240     //
241     // That means here we can report success for a case where
242     // all exits are deoptimizing but one of them has complex enough
243     // control flow (e.g. with loops).
244     //
245     // That should be a very rare case and false positives for this function
246     // have compile-time effect only.
247     return any_of(Exits, [](const BasicBlock *BB) {
248       return !BB->getPostdominatingDeoptimizeCall();
249     });
250   }
251   return false;
252 }
253 
254 /// Rotate loop LP. Return true if the loop is rotated.
255 ///
256 /// \param SimplifiedLatch is true if the latch was just folded into the final
257 /// loop exit. In this case we may want to rotate even though the new latch is
258 /// now an exiting branch. This rotation would have happened had the latch not
259 /// been simplified. However, if SimplifiedLatch is false, then we avoid
260 /// rotating loops in which the latch exits to avoid excessive or endless
261 /// rotation. LoopRotate should be repeatable and converge to a canonical
262 /// form. This property is satisfied because simplifying the loop latch can only
263 /// happen once across multiple invocations of the LoopRotate pass.
264 ///
265 /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
266 /// so to reach a suitable (non-deoptimizing) exit.
267 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
268   // If the loop has only one block then there is not much to rotate.
269   if (L->getBlocks().size() == 1)
270     return false;
271 
272   bool Rotated = false;
273   do {
274     BasicBlock *OrigHeader = L->getHeader();
275     BasicBlock *OrigLatch = L->getLoopLatch();
276 
277     BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
278     if (!BI || BI->isUnconditional())
279       return Rotated;
280 
281     // If the loop header is not one of the loop exiting blocks then
282     // either this loop is already rotated or it is not
283     // suitable for loop rotation transformations.
284     if (!L->isLoopExiting(OrigHeader))
285       return Rotated;
286 
287     // If the loop latch already contains a branch that leaves the loop then the
288     // loop is already rotated.
289     if (!OrigLatch)
290       return Rotated;
291 
292     // Rotate if either the loop latch does *not* exit the loop, or if the loop
293     // latch was just simplified. Or if we think it will be profitable.
294     if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
295         !profitableToRotateLoopExitingLatch(L) &&
296         !canRotateDeoptimizingLatchExit(L))
297       return Rotated;
298 
299     // Check size of original header and reject loop if it is very big or we can't
300     // duplicate blocks inside it.
301     {
302       SmallPtrSet<const Value *, 32> EphValues;
303       CodeMetrics::collectEphemeralValues(L, AC, EphValues);
304 
305       CodeMetrics Metrics;
306       Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
307       if (Metrics.notDuplicatable) {
308         LLVM_DEBUG(
309                    dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
310                    << " instructions: ";
311                    L->dump());
312         return Rotated;
313       }
314       if (Metrics.convergent) {
315         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
316                    "instructions: ";
317                    L->dump());
318         return Rotated;
319       }
320       if (Metrics.NumInsts > MaxHeaderSize) {
321         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
322                           << Metrics.NumInsts
323                           << " instructions, which is more than the threshold ("
324                           << MaxHeaderSize << " instructions): ";
325                    L->dump());
326         ++NumNotRotatedDueToHeaderSize;
327         return Rotated;
328       }
329 
330       // When preparing for LTO, avoid rotating loops with calls that could be
331       // inlined during the LTO stage.
332       if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
333         return Rotated;
334     }
335 
336     // Now, this loop is suitable for rotation.
337     BasicBlock *OrigPreheader = L->getLoopPreheader();
338 
339     // If the loop could not be converted to canonical form, it must have an
340     // indirectbr in it, just give up.
341     if (!OrigPreheader || !L->hasDedicatedExits())
342       return Rotated;
343 
344     // Anything ScalarEvolution may know about this loop or the PHI nodes
345     // in its header will soon be invalidated. We should also invalidate
346     // all outer loops because insertion and deletion of blocks that happens
347     // during the rotation may violate invariants related to backedge taken
348     // infos in them.
349     if (SE)
350       SE->forgetTopmostLoop(L);
351 
352     LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
353     if (MSSAU && VerifyMemorySSA)
354       MSSAU->getMemorySSA()->verifyMemorySSA();
355 
356     // Find new Loop header. NewHeader is a Header's one and only successor
357     // that is inside loop.  Header's other successor is outside the
358     // loop.  Otherwise loop is not suitable for rotation.
359     BasicBlock *Exit = BI->getSuccessor(0);
360     BasicBlock *NewHeader = BI->getSuccessor(1);
361     if (L->contains(Exit))
362       std::swap(Exit, NewHeader);
363     assert(NewHeader && "Unable to determine new loop header");
364     assert(L->contains(NewHeader) && !L->contains(Exit) &&
365            "Unable to determine loop header and exit blocks");
366 
367     // This code assumes that the new header has exactly one predecessor.
368     // Remove any single-entry PHI nodes in it.
369     assert(NewHeader->getSinglePredecessor() &&
370            "New header doesn't have one pred!");
371     FoldSingleEntryPHINodes(NewHeader);
372 
373     // Begin by walking OrigHeader and populating ValueMap with an entry for
374     // each Instruction.
375     BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
376     ValueToValueMapTy ValueMap, ValueMapMSSA;
377 
378     // For PHI nodes, the value available in OldPreHeader is just the
379     // incoming value from OldPreHeader.
380     for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
381       InsertNewValueIntoMap(ValueMap, PN,
382                             PN->getIncomingValueForBlock(OrigPreheader));
383 
384     // For the rest of the instructions, either hoist to the OrigPreheader if
385     // possible or create a clone in the OldPreHeader if not.
386     Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
387 
388     // Record all debug intrinsics preceding LoopEntryBranch to avoid
389     // duplication.
390     using DbgIntrinsicHash =
391         std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
392     auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
393       auto VarLocOps = D->location_ops();
394       return {{hash_combine_range(VarLocOps.begin(), VarLocOps.end()),
395                D->getVariable()},
396               D->getExpression()};
397     };
398     SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
399     for (Instruction &I : llvm::drop_begin(llvm::reverse(*OrigPreheader))) {
400       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I))
401         DbgIntrinsics.insert(makeHash(DII));
402       else
403         break;
404     }
405 
406     // Remember the local noalias scope declarations in the header. After the
407     // rotation, they must be duplicated and the scope must be cloned. This
408     // avoids unwanted interaction across iterations.
409     SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
410     for (Instruction &I : *OrigHeader)
411       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
412         NoAliasDeclInstructions.push_back(Decl);
413 
414     while (I != E) {
415       Instruction *Inst = &*I++;
416 
417       // If the instruction's operands are invariant and it doesn't read or write
418       // memory, then it is safe to hoist.  Doing this doesn't change the order of
419       // execution in the preheader, but does prevent the instruction from
420       // executing in each iteration of the loop.  This means it is safe to hoist
421       // something that might trap, but isn't safe to hoist something that reads
422       // memory (without proving that the loop doesn't write).
423       if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
424           !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
425           !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
426         Inst->moveBefore(LoopEntryBranch);
427         ++NumInstrsHoisted;
428         continue;
429       }
430 
431       // Otherwise, create a duplicate of the instruction.
432       Instruction *C = Inst->clone();
433       ++NumInstrsDuplicated;
434 
435       // Eagerly remap the operands of the instruction.
436       RemapInstruction(C, ValueMap,
437                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
438 
439       // Avoid inserting the same intrinsic twice.
440       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
441         if (DbgIntrinsics.count(makeHash(DII))) {
442           C->deleteValue();
443           continue;
444         }
445 
446       // With the operands remapped, see if the instruction constant folds or is
447       // otherwise simplifyable.  This commonly occurs because the entry from PHI
448       // nodes allows icmps and other instructions to fold.
449       Value *V = SimplifyInstruction(C, SQ);
450       if (V && LI->replacementPreservesLCSSAForm(C, V)) {
451         // If so, then delete the temporary instruction and stick the folded value
452         // in the map.
453         InsertNewValueIntoMap(ValueMap, Inst, V);
454         if (!C->mayHaveSideEffects()) {
455           C->deleteValue();
456           C = nullptr;
457         }
458       } else {
459         InsertNewValueIntoMap(ValueMap, Inst, C);
460       }
461       if (C) {
462         // Otherwise, stick the new instruction into the new block!
463         C->setName(Inst->getName());
464         C->insertBefore(LoopEntryBranch);
465 
466         if (auto *II = dyn_cast<AssumeInst>(C))
467           AC->registerAssumption(II);
468         // MemorySSA cares whether the cloned instruction was inserted or not, and
469         // not whether it can be remapped to a simplified value.
470         if (MSSAU)
471           InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
472       }
473     }
474 
475     if (!NoAliasDeclInstructions.empty()) {
476       // There are noalias scope declarations:
477       // (general):
478       // Original:    OrigPre              { OrigHeader NewHeader ... Latch }
479       // after:      (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
480       //
481       // with D: llvm.experimental.noalias.scope.decl,
482       //      U: !noalias or !alias.scope depending on D
483       //       ... { D U1 U2 }   can transform into:
484       // (0) : ... { D U1 U2 }        // no relevant rotation for this part
485       // (1) : ... D' { U1 U2 D }     // D is part of OrigHeader
486       // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
487       //
488       // We now want to transform:
489       // (1) -> : ... D' { D U1 U2 D'' }
490       // (2) -> : ... D' U1' { D U2 D'' U1'' }
491       // D: original llvm.experimental.noalias.scope.decl
492       // D', U1': duplicate with replaced scopes
493       // D'', U1'': different duplicate with replaced scopes
494       // This ensures a safe fallback to 'may_alias' introduced by the rotate,
495       // as U1'' and U1' scopes will not be compatible wrt to the local restrict
496 
497       // Clone the llvm.experimental.noalias.decl again for the NewHeader.
498       Instruction *NewHeaderInsertionPoint = &(*NewHeader->getFirstNonPHI());
499       for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
500         LLVM_DEBUG(dbgs() << "  Cloning llvm.experimental.noalias.scope.decl:"
501                           << *NAD << "\n");
502         Instruction *NewNAD = NAD->clone();
503         NewNAD->insertBefore(NewHeaderInsertionPoint);
504       }
505 
506       // Scopes must now be duplicated, once for OrigHeader and once for
507       // OrigPreHeader'.
508       {
509         auto &Context = NewHeader->getContext();
510 
511         SmallVector<MDNode *, 8> NoAliasDeclScopes;
512         for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
513           NoAliasDeclScopes.push_back(NAD->getScopeList());
514 
515         LLVM_DEBUG(dbgs() << "  Updating OrigHeader scopes\n");
516         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
517                                    "h.rot");
518         LLVM_DEBUG(OrigHeader->dump());
519 
520         // Keep the compile time impact low by only adapting the inserted block
521         // of instructions in the OrigPreHeader. This might result in slightly
522         // more aliasing between these instructions and those that were already
523         // present, but it will be much faster when the original PreHeader is
524         // large.
525         LLVM_DEBUG(dbgs() << "  Updating part of OrigPreheader scopes\n");
526         auto *FirstDecl =
527             cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
528         auto *LastInst = &OrigPreheader->back();
529         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
530                                    Context, "pre.rot");
531         LLVM_DEBUG(OrigPreheader->dump());
532 
533         LLVM_DEBUG(dbgs() << "  Updated NewHeader:\n");
534         LLVM_DEBUG(NewHeader->dump());
535       }
536     }
537 
538     // Along with all the other instructions, we just cloned OrigHeader's
539     // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
540     // successors by duplicating their incoming values for OrigHeader.
541     for (BasicBlock *SuccBB : successors(OrigHeader))
542       for (BasicBlock::iterator BI = SuccBB->begin();
543            PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
544         PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
545 
546     // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
547     // OrigPreHeader's old terminator (the original branch into the loop), and
548     // remove the corresponding incoming values from the PHI nodes in OrigHeader.
549     LoopEntryBranch->eraseFromParent();
550 
551     // Update MemorySSA before the rewrite call below changes the 1:1
552     // instruction:cloned_instruction_or_value mapping.
553     if (MSSAU) {
554       InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
555       MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
556                                           ValueMapMSSA);
557     }
558 
559     SmallVector<PHINode*, 2> InsertedPHIs;
560     // If there were any uses of instructions in the duplicated block outside the
561     // loop, update them, inserting PHI nodes as required
562     RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
563                                     &InsertedPHIs);
564 
565     // Attach dbg.value intrinsics to the new phis if that phi uses a value that
566     // previously had debug metadata attached. This keeps the debug info
567     // up-to-date in the loop body.
568     if (!InsertedPHIs.empty())
569       insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
570 
571     // NewHeader is now the header of the loop.
572     L->moveToHeader(NewHeader);
573     assert(L->getHeader() == NewHeader && "Latch block is our new header");
574 
575     // Inform DT about changes to the CFG.
576     if (DT) {
577       // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
578       // the DT about the removed edge to the OrigHeader (that got removed).
579       SmallVector<DominatorTree::UpdateType, 3> Updates;
580       Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
581       Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
582       Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
583 
584       if (MSSAU) {
585         MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
586         if (VerifyMemorySSA)
587           MSSAU->getMemorySSA()->verifyMemorySSA();
588       } else {
589         DT->applyUpdates(Updates);
590       }
591     }
592 
593     // At this point, we've finished our major CFG changes.  As part of cloning
594     // the loop into the preheader we've simplified instructions and the
595     // duplicated conditional branch may now be branching on a constant.  If it is
596     // branching on a constant and if that constant means that we enter the loop,
597     // then we fold away the cond branch to an uncond branch.  This simplifies the
598     // loop in cases important for nested loops, and it also means we don't have
599     // to split as many edges.
600     BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
601     assert(PHBI->isConditional() && "Should be clone of BI condbr!");
602     if (!isa<ConstantInt>(PHBI->getCondition()) ||
603         PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
604         NewHeader) {
605       // The conditional branch can't be folded, handle the general case.
606       // Split edges as necessary to preserve LoopSimplify form.
607 
608       // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
609       // thus is not a preheader anymore.
610       // Split the edge to form a real preheader.
611       BasicBlock *NewPH = SplitCriticalEdge(
612                                             OrigPreheader, NewHeader,
613                                             CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
614       NewPH->setName(NewHeader->getName() + ".lr.ph");
615 
616       // Preserve canonical loop form, which means that 'Exit' should have only
617       // one predecessor. Note that Exit could be an exit block for multiple
618       // nested loops, causing both of the edges to now be critical and need to
619       // be split.
620       SmallVector<BasicBlock *, 4> ExitPreds(predecessors(Exit));
621       bool SplitLatchEdge = false;
622       for (BasicBlock *ExitPred : ExitPreds) {
623         // We only need to split loop exit edges.
624         Loop *PredLoop = LI->getLoopFor(ExitPred);
625         if (!PredLoop || PredLoop->contains(Exit) ||
626             ExitPred->getTerminator()->isIndirectTerminator())
627           continue;
628         SplitLatchEdge |= L->getLoopLatch() == ExitPred;
629         BasicBlock *ExitSplit = SplitCriticalEdge(
630                                                   ExitPred, Exit,
631                                                   CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
632         ExitSplit->moveBefore(Exit);
633       }
634       assert(SplitLatchEdge &&
635              "Despite splitting all preds, failed to split latch exit?");
636       (void)SplitLatchEdge;
637     } else {
638       // We can fold the conditional branch in the preheader, this makes things
639       // simpler. The first step is to remove the extra edge to the Exit block.
640       Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
641       BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
642       NewBI->setDebugLoc(PHBI->getDebugLoc());
643       PHBI->eraseFromParent();
644 
645       // With our CFG finalized, update DomTree if it is available.
646       if (DT) DT->deleteEdge(OrigPreheader, Exit);
647 
648       // Update MSSA too, if available.
649       if (MSSAU)
650         MSSAU->removeEdge(OrigPreheader, Exit);
651     }
652 
653     assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
654     assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
655 
656     if (MSSAU && VerifyMemorySSA)
657       MSSAU->getMemorySSA()->verifyMemorySSA();
658 
659     // Now that the CFG and DomTree are in a consistent state again, try to merge
660     // the OrigHeader block into OrigLatch.  This will succeed if they are
661     // connected by an unconditional branch.  This is just a cleanup so the
662     // emitted code isn't too gross in this common case.
663     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
664     BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
665     bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
666     if (DidMerge)
667       RemoveRedundantDbgInstrs(PredBB);
668 
669     if (MSSAU && VerifyMemorySSA)
670       MSSAU->getMemorySSA()->verifyMemorySSA();
671 
672     LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
673 
674     ++NumRotated;
675 
676     Rotated = true;
677     SimplifiedLatch = false;
678 
679     // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
680     // Deoptimizing latch exit is not a generally typical case, so we just loop over.
681     // TODO: if it becomes a performance bottleneck extend rotation algorithm
682     // to handle multiple rotations in one go.
683   } while (MultiRotate && canRotateDeoptimizingLatchExit(L));
684 
685 
686   return true;
687 }
688 
689 /// Determine whether the instructions in this range may be safely and cheaply
690 /// speculated. This is not an important enough situation to develop complex
691 /// heuristics. We handle a single arithmetic instruction along with any type
692 /// conversions.
693 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
694                                   BasicBlock::iterator End, Loop *L) {
695   bool seenIncrement = false;
696   bool MultiExitLoop = false;
697 
698   if (!L->getExitingBlock())
699     MultiExitLoop = true;
700 
701   for (BasicBlock::iterator I = Begin; I != End; ++I) {
702 
703     if (!isSafeToSpeculativelyExecute(&*I))
704       return false;
705 
706     if (isa<DbgInfoIntrinsic>(I))
707       continue;
708 
709     switch (I->getOpcode()) {
710     default:
711       return false;
712     case Instruction::GetElementPtr:
713       // GEPs are cheap if all indices are constant.
714       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
715         return false;
716       // fall-thru to increment case
717       LLVM_FALLTHROUGH;
718     case Instruction::Add:
719     case Instruction::Sub:
720     case Instruction::And:
721     case Instruction::Or:
722     case Instruction::Xor:
723     case Instruction::Shl:
724     case Instruction::LShr:
725     case Instruction::AShr: {
726       Value *IVOpnd =
727           !isa<Constant>(I->getOperand(0))
728               ? I->getOperand(0)
729               : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
730       if (!IVOpnd)
731         return false;
732 
733       // If increment operand is used outside of the loop, this speculation
734       // could cause extra live range interference.
735       if (MultiExitLoop) {
736         for (User *UseI : IVOpnd->users()) {
737           auto *UserInst = cast<Instruction>(UseI);
738           if (!L->contains(UserInst))
739             return false;
740         }
741       }
742 
743       if (seenIncrement)
744         return false;
745       seenIncrement = true;
746       break;
747     }
748     case Instruction::Trunc:
749     case Instruction::ZExt:
750     case Instruction::SExt:
751       // ignore type conversions
752       break;
753     }
754   }
755   return true;
756 }
757 
758 /// Fold the loop tail into the loop exit by speculating the loop tail
759 /// instructions. Typically, this is a single post-increment. In the case of a
760 /// simple 2-block loop, hoisting the increment can be much better than
761 /// duplicating the entire loop header. In the case of loops with early exits,
762 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
763 /// canonical form so downstream passes can handle it.
764 ///
765 /// I don't believe this invalidates SCEV.
766 bool LoopRotate::simplifyLoopLatch(Loop *L) {
767   BasicBlock *Latch = L->getLoopLatch();
768   if (!Latch || Latch->hasAddressTaken())
769     return false;
770 
771   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
772   if (!Jmp || !Jmp->isUnconditional())
773     return false;
774 
775   BasicBlock *LastExit = Latch->getSinglePredecessor();
776   if (!LastExit || !L->isLoopExiting(LastExit))
777     return false;
778 
779   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
780   if (!BI)
781     return false;
782 
783   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
784     return false;
785 
786   LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
787                     << LastExit->getName() << "\n");
788 
789   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
790   MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
791                             /*PredecessorWithTwoSuccessors=*/true);
792 
793   if (MSSAU && VerifyMemorySSA)
794     MSSAU->getMemorySSA()->verifyMemorySSA();
795 
796   return true;
797 }
798 
799 /// Rotate \c L, and return true if any modification was made.
800 bool LoopRotate::processLoop(Loop *L) {
801   // Save the loop metadata.
802   MDNode *LoopMD = L->getLoopID();
803 
804   bool SimplifiedLatch = false;
805 
806   // Simplify the loop latch before attempting to rotate the header
807   // upward. Rotation may not be needed if the loop tail can be folded into the
808   // loop exit.
809   if (!RotationOnly)
810     SimplifiedLatch = simplifyLoopLatch(L);
811 
812   bool MadeChange = rotateLoop(L, SimplifiedLatch);
813   assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
814          "Loop latch should be exiting after loop-rotate.");
815 
816   // Restore the loop metadata.
817   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
818   if ((MadeChange || SimplifiedLatch) && LoopMD)
819     L->setLoopID(LoopMD);
820 
821   return MadeChange || SimplifiedLatch;
822 }
823 
824 
825 /// The utility to convert a loop into a loop with bottom test.
826 bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
827                         AssumptionCache *AC, DominatorTree *DT,
828                         ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
829                         const SimplifyQuery &SQ, bool RotationOnly = true,
830                         unsigned Threshold = unsigned(-1),
831                         bool IsUtilMode = true, bool PrepareForLTO) {
832   LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
833                 IsUtilMode, PrepareForLTO);
834   return LR.processLoop(L);
835 }
836