xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Utils/LoopRotationUtils.cpp (revision 725a9f47324d42037db93c27ceb40d4956872f3e)
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/CodeMetrics.h"
17 #include "llvm/Analysis/DomTreeUpdater.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/MemorySSA.h"
21 #include "llvm/Analysis/MemorySSAUpdater.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/MDBuilder.h"
29 #include "llvm/IR/ProfDataUtils.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/Cloning.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Transforms/Utils/SSAUpdater.h"
37 #include "llvm/Transforms/Utils/ValueMapper.h"
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "loop-rotate"
41 
42 STATISTIC(NumNotRotatedDueToHeaderSize,
43           "Number of loops not rotated due to the header size");
44 STATISTIC(NumInstrsHoisted,
45           "Number of instructions hoisted into loop preheader");
46 STATISTIC(NumInstrsDuplicated,
47           "Number of instructions cloned into loop preheader");
48 STATISTIC(NumRotated, "Number of loops rotated");
49 
50 static cl::opt<bool>
51     MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
52                 cl::desc("Allow loop rotation multiple times in order to reach "
53                          "a better latch exit"));
54 
55 // Probability that a rotated loop has zero trip count / is never entered.
56 static constexpr uint32_t ZeroTripCountWeights[] = {1, 127};
57 
58 namespace {
59 /// A simple loop rotation transformation.
60 class LoopRotate {
61   const unsigned MaxHeaderSize;
62   LoopInfo *LI;
63   const TargetTransformInfo *TTI;
64   AssumptionCache *AC;
65   DominatorTree *DT;
66   ScalarEvolution *SE;
67   MemorySSAUpdater *MSSAU;
68   const SimplifyQuery &SQ;
69   bool RotationOnly;
70   bool IsUtilMode;
71   bool PrepareForLTO;
72 
73 public:
74   LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
75              const TargetTransformInfo *TTI, AssumptionCache *AC,
76              DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
77              const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
78              bool PrepareForLTO)
79       : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
80         MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
81         IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
82   bool processLoop(Loop *L);
83 
84 private:
85   bool rotateLoop(Loop *L, bool SimplifiedLatch);
86   bool simplifyLoopLatch(Loop *L);
87 };
88 } // end anonymous namespace
89 
90 /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
91 /// previously exist in the map, and the value was inserted.
92 static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) {
93   bool Inserted = VM.insert({K, V}).second;
94   assert(Inserted);
95   (void)Inserted;
96 }
97 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
98 /// old header into the preheader.  If there were uses of the values produced by
99 /// these instruction that were outside of the loop, we have to insert PHI nodes
100 /// to merge the two values.  Do this now.
101 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
102                                             BasicBlock *OrigPreheader,
103                                             ValueToValueMapTy &ValueMap,
104                                             ScalarEvolution *SE,
105                                 SmallVectorImpl<PHINode*> *InsertedPHIs) {
106   // Remove PHI node entries that are no longer live.
107   BasicBlock::iterator I, E = OrigHeader->end();
108   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
109     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
110 
111   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
112   // as necessary.
113   SSAUpdater SSA(InsertedPHIs);
114   for (I = OrigHeader->begin(); I != E; ++I) {
115     Value *OrigHeaderVal = &*I;
116 
117     // If there are no uses of the value (e.g. because it returns void), there
118     // is nothing to rewrite.
119     if (OrigHeaderVal->use_empty())
120       continue;
121 
122     Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
123 
124     // The value now exits in two versions: the initial value in the preheader
125     // and the loop "next" value in the original header.
126     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
127     // Force re-computation of OrigHeaderVal, as some users now need to use the
128     // new PHI node.
129     if (SE)
130       SE->forgetValue(OrigHeaderVal);
131     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
132     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
133 
134     // Visit each use of the OrigHeader instruction.
135     for (Use &U : llvm::make_early_inc_range(OrigHeaderVal->uses())) {
136       // SSAUpdater can't handle a non-PHI use in the same block as an
137       // earlier def. We can easily handle those cases manually.
138       Instruction *UserInst = cast<Instruction>(U.getUser());
139       if (!isa<PHINode>(UserInst)) {
140         BasicBlock *UserBB = UserInst->getParent();
141 
142         // The original users in the OrigHeader are already using the
143         // original definitions.
144         if (UserBB == OrigHeader)
145           continue;
146 
147         // Users in the OrigPreHeader need to use the value to which the
148         // original definitions are mapped.
149         if (UserBB == OrigPreheader) {
150           U = OrigPreHeaderVal;
151           continue;
152         }
153       }
154 
155       // Anything else can be handled by SSAUpdater.
156       SSA.RewriteUse(U);
157     }
158 
159     // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
160     // intrinsics.
161     SmallVector<DbgValueInst *, 1> DbgValues;
162     SmallVector<DPValue *, 1> DPValues;
163     llvm::findDbgValues(DbgValues, OrigHeaderVal, &DPValues);
164     for (auto &DbgValue : DbgValues) {
165       // The original users in the OrigHeader are already using the original
166       // definitions.
167       BasicBlock *UserBB = DbgValue->getParent();
168       if (UserBB == OrigHeader)
169         continue;
170 
171       // Users in the OrigPreHeader need to use the value to which the
172       // original definitions are mapped and anything else can be handled by
173       // the SSAUpdater. To avoid adding PHINodes, check if the value is
174       // available in UserBB, if not substitute undef.
175       Value *NewVal;
176       if (UserBB == OrigPreheader)
177         NewVal = OrigPreHeaderVal;
178       else if (SSA.HasValueForBlock(UserBB))
179         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
180       else
181         NewVal = UndefValue::get(OrigHeaderVal->getType());
182       DbgValue->replaceVariableLocationOp(OrigHeaderVal, NewVal);
183     }
184 
185     // RemoveDIs: duplicate implementation for non-instruction debug-info
186     // storage in DPValues.
187     for (DPValue *DPV : DPValues) {
188       // The original users in the OrigHeader are already using the original
189       // definitions.
190       BasicBlock *UserBB = DPV->getMarker()->getParent();
191       if (UserBB == OrigHeader)
192         continue;
193 
194       // Users in the OrigPreHeader need to use the value to which the
195       // original definitions are mapped and anything else can be handled by
196       // the SSAUpdater. To avoid adding PHINodes, check if the value is
197       // available in UserBB, if not substitute undef.
198       Value *NewVal;
199       if (UserBB == OrigPreheader)
200         NewVal = OrigPreHeaderVal;
201       else if (SSA.HasValueForBlock(UserBB))
202         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
203       else
204         NewVal = UndefValue::get(OrigHeaderVal->getType());
205       DPV->replaceVariableLocationOp(OrigHeaderVal, NewVal);
206     }
207   }
208 }
209 
210 // Assuming both header and latch are exiting, look for a phi which is only
211 // used outside the loop (via a LCSSA phi) in the exit from the header.
212 // This means that rotating the loop can remove the phi.
213 static bool profitableToRotateLoopExitingLatch(Loop *L) {
214   BasicBlock *Header = L->getHeader();
215   BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
216   assert(BI && BI->isConditional() && "need header with conditional exit");
217   BasicBlock *HeaderExit = BI->getSuccessor(0);
218   if (L->contains(HeaderExit))
219     HeaderExit = BI->getSuccessor(1);
220 
221   for (auto &Phi : Header->phis()) {
222     // Look for uses of this phi in the loop/via exits other than the header.
223     if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
224           return cast<Instruction>(U)->getParent() != HeaderExit;
225         }))
226       continue;
227     return true;
228   }
229   return false;
230 }
231 
232 // Check that latch exit is deoptimizing (which means - very unlikely to happen)
233 // and there is another exit from the loop which is non-deoptimizing.
234 // If we rotate latch to that exit our loop has a better chance of being fully
235 // canonical.
236 //
237 // It can give false positives in some rare cases.
238 static bool canRotateDeoptimizingLatchExit(Loop *L) {
239   BasicBlock *Latch = L->getLoopLatch();
240   assert(Latch && "need latch");
241   BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
242   // Need normal exiting latch.
243   if (!BI || !BI->isConditional())
244     return false;
245 
246   BasicBlock *Exit = BI->getSuccessor(1);
247   if (L->contains(Exit))
248     Exit = BI->getSuccessor(0);
249 
250   // Latch exit is non-deoptimizing, no need to rotate.
251   if (!Exit->getPostdominatingDeoptimizeCall())
252     return false;
253 
254   SmallVector<BasicBlock *, 4> Exits;
255   L->getUniqueExitBlocks(Exits);
256   if (!Exits.empty()) {
257     // There is at least one non-deoptimizing exit.
258     //
259     // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
260     // as it can conservatively return false for deoptimizing exits with
261     // complex enough control flow down to deoptimize call.
262     //
263     // That means here we can report success for a case where
264     // all exits are deoptimizing but one of them has complex enough
265     // control flow (e.g. with loops).
266     //
267     // That should be a very rare case and false positives for this function
268     // have compile-time effect only.
269     return any_of(Exits, [](const BasicBlock *BB) {
270       return !BB->getPostdominatingDeoptimizeCall();
271     });
272   }
273   return false;
274 }
275 
276 static void updateBranchWeights(BranchInst &PreHeaderBI, BranchInst &LoopBI,
277                                 bool HasConditionalPreHeader,
278                                 bool SuccsSwapped) {
279   MDNode *WeightMD = getBranchWeightMDNode(PreHeaderBI);
280   if (WeightMD == nullptr)
281     return;
282 
283   // LoopBI should currently be a clone of PreHeaderBI with the same
284   // metadata. But we double check to make sure we don't have a degenerate case
285   // where instsimplify changed the instructions.
286   if (WeightMD != getBranchWeightMDNode(LoopBI))
287     return;
288 
289   SmallVector<uint32_t, 2> Weights;
290   extractFromBranchWeightMD(WeightMD, Weights);
291   if (Weights.size() != 2)
292     return;
293   uint32_t OrigLoopExitWeight = Weights[0];
294   uint32_t OrigLoopBackedgeWeight = Weights[1];
295 
296   if (SuccsSwapped)
297     std::swap(OrigLoopExitWeight, OrigLoopBackedgeWeight);
298 
299   // Update branch weights. Consider the following edge-counts:
300   //
301   //    |  |--------             |
302   //    V  V       |             V
303   //   Br i1 ...   |            Br i1 ...
304   //   |       |   |            |     |
305   //  x|      y|   |  becomes:  |   y0|  |-----
306   //   V       V   |            |     V  V    |
307   // Exit    Loop  |            |    Loop     |
308   //           |   |            |   Br i1 ... |
309   //           -----            |   |      |  |
310   //                          x0| x1|   y1 |  |
311   //                            V   V      ----
312   //                            Exit
313   //
314   // The following must hold:
315   //  -  x == x0 + x1        # counts to "exit" must stay the same.
316   //  - y0 == x - x0 == x1   # how often loop was entered at all.
317   //  - y1 == y - y0         # How often loop was repeated (after first iter.).
318   //
319   // We cannot generally deduce how often we had a zero-trip count loop so we
320   // have to make a guess for how to distribute x among the new x0 and x1.
321 
322   uint32_t ExitWeight0;    // aka x0
323   uint32_t ExitWeight1;    // aka x1
324   uint32_t EnterWeight;    // aka y0
325   uint32_t LoopBackWeight; // aka y1
326   if (OrigLoopExitWeight > 0 && OrigLoopBackedgeWeight > 0) {
327     ExitWeight0 = 0;
328     if (HasConditionalPreHeader) {
329       // Here we cannot know how many 0-trip count loops we have, so we guess:
330       if (OrigLoopBackedgeWeight >= OrigLoopExitWeight) {
331         // If the loop count is bigger than the exit count then we set
332         // probabilities as if 0-trip count nearly never happens.
333         ExitWeight0 = ZeroTripCountWeights[0];
334         // Scale up counts if necessary so we can match `ZeroTripCountWeights`
335         // for the `ExitWeight0`:`ExitWeight1` (aka `x0`:`x1` ratio`) ratio.
336         while (OrigLoopExitWeight < ZeroTripCountWeights[1] + ExitWeight0) {
337           // ... but don't overflow.
338           uint32_t const HighBit = uint32_t{1} << (sizeof(uint32_t) * 8 - 1);
339           if ((OrigLoopBackedgeWeight & HighBit) != 0 ||
340               (OrigLoopExitWeight & HighBit) != 0)
341             break;
342           OrigLoopBackedgeWeight <<= 1;
343           OrigLoopExitWeight <<= 1;
344         }
345       } else {
346         // If there's a higher exit-count than backedge-count then we set
347         // probabilities as if there are only 0-trip and 1-trip cases.
348         ExitWeight0 = OrigLoopExitWeight - OrigLoopBackedgeWeight;
349       }
350     }
351     ExitWeight1 = OrigLoopExitWeight - ExitWeight0;
352     EnterWeight = ExitWeight1;
353     LoopBackWeight = OrigLoopBackedgeWeight - EnterWeight;
354   } else if (OrigLoopExitWeight == 0) {
355     if (OrigLoopBackedgeWeight == 0) {
356       // degenerate case... keep everything zero...
357       ExitWeight0 = 0;
358       ExitWeight1 = 0;
359       EnterWeight = 0;
360       LoopBackWeight = 0;
361     } else {
362       // Special case "LoopExitWeight == 0" weights which behaves like an
363       // endless where we don't want loop-enttry (y0) to be the same as
364       // loop-exit (x1).
365       ExitWeight0 = 0;
366       ExitWeight1 = 0;
367       EnterWeight = 1;
368       LoopBackWeight = OrigLoopBackedgeWeight;
369     }
370   } else {
371     // loop is never entered.
372     assert(OrigLoopBackedgeWeight == 0 && "remaining case is backedge zero");
373     ExitWeight0 = 1;
374     ExitWeight1 = 1;
375     EnterWeight = 0;
376     LoopBackWeight = 0;
377   }
378 
379   const uint32_t LoopBIWeights[] = {
380       SuccsSwapped ? LoopBackWeight : ExitWeight1,
381       SuccsSwapped ? ExitWeight1 : LoopBackWeight,
382   };
383   setBranchWeights(LoopBI, LoopBIWeights);
384   if (HasConditionalPreHeader) {
385     const uint32_t PreHeaderBIWeights[] = {
386         SuccsSwapped ? EnterWeight : ExitWeight0,
387         SuccsSwapped ? ExitWeight0 : EnterWeight,
388     };
389     setBranchWeights(PreHeaderBI, PreHeaderBIWeights);
390   }
391 }
392 
393 /// Rotate loop LP. Return true if the loop is rotated.
394 ///
395 /// \param SimplifiedLatch is true if the latch was just folded into the final
396 /// loop exit. In this case we may want to rotate even though the new latch is
397 /// now an exiting branch. This rotation would have happened had the latch not
398 /// been simplified. However, if SimplifiedLatch is false, then we avoid
399 /// rotating loops in which the latch exits to avoid excessive or endless
400 /// rotation. LoopRotate should be repeatable and converge to a canonical
401 /// form. This property is satisfied because simplifying the loop latch can only
402 /// happen once across multiple invocations of the LoopRotate pass.
403 ///
404 /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
405 /// so to reach a suitable (non-deoptimizing) exit.
406 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
407   // If the loop has only one block then there is not much to rotate.
408   if (L->getBlocks().size() == 1)
409     return false;
410 
411   bool Rotated = false;
412   do {
413     BasicBlock *OrigHeader = L->getHeader();
414     BasicBlock *OrigLatch = L->getLoopLatch();
415 
416     BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
417     if (!BI || BI->isUnconditional())
418       return Rotated;
419 
420     // If the loop header is not one of the loop exiting blocks then
421     // either this loop is already rotated or it is not
422     // suitable for loop rotation transformations.
423     if (!L->isLoopExiting(OrigHeader))
424       return Rotated;
425 
426     // If the loop latch already contains a branch that leaves the loop then the
427     // loop is already rotated.
428     if (!OrigLatch)
429       return Rotated;
430 
431     // Rotate if either the loop latch does *not* exit the loop, or if the loop
432     // latch was just simplified. Or if we think it will be profitable.
433     if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
434         !profitableToRotateLoopExitingLatch(L) &&
435         !canRotateDeoptimizingLatchExit(L))
436       return Rotated;
437 
438     // Check size of original header and reject loop if it is very big or we can't
439     // duplicate blocks inside it.
440     {
441       SmallPtrSet<const Value *, 32> EphValues;
442       CodeMetrics::collectEphemeralValues(L, AC, EphValues);
443 
444       CodeMetrics Metrics;
445       Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
446       if (Metrics.notDuplicatable) {
447         LLVM_DEBUG(
448                    dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
449                    << " instructions: ";
450                    L->dump());
451         return Rotated;
452       }
453       if (Metrics.convergent) {
454         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
455                    "instructions: ";
456                    L->dump());
457         return Rotated;
458       }
459       if (!Metrics.NumInsts.isValid()) {
460         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains instructions"
461                    " with invalid cost: ";
462                    L->dump());
463         return Rotated;
464       }
465       if (Metrics.NumInsts > MaxHeaderSize) {
466         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
467                           << Metrics.NumInsts
468                           << " instructions, which is more than the threshold ("
469                           << MaxHeaderSize << " instructions): ";
470                    L->dump());
471         ++NumNotRotatedDueToHeaderSize;
472         return Rotated;
473       }
474 
475       // When preparing for LTO, avoid rotating loops with calls that could be
476       // inlined during the LTO stage.
477       if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
478         return Rotated;
479     }
480 
481     // Now, this loop is suitable for rotation.
482     BasicBlock *OrigPreheader = L->getLoopPreheader();
483 
484     // If the loop could not be converted to canonical form, it must have an
485     // indirectbr in it, just give up.
486     if (!OrigPreheader || !L->hasDedicatedExits())
487       return Rotated;
488 
489     // Anything ScalarEvolution may know about this loop or the PHI nodes
490     // in its header will soon be invalidated. We should also invalidate
491     // all outer loops because insertion and deletion of blocks that happens
492     // during the rotation may violate invariants related to backedge taken
493     // infos in them.
494     if (SE) {
495       SE->forgetTopmostLoop(L);
496       // We may hoist some instructions out of loop. In case if they were cached
497       // as "loop variant" or "loop computable", these caches must be dropped.
498       // We also may fold basic blocks, so cached block dispositions also need
499       // to be dropped.
500       SE->forgetBlockAndLoopDispositions();
501     }
502 
503     LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
504     if (MSSAU && VerifyMemorySSA)
505       MSSAU->getMemorySSA()->verifyMemorySSA();
506 
507     // Find new Loop header. NewHeader is a Header's one and only successor
508     // that is inside loop.  Header's other successor is outside the
509     // loop.  Otherwise loop is not suitable for rotation.
510     BasicBlock *Exit = BI->getSuccessor(0);
511     BasicBlock *NewHeader = BI->getSuccessor(1);
512     bool BISuccsSwapped = L->contains(Exit);
513     if (BISuccsSwapped)
514       std::swap(Exit, NewHeader);
515     assert(NewHeader && "Unable to determine new loop header");
516     assert(L->contains(NewHeader) && !L->contains(Exit) &&
517            "Unable to determine loop header and exit blocks");
518 
519     // This code assumes that the new header has exactly one predecessor.
520     // Remove any single-entry PHI nodes in it.
521     assert(NewHeader->getSinglePredecessor() &&
522            "New header doesn't have one pred!");
523     FoldSingleEntryPHINodes(NewHeader);
524 
525     // Begin by walking OrigHeader and populating ValueMap with an entry for
526     // each Instruction.
527     BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
528     ValueToValueMapTy ValueMap, ValueMapMSSA;
529 
530     // For PHI nodes, the value available in OldPreHeader is just the
531     // incoming value from OldPreHeader.
532     for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
533       InsertNewValueIntoMap(ValueMap, PN,
534                             PN->getIncomingValueForBlock(OrigPreheader));
535 
536     // For the rest of the instructions, either hoist to the OrigPreheader if
537     // possible or create a clone in the OldPreHeader if not.
538     Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
539 
540     // Record all debug intrinsics preceding LoopEntryBranch to avoid
541     // duplication.
542     using DbgIntrinsicHash =
543         std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
544     auto makeHash = [](auto *D) -> DbgIntrinsicHash {
545       auto VarLocOps = D->location_ops();
546       return {{hash_combine_range(VarLocOps.begin(), VarLocOps.end()),
547                D->getVariable()},
548               D->getExpression()};
549     };
550 
551     SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
552     for (Instruction &I : llvm::drop_begin(llvm::reverse(*OrigPreheader))) {
553       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
554         DbgIntrinsics.insert(makeHash(DII));
555         // Until RemoveDIs supports dbg.declares in DPValue format, we'll need
556         // to collect DPValues attached to any other debug intrinsics.
557         for (const DPValue &DPV : DII->getDbgValueRange())
558           DbgIntrinsics.insert(makeHash(&DPV));
559       } else {
560         break;
561       }
562     }
563 
564     // Build DPValue hashes for DPValues attached to the terminator, which isn't
565     // considered in the loop above.
566     for (const DPValue &DPV :
567          OrigPreheader->getTerminator()->getDbgValueRange())
568       DbgIntrinsics.insert(makeHash(&DPV));
569 
570     // Remember the local noalias scope declarations in the header. After the
571     // rotation, they must be duplicated and the scope must be cloned. This
572     // avoids unwanted interaction across iterations.
573     SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
574     for (Instruction &I : *OrigHeader)
575       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
576         NoAliasDeclInstructions.push_back(Decl);
577 
578     Module *M = OrigHeader->getModule();
579 
580     // Track the next DPValue to clone. If we have a sequence where an
581     // instruction is hoisted instead of being cloned:
582     //    DPValue blah
583     //    %foo = add i32 0, 0
584     //    DPValue xyzzy
585     //    %bar = call i32 @foobar()
586     // where %foo is hoisted, then the DPValue "blah" will be seen twice, once
587     // attached to %foo, then when %foo his hoisted it will "fall down" onto the
588     // function call:
589     //    DPValue blah
590     //    DPValue xyzzy
591     //    %bar = call i32 @foobar()
592     // causing it to appear attached to the call too.
593     //
594     // To avoid this, cloneDebugInfoFrom takes an optional "start cloning from
595     // here" position to account for this behaviour. We point it at any DPValues
596     // on the next instruction, here labelled xyzzy, before we hoist %foo.
597     // Later, we only only clone DPValues from that position (xyzzy) onwards,
598     // which avoids cloning DPValue "blah" multiple times.
599     std::optional<DPValue::self_iterator> NextDbgInst = std::nullopt;
600 
601     while (I != E) {
602       Instruction *Inst = &*I++;
603 
604       // If the instruction's operands are invariant and it doesn't read or write
605       // memory, then it is safe to hoist.  Doing this doesn't change the order of
606       // execution in the preheader, but does prevent the instruction from
607       // executing in each iteration of the loop.  This means it is safe to hoist
608       // something that might trap, but isn't safe to hoist something that reads
609       // memory (without proving that the loop doesn't write).
610       if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
611           !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
612           !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
613 
614         if (LoopEntryBranch->getParent()->IsNewDbgInfoFormat) {
615           auto DbgValueRange =
616               LoopEntryBranch->cloneDebugInfoFrom(Inst, NextDbgInst);
617           RemapDPValueRange(M, DbgValueRange, ValueMap,
618                             RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
619           // Erase anything we've seen before.
620           for (DPValue &DPV : make_early_inc_range(DbgValueRange))
621             if (DbgIntrinsics.count(makeHash(&DPV)))
622               DPV.eraseFromParent();
623         }
624 
625         NextDbgInst = I->getDbgValueRange().begin();
626         Inst->moveBefore(LoopEntryBranch);
627 
628         ++NumInstrsHoisted;
629         continue;
630       }
631 
632       // Otherwise, create a duplicate of the instruction.
633       Instruction *C = Inst->clone();
634       C->insertBefore(LoopEntryBranch);
635 
636       ++NumInstrsDuplicated;
637 
638       if (LoopEntryBranch->getParent()->IsNewDbgInfoFormat) {
639         auto Range = C->cloneDebugInfoFrom(Inst, NextDbgInst);
640         RemapDPValueRange(M, Range, ValueMap,
641                           RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
642         NextDbgInst = std::nullopt;
643         // Erase anything we've seen before.
644         for (DPValue &DPV : make_early_inc_range(Range))
645           if (DbgIntrinsics.count(makeHash(&DPV)))
646             DPV.eraseFromParent();
647       }
648 
649       // Eagerly remap the operands of the instruction.
650       RemapInstruction(C, ValueMap,
651                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
652 
653       // Avoid inserting the same intrinsic twice.
654       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
655         if (DbgIntrinsics.count(makeHash(DII))) {
656           C->eraseFromParent();
657           continue;
658         }
659 
660       // With the operands remapped, see if the instruction constant folds or is
661       // otherwise simplifyable.  This commonly occurs because the entry from PHI
662       // nodes allows icmps and other instructions to fold.
663       Value *V = simplifyInstruction(C, SQ);
664       if (V && LI->replacementPreservesLCSSAForm(C, V)) {
665         // If so, then delete the temporary instruction and stick the folded value
666         // in the map.
667         InsertNewValueIntoMap(ValueMap, Inst, V);
668         if (!C->mayHaveSideEffects()) {
669           C->eraseFromParent();
670           C = nullptr;
671         }
672       } else {
673         InsertNewValueIntoMap(ValueMap, Inst, C);
674       }
675       if (C) {
676         // Otherwise, stick the new instruction into the new block!
677         C->setName(Inst->getName());
678 
679         if (auto *II = dyn_cast<AssumeInst>(C))
680           AC->registerAssumption(II);
681         // MemorySSA cares whether the cloned instruction was inserted or not, and
682         // not whether it can be remapped to a simplified value.
683         if (MSSAU)
684           InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
685       }
686     }
687 
688     if (!NoAliasDeclInstructions.empty()) {
689       // There are noalias scope declarations:
690       // (general):
691       // Original:    OrigPre              { OrigHeader NewHeader ... Latch }
692       // after:      (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
693       //
694       // with D: llvm.experimental.noalias.scope.decl,
695       //      U: !noalias or !alias.scope depending on D
696       //       ... { D U1 U2 }   can transform into:
697       // (0) : ... { D U1 U2 }        // no relevant rotation for this part
698       // (1) : ... D' { U1 U2 D }     // D is part of OrigHeader
699       // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
700       //
701       // We now want to transform:
702       // (1) -> : ... D' { D U1 U2 D'' }
703       // (2) -> : ... D' U1' { D U2 D'' U1'' }
704       // D: original llvm.experimental.noalias.scope.decl
705       // D', U1': duplicate with replaced scopes
706       // D'', U1'': different duplicate with replaced scopes
707       // This ensures a safe fallback to 'may_alias' introduced by the rotate,
708       // as U1'' and U1' scopes will not be compatible wrt to the local restrict
709 
710       // Clone the llvm.experimental.noalias.decl again for the NewHeader.
711       BasicBlock::iterator NewHeaderInsertionPoint =
712           NewHeader->getFirstNonPHIIt();
713       for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
714         LLVM_DEBUG(dbgs() << "  Cloning llvm.experimental.noalias.scope.decl:"
715                           << *NAD << "\n");
716         Instruction *NewNAD = NAD->clone();
717         NewNAD->insertBefore(*NewHeader, NewHeaderInsertionPoint);
718       }
719 
720       // Scopes must now be duplicated, once for OrigHeader and once for
721       // OrigPreHeader'.
722       {
723         auto &Context = NewHeader->getContext();
724 
725         SmallVector<MDNode *, 8> NoAliasDeclScopes;
726         for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
727           NoAliasDeclScopes.push_back(NAD->getScopeList());
728 
729         LLVM_DEBUG(dbgs() << "  Updating OrigHeader scopes\n");
730         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
731                                    "h.rot");
732         LLVM_DEBUG(OrigHeader->dump());
733 
734         // Keep the compile time impact low by only adapting the inserted block
735         // of instructions in the OrigPreHeader. This might result in slightly
736         // more aliasing between these instructions and those that were already
737         // present, but it will be much faster when the original PreHeader is
738         // large.
739         LLVM_DEBUG(dbgs() << "  Updating part of OrigPreheader scopes\n");
740         auto *FirstDecl =
741             cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
742         auto *LastInst = &OrigPreheader->back();
743         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
744                                    Context, "pre.rot");
745         LLVM_DEBUG(OrigPreheader->dump());
746 
747         LLVM_DEBUG(dbgs() << "  Updated NewHeader:\n");
748         LLVM_DEBUG(NewHeader->dump());
749       }
750     }
751 
752     // Along with all the other instructions, we just cloned OrigHeader's
753     // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
754     // successors by duplicating their incoming values for OrigHeader.
755     for (BasicBlock *SuccBB : successors(OrigHeader))
756       for (BasicBlock::iterator BI = SuccBB->begin();
757            PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
758         PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
759 
760     // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
761     // OrigPreHeader's old terminator (the original branch into the loop), and
762     // remove the corresponding incoming values from the PHI nodes in OrigHeader.
763     LoopEntryBranch->eraseFromParent();
764     OrigPreheader->flushTerminatorDbgValues();
765 
766     // Update MemorySSA before the rewrite call below changes the 1:1
767     // instruction:cloned_instruction_or_value mapping.
768     if (MSSAU) {
769       InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
770       MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
771                                           ValueMapMSSA);
772     }
773 
774     SmallVector<PHINode*, 2> InsertedPHIs;
775     // If there were any uses of instructions in the duplicated block outside the
776     // loop, update them, inserting PHI nodes as required
777     RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
778                                     &InsertedPHIs);
779 
780     // Attach dbg.value intrinsics to the new phis if that phi uses a value that
781     // previously had debug metadata attached. This keeps the debug info
782     // up-to-date in the loop body.
783     if (!InsertedPHIs.empty())
784       insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
785 
786     // NewHeader is now the header of the loop.
787     L->moveToHeader(NewHeader);
788     assert(L->getHeader() == NewHeader && "Latch block is our new header");
789 
790     // Inform DT about changes to the CFG.
791     if (DT) {
792       // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
793       // the DT about the removed edge to the OrigHeader (that got removed).
794       SmallVector<DominatorTree::UpdateType, 3> Updates;
795       Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
796       Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
797       Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
798 
799       if (MSSAU) {
800         MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
801         if (VerifyMemorySSA)
802           MSSAU->getMemorySSA()->verifyMemorySSA();
803       } else {
804         DT->applyUpdates(Updates);
805       }
806     }
807 
808     // At this point, we've finished our major CFG changes.  As part of cloning
809     // the loop into the preheader we've simplified instructions and the
810     // duplicated conditional branch may now be branching on a constant.  If it is
811     // branching on a constant and if that constant means that we enter the loop,
812     // then we fold away the cond branch to an uncond branch.  This simplifies the
813     // loop in cases important for nested loops, and it also means we don't have
814     // to split as many edges.
815     BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
816     assert(PHBI->isConditional() && "Should be clone of BI condbr!");
817     const Value *Cond = PHBI->getCondition();
818     const bool HasConditionalPreHeader =
819         !isa<ConstantInt>(Cond) ||
820         PHBI->getSuccessor(cast<ConstantInt>(Cond)->isZero()) != NewHeader;
821 
822     updateBranchWeights(*PHBI, *BI, HasConditionalPreHeader, BISuccsSwapped);
823 
824     if (HasConditionalPreHeader) {
825       // The conditional branch can't be folded, handle the general case.
826       // Split edges as necessary to preserve LoopSimplify form.
827 
828       // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
829       // thus is not a preheader anymore.
830       // Split the edge to form a real preheader.
831       BasicBlock *NewPH = SplitCriticalEdge(
832                                             OrigPreheader, NewHeader,
833                                             CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
834       NewPH->setName(NewHeader->getName() + ".lr.ph");
835 
836       // Preserve canonical loop form, which means that 'Exit' should have only
837       // one predecessor. Note that Exit could be an exit block for multiple
838       // nested loops, causing both of the edges to now be critical and need to
839       // be split.
840       SmallVector<BasicBlock *, 4> ExitPreds(predecessors(Exit));
841       bool SplitLatchEdge = false;
842       for (BasicBlock *ExitPred : ExitPreds) {
843         // We only need to split loop exit edges.
844         Loop *PredLoop = LI->getLoopFor(ExitPred);
845         if (!PredLoop || PredLoop->contains(Exit) ||
846             isa<IndirectBrInst>(ExitPred->getTerminator()))
847           continue;
848         SplitLatchEdge |= L->getLoopLatch() == ExitPred;
849         BasicBlock *ExitSplit = SplitCriticalEdge(
850                                                   ExitPred, Exit,
851                                                   CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
852         ExitSplit->moveBefore(Exit);
853       }
854       assert(SplitLatchEdge &&
855              "Despite splitting all preds, failed to split latch exit?");
856       (void)SplitLatchEdge;
857     } else {
858       // We can fold the conditional branch in the preheader, this makes things
859       // simpler. The first step is to remove the extra edge to the Exit block.
860       Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
861       BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
862       NewBI->setDebugLoc(PHBI->getDebugLoc());
863       PHBI->eraseFromParent();
864 
865       // With our CFG finalized, update DomTree if it is available.
866       if (DT) DT->deleteEdge(OrigPreheader, Exit);
867 
868       // Update MSSA too, if available.
869       if (MSSAU)
870         MSSAU->removeEdge(OrigPreheader, Exit);
871     }
872 
873     assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
874     assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
875 
876     if (MSSAU && VerifyMemorySSA)
877       MSSAU->getMemorySSA()->verifyMemorySSA();
878 
879     // Now that the CFG and DomTree are in a consistent state again, try to merge
880     // the OrigHeader block into OrigLatch.  This will succeed if they are
881     // connected by an unconditional branch.  This is just a cleanup so the
882     // emitted code isn't too gross in this common case.
883     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
884     BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
885     bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
886     if (DidMerge)
887       RemoveRedundantDbgInstrs(PredBB);
888 
889     if (MSSAU && VerifyMemorySSA)
890       MSSAU->getMemorySSA()->verifyMemorySSA();
891 
892     LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
893 
894     ++NumRotated;
895 
896     Rotated = true;
897     SimplifiedLatch = false;
898 
899     // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
900     // Deoptimizing latch exit is not a generally typical case, so we just loop over.
901     // TODO: if it becomes a performance bottleneck extend rotation algorithm
902     // to handle multiple rotations in one go.
903   } while (MultiRotate && canRotateDeoptimizingLatchExit(L));
904 
905 
906   return true;
907 }
908 
909 /// Determine whether the instructions in this range may be safely and cheaply
910 /// speculated. This is not an important enough situation to develop complex
911 /// heuristics. We handle a single arithmetic instruction along with any type
912 /// conversions.
913 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
914                                   BasicBlock::iterator End, Loop *L) {
915   bool seenIncrement = false;
916   bool MultiExitLoop = false;
917 
918   if (!L->getExitingBlock())
919     MultiExitLoop = true;
920 
921   for (BasicBlock::iterator I = Begin; I != End; ++I) {
922 
923     if (!isSafeToSpeculativelyExecute(&*I))
924       return false;
925 
926     if (isa<DbgInfoIntrinsic>(I))
927       continue;
928 
929     switch (I->getOpcode()) {
930     default:
931       return false;
932     case Instruction::GetElementPtr:
933       // GEPs are cheap if all indices are constant.
934       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
935         return false;
936       // fall-thru to increment case
937       [[fallthrough]];
938     case Instruction::Add:
939     case Instruction::Sub:
940     case Instruction::And:
941     case Instruction::Or:
942     case Instruction::Xor:
943     case Instruction::Shl:
944     case Instruction::LShr:
945     case Instruction::AShr: {
946       Value *IVOpnd =
947           !isa<Constant>(I->getOperand(0))
948               ? I->getOperand(0)
949               : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
950       if (!IVOpnd)
951         return false;
952 
953       // If increment operand is used outside of the loop, this speculation
954       // could cause extra live range interference.
955       if (MultiExitLoop) {
956         for (User *UseI : IVOpnd->users()) {
957           auto *UserInst = cast<Instruction>(UseI);
958           if (!L->contains(UserInst))
959             return false;
960         }
961       }
962 
963       if (seenIncrement)
964         return false;
965       seenIncrement = true;
966       break;
967     }
968     case Instruction::Trunc:
969     case Instruction::ZExt:
970     case Instruction::SExt:
971       // ignore type conversions
972       break;
973     }
974   }
975   return true;
976 }
977 
978 /// Fold the loop tail into the loop exit by speculating the loop tail
979 /// instructions. Typically, this is a single post-increment. In the case of a
980 /// simple 2-block loop, hoisting the increment can be much better than
981 /// duplicating the entire loop header. In the case of loops with early exits,
982 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
983 /// canonical form so downstream passes can handle it.
984 ///
985 /// I don't believe this invalidates SCEV.
986 bool LoopRotate::simplifyLoopLatch(Loop *L) {
987   BasicBlock *Latch = L->getLoopLatch();
988   if (!Latch || Latch->hasAddressTaken())
989     return false;
990 
991   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
992   if (!Jmp || !Jmp->isUnconditional())
993     return false;
994 
995   BasicBlock *LastExit = Latch->getSinglePredecessor();
996   if (!LastExit || !L->isLoopExiting(LastExit))
997     return false;
998 
999   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
1000   if (!BI)
1001     return false;
1002 
1003   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
1004     return false;
1005 
1006   LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
1007                     << LastExit->getName() << "\n");
1008 
1009   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
1010   MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
1011                             /*PredecessorWithTwoSuccessors=*/true);
1012 
1013     if (SE) {
1014       // Merging blocks may remove blocks reference in the block disposition cache. Clear the cache.
1015       SE->forgetBlockAndLoopDispositions();
1016     }
1017 
1018   if (MSSAU && VerifyMemorySSA)
1019     MSSAU->getMemorySSA()->verifyMemorySSA();
1020 
1021   return true;
1022 }
1023 
1024 /// Rotate \c L, and return true if any modification was made.
1025 bool LoopRotate::processLoop(Loop *L) {
1026   // Save the loop metadata.
1027   MDNode *LoopMD = L->getLoopID();
1028 
1029   bool SimplifiedLatch = false;
1030 
1031   // Simplify the loop latch before attempting to rotate the header
1032   // upward. Rotation may not be needed if the loop tail can be folded into the
1033   // loop exit.
1034   if (!RotationOnly)
1035     SimplifiedLatch = simplifyLoopLatch(L);
1036 
1037   bool MadeChange = rotateLoop(L, SimplifiedLatch);
1038   assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
1039          "Loop latch should be exiting after loop-rotate.");
1040 
1041   // Restore the loop metadata.
1042   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
1043   if ((MadeChange || SimplifiedLatch) && LoopMD)
1044     L->setLoopID(LoopMD);
1045 
1046   return MadeChange || SimplifiedLatch;
1047 }
1048 
1049 
1050 /// The utility to convert a loop into a loop with bottom test.
1051 bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
1052                         AssumptionCache *AC, DominatorTree *DT,
1053                         ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
1054                         const SimplifyQuery &SQ, bool RotationOnly = true,
1055                         unsigned Threshold = unsigned(-1),
1056                         bool IsUtilMode = true, bool PrepareForLTO) {
1057   LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
1058                 IsUtilMode, PrepareForLTO);
1059   return LR.processLoop(L);
1060 }
1061