10b57cec5SDimitry Andric //===----------------- LoopRotationUtils.cpp -----------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file provides utilities to convert a loop into a loop with bottom test.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopRotationUtils.h"
140b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
150b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
160b57cec5SDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
1981ad6265SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
240b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
25fe6060f1SDimitry Andric #include "llvm/IR/DebugInfo.h"
260b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
270b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
28*c9157d92SDimitry Andric #include "llvm/IR/MDBuilder.h"
29*c9157d92SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
300b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
310b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
320b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
330b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
350b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
360b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdater.h"
370b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
380b57cec5SDimitry Andric using namespace llvm;
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric #define DEBUG_TYPE "loop-rotate"
410b57cec5SDimitry Andric 
42e8d8bef9SDimitry Andric STATISTIC(NumNotRotatedDueToHeaderSize,
43e8d8bef9SDimitry Andric           "Number of loops not rotated due to the header size");
44fe6060f1SDimitry Andric STATISTIC(NumInstrsHoisted,
45fe6060f1SDimitry Andric           "Number of instructions hoisted into loop preheader");
46fe6060f1SDimitry Andric STATISTIC(NumInstrsDuplicated,
47fe6060f1SDimitry Andric           "Number of instructions cloned into loop preheader");
480b57cec5SDimitry Andric STATISTIC(NumRotated, "Number of loops rotated");
490b57cec5SDimitry Andric 
505ffd83dbSDimitry Andric static cl::opt<bool>
515ffd83dbSDimitry Andric     MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
525ffd83dbSDimitry Andric                 cl::desc("Allow loop rotation multiple times in order to reach "
535ffd83dbSDimitry Andric                          "a better latch exit"));
545ffd83dbSDimitry Andric 
55*c9157d92SDimitry Andric // Probability that a rotated loop has zero trip count / is never entered.
56*c9157d92SDimitry Andric static constexpr uint32_t ZeroTripCountWeights[] = {1, 127};
57*c9157d92SDimitry Andric 
580b57cec5SDimitry Andric namespace {
590b57cec5SDimitry Andric /// A simple loop rotation transformation.
600b57cec5SDimitry Andric class LoopRotate {
610b57cec5SDimitry Andric   const unsigned MaxHeaderSize;
620b57cec5SDimitry Andric   LoopInfo *LI;
630b57cec5SDimitry Andric   const TargetTransformInfo *TTI;
640b57cec5SDimitry Andric   AssumptionCache *AC;
650b57cec5SDimitry Andric   DominatorTree *DT;
660b57cec5SDimitry Andric   ScalarEvolution *SE;
670b57cec5SDimitry Andric   MemorySSAUpdater *MSSAU;
680b57cec5SDimitry Andric   const SimplifyQuery &SQ;
690b57cec5SDimitry Andric   bool RotationOnly;
700b57cec5SDimitry Andric   bool IsUtilMode;
71e8d8bef9SDimitry Andric   bool PrepareForLTO;
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric public:
LoopRotate(unsigned MaxHeaderSize,LoopInfo * LI,const TargetTransformInfo * TTI,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,const SimplifyQuery & SQ,bool RotationOnly,bool IsUtilMode,bool PrepareForLTO)740b57cec5SDimitry Andric   LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
750b57cec5SDimitry Andric              const TargetTransformInfo *TTI, AssumptionCache *AC,
760b57cec5SDimitry Andric              DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
77e8d8bef9SDimitry Andric              const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
78e8d8bef9SDimitry Andric              bool PrepareForLTO)
790b57cec5SDimitry Andric       : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
800b57cec5SDimitry Andric         MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
81e8d8bef9SDimitry Andric         IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
820b57cec5SDimitry Andric   bool processLoop(Loop *L);
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric private:
850b57cec5SDimitry Andric   bool rotateLoop(Loop *L, bool SimplifiedLatch);
860b57cec5SDimitry Andric   bool simplifyLoopLatch(Loop *L);
870b57cec5SDimitry Andric };
880b57cec5SDimitry Andric } // end anonymous namespace
890b57cec5SDimitry Andric 
90480093f4SDimitry Andric /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
91480093f4SDimitry Andric /// previously exist in the map, and the value was inserted.
InsertNewValueIntoMap(ValueToValueMapTy & VM,Value * K,Value * V)92480093f4SDimitry Andric static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) {
93480093f4SDimitry Andric   bool Inserted = VM.insert({K, V}).second;
94480093f4SDimitry Andric   assert(Inserted);
95480093f4SDimitry Andric   (void)Inserted;
96480093f4SDimitry Andric }
970b57cec5SDimitry Andric /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
980b57cec5SDimitry Andric /// old header into the preheader.  If there were uses of the values produced by
990b57cec5SDimitry Andric /// these instruction that were outside of the loop, we have to insert PHI nodes
1000b57cec5SDimitry Andric /// to merge the two values.  Do this now.
RewriteUsesOfClonedInstructions(BasicBlock * OrigHeader,BasicBlock * OrigPreheader,ValueToValueMapTy & ValueMap,ScalarEvolution * SE,SmallVectorImpl<PHINode * > * InsertedPHIs)1010b57cec5SDimitry Andric static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
1020b57cec5SDimitry Andric                                             BasicBlock *OrigPreheader,
1030b57cec5SDimitry Andric                                             ValueToValueMapTy &ValueMap,
104349cc55cSDimitry Andric                                             ScalarEvolution *SE,
1050b57cec5SDimitry Andric                                 SmallVectorImpl<PHINode*> *InsertedPHIs) {
1060b57cec5SDimitry Andric   // Remove PHI node entries that are no longer live.
1070b57cec5SDimitry Andric   BasicBlock::iterator I, E = OrigHeader->end();
1080b57cec5SDimitry Andric   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
1090b57cec5SDimitry Andric     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
1120b57cec5SDimitry Andric   // as necessary.
1130b57cec5SDimitry Andric   SSAUpdater SSA(InsertedPHIs);
1140b57cec5SDimitry Andric   for (I = OrigHeader->begin(); I != E; ++I) {
1150b57cec5SDimitry Andric     Value *OrigHeaderVal = &*I;
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric     // If there are no uses of the value (e.g. because it returns void), there
1180b57cec5SDimitry Andric     // is nothing to rewrite.
1190b57cec5SDimitry Andric     if (OrigHeaderVal->use_empty())
1200b57cec5SDimitry Andric       continue;
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric     Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric     // The value now exits in two versions: the initial value in the preheader
1250b57cec5SDimitry Andric     // and the loop "next" value in the original header.
1260b57cec5SDimitry Andric     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
127349cc55cSDimitry Andric     // Force re-computation of OrigHeaderVal, as some users now need to use the
128349cc55cSDimitry Andric     // new PHI node.
129349cc55cSDimitry Andric     if (SE)
130349cc55cSDimitry Andric       SE->forgetValue(OrigHeaderVal);
1310b57cec5SDimitry Andric     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
1320b57cec5SDimitry Andric     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric     // Visit each use of the OrigHeader instruction.
135349cc55cSDimitry Andric     for (Use &U : llvm::make_early_inc_range(OrigHeaderVal->uses())) {
1360b57cec5SDimitry Andric       // SSAUpdater can't handle a non-PHI use in the same block as an
1370b57cec5SDimitry Andric       // earlier def. We can easily handle those cases manually.
1380b57cec5SDimitry Andric       Instruction *UserInst = cast<Instruction>(U.getUser());
1390b57cec5SDimitry Andric       if (!isa<PHINode>(UserInst)) {
1400b57cec5SDimitry Andric         BasicBlock *UserBB = UserInst->getParent();
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric         // The original users in the OrigHeader are already using the
1430b57cec5SDimitry Andric         // original definitions.
1440b57cec5SDimitry Andric         if (UserBB == OrigHeader)
1450b57cec5SDimitry Andric           continue;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric         // Users in the OrigPreHeader need to use the value to which the
1480b57cec5SDimitry Andric         // original definitions are mapped.
1490b57cec5SDimitry Andric         if (UserBB == OrigPreheader) {
1500b57cec5SDimitry Andric           U = OrigPreHeaderVal;
1510b57cec5SDimitry Andric           continue;
1520b57cec5SDimitry Andric         }
1530b57cec5SDimitry Andric       }
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric       // Anything else can be handled by SSAUpdater.
1560b57cec5SDimitry Andric       SSA.RewriteUse(U);
1570b57cec5SDimitry Andric     }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric     // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
1600b57cec5SDimitry Andric     // intrinsics.
1610b57cec5SDimitry Andric     SmallVector<DbgValueInst *, 1> DbgValues;
162*c9157d92SDimitry Andric     SmallVector<DPValue *, 1> DPValues;
163*c9157d92SDimitry Andric     llvm::findDbgValues(DbgValues, OrigHeaderVal, &DPValues);
1640b57cec5SDimitry Andric     for (auto &DbgValue : DbgValues) {
1650b57cec5SDimitry Andric       // The original users in the OrigHeader are already using the original
1660b57cec5SDimitry Andric       // definitions.
1670b57cec5SDimitry Andric       BasicBlock *UserBB = DbgValue->getParent();
1680b57cec5SDimitry Andric       if (UserBB == OrigHeader)
1690b57cec5SDimitry Andric         continue;
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric       // Users in the OrigPreHeader need to use the value to which the
1720b57cec5SDimitry Andric       // original definitions are mapped and anything else can be handled by
1730b57cec5SDimitry Andric       // the SSAUpdater. To avoid adding PHINodes, check if the value is
1740b57cec5SDimitry Andric       // available in UserBB, if not substitute undef.
1750b57cec5SDimitry Andric       Value *NewVal;
1760b57cec5SDimitry Andric       if (UserBB == OrigPreheader)
1770b57cec5SDimitry Andric         NewVal = OrigPreHeaderVal;
1780b57cec5SDimitry Andric       else if (SSA.HasValueForBlock(UserBB))
1790b57cec5SDimitry Andric         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
1800b57cec5SDimitry Andric       else
1810b57cec5SDimitry Andric         NewVal = UndefValue::get(OrigHeaderVal->getType());
182fe6060f1SDimitry Andric       DbgValue->replaceVariableLocationOp(OrigHeaderVal, NewVal);
1830b57cec5SDimitry Andric     }
184*c9157d92SDimitry Andric 
185*c9157d92SDimitry Andric     // RemoveDIs: duplicate implementation for non-instruction debug-info
186*c9157d92SDimitry Andric     // storage in DPValues.
187*c9157d92SDimitry Andric     for (DPValue *DPV : DPValues) {
188*c9157d92SDimitry Andric       // The original users in the OrigHeader are already using the original
189*c9157d92SDimitry Andric       // definitions.
190*c9157d92SDimitry Andric       BasicBlock *UserBB = DPV->getMarker()->getParent();
191*c9157d92SDimitry Andric       if (UserBB == OrigHeader)
192*c9157d92SDimitry Andric         continue;
193*c9157d92SDimitry Andric 
194*c9157d92SDimitry Andric       // Users in the OrigPreHeader need to use the value to which the
195*c9157d92SDimitry Andric       // original definitions are mapped and anything else can be handled by
196*c9157d92SDimitry Andric       // the SSAUpdater. To avoid adding PHINodes, check if the value is
197*c9157d92SDimitry Andric       // available in UserBB, if not substitute undef.
198*c9157d92SDimitry Andric       Value *NewVal;
199*c9157d92SDimitry Andric       if (UserBB == OrigPreheader)
200*c9157d92SDimitry Andric         NewVal = OrigPreHeaderVal;
201*c9157d92SDimitry Andric       else if (SSA.HasValueForBlock(UserBB))
202*c9157d92SDimitry Andric         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
203*c9157d92SDimitry Andric       else
204*c9157d92SDimitry Andric         NewVal = UndefValue::get(OrigHeaderVal->getType());
205*c9157d92SDimitry Andric       DPV->replaceVariableLocationOp(OrigHeaderVal, NewVal);
206*c9157d92SDimitry Andric     }
2070b57cec5SDimitry Andric   }
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric 
2105ffd83dbSDimitry Andric // Assuming both header and latch are exiting, look for a phi which is only
2115ffd83dbSDimitry Andric // used outside the loop (via a LCSSA phi) in the exit from the header.
2125ffd83dbSDimitry Andric // This means that rotating the loop can remove the phi.
profitableToRotateLoopExitingLatch(Loop * L)2135ffd83dbSDimitry Andric static bool profitableToRotateLoopExitingLatch(Loop *L) {
2140b57cec5SDimitry Andric   BasicBlock *Header = L->getHeader();
2155ffd83dbSDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
2165ffd83dbSDimitry Andric   assert(BI && BI->isConditional() && "need header with conditional exit");
2175ffd83dbSDimitry Andric   BasicBlock *HeaderExit = BI->getSuccessor(0);
2180b57cec5SDimitry Andric   if (L->contains(HeaderExit))
2195ffd83dbSDimitry Andric     HeaderExit = BI->getSuccessor(1);
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   for (auto &Phi : Header->phis()) {
2220b57cec5SDimitry Andric     // Look for uses of this phi in the loop/via exits other than the header.
2230b57cec5SDimitry Andric     if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
2240b57cec5SDimitry Andric           return cast<Instruction>(U)->getParent() != HeaderExit;
2250b57cec5SDimitry Andric         }))
2260b57cec5SDimitry Andric       continue;
2270b57cec5SDimitry Andric     return true;
2280b57cec5SDimitry Andric   }
2295ffd83dbSDimitry Andric   return false;
2305ffd83dbSDimitry Andric }
2310b57cec5SDimitry Andric 
2325ffd83dbSDimitry Andric // Check that latch exit is deoptimizing (which means - very unlikely to happen)
2335ffd83dbSDimitry Andric // and there is another exit from the loop which is non-deoptimizing.
2345ffd83dbSDimitry Andric // If we rotate latch to that exit our loop has a better chance of being fully
2355ffd83dbSDimitry Andric // canonical.
2365ffd83dbSDimitry Andric //
2375ffd83dbSDimitry Andric // It can give false positives in some rare cases.
canRotateDeoptimizingLatchExit(Loop * L)2385ffd83dbSDimitry Andric static bool canRotateDeoptimizingLatchExit(Loop *L) {
2395ffd83dbSDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
2405ffd83dbSDimitry Andric   assert(Latch && "need latch");
2415ffd83dbSDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
2425ffd83dbSDimitry Andric   // Need normal exiting latch.
2435ffd83dbSDimitry Andric   if (!BI || !BI->isConditional())
2445ffd83dbSDimitry Andric     return false;
2455ffd83dbSDimitry Andric 
2465ffd83dbSDimitry Andric   BasicBlock *Exit = BI->getSuccessor(1);
2475ffd83dbSDimitry Andric   if (L->contains(Exit))
2485ffd83dbSDimitry Andric     Exit = BI->getSuccessor(0);
2495ffd83dbSDimitry Andric 
2505ffd83dbSDimitry Andric   // Latch exit is non-deoptimizing, no need to rotate.
2515ffd83dbSDimitry Andric   if (!Exit->getPostdominatingDeoptimizeCall())
2525ffd83dbSDimitry Andric     return false;
2535ffd83dbSDimitry Andric 
2545ffd83dbSDimitry Andric   SmallVector<BasicBlock *, 4> Exits;
2555ffd83dbSDimitry Andric   L->getUniqueExitBlocks(Exits);
2565ffd83dbSDimitry Andric   if (!Exits.empty()) {
2575ffd83dbSDimitry Andric     // There is at least one non-deoptimizing exit.
2585ffd83dbSDimitry Andric     //
2595ffd83dbSDimitry Andric     // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
2605ffd83dbSDimitry Andric     // as it can conservatively return false for deoptimizing exits with
2615ffd83dbSDimitry Andric     // complex enough control flow down to deoptimize call.
2625ffd83dbSDimitry Andric     //
2635ffd83dbSDimitry Andric     // That means here we can report success for a case where
2645ffd83dbSDimitry Andric     // all exits are deoptimizing but one of them has complex enough
2655ffd83dbSDimitry Andric     // control flow (e.g. with loops).
2665ffd83dbSDimitry Andric     //
2675ffd83dbSDimitry Andric     // That should be a very rare case and false positives for this function
2685ffd83dbSDimitry Andric     // have compile-time effect only.
2695ffd83dbSDimitry Andric     return any_of(Exits, [](const BasicBlock *BB) {
2705ffd83dbSDimitry Andric       return !BB->getPostdominatingDeoptimizeCall();
2715ffd83dbSDimitry Andric     });
2725ffd83dbSDimitry Andric   }
2730b57cec5SDimitry Andric   return false;
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric 
updateBranchWeights(BranchInst & PreHeaderBI,BranchInst & LoopBI,bool HasConditionalPreHeader,bool SuccsSwapped)276*c9157d92SDimitry Andric static void updateBranchWeights(BranchInst &PreHeaderBI, BranchInst &LoopBI,
277*c9157d92SDimitry Andric                                 bool HasConditionalPreHeader,
278*c9157d92SDimitry Andric                                 bool SuccsSwapped) {
279*c9157d92SDimitry Andric   MDNode *WeightMD = getBranchWeightMDNode(PreHeaderBI);
280*c9157d92SDimitry Andric   if (WeightMD == nullptr)
281*c9157d92SDimitry Andric     return;
282*c9157d92SDimitry Andric 
283*c9157d92SDimitry Andric   // LoopBI should currently be a clone of PreHeaderBI with the same
284*c9157d92SDimitry Andric   // metadata. But we double check to make sure we don't have a degenerate case
285*c9157d92SDimitry Andric   // where instsimplify changed the instructions.
286*c9157d92SDimitry Andric   if (WeightMD != getBranchWeightMDNode(LoopBI))
287*c9157d92SDimitry Andric     return;
288*c9157d92SDimitry Andric 
289*c9157d92SDimitry Andric   SmallVector<uint32_t, 2> Weights;
290*c9157d92SDimitry Andric   extractFromBranchWeightMD(WeightMD, Weights);
291*c9157d92SDimitry Andric   if (Weights.size() != 2)
292*c9157d92SDimitry Andric     return;
293*c9157d92SDimitry Andric   uint32_t OrigLoopExitWeight = Weights[0];
294*c9157d92SDimitry Andric   uint32_t OrigLoopBackedgeWeight = Weights[1];
295*c9157d92SDimitry Andric 
296*c9157d92SDimitry Andric   if (SuccsSwapped)
297*c9157d92SDimitry Andric     std::swap(OrigLoopExitWeight, OrigLoopBackedgeWeight);
298*c9157d92SDimitry Andric 
299*c9157d92SDimitry Andric   // Update branch weights. Consider the following edge-counts:
300*c9157d92SDimitry Andric   //
301*c9157d92SDimitry Andric   //    |  |--------             |
302*c9157d92SDimitry Andric   //    V  V       |             V
303*c9157d92SDimitry Andric   //   Br i1 ...   |            Br i1 ...
304*c9157d92SDimitry Andric   //   |       |   |            |     |
305*c9157d92SDimitry Andric   //  x|      y|   |  becomes:  |   y0|  |-----
306*c9157d92SDimitry Andric   //   V       V   |            |     V  V    |
307*c9157d92SDimitry Andric   // Exit    Loop  |            |    Loop     |
308*c9157d92SDimitry Andric   //           |   |            |   Br i1 ... |
309*c9157d92SDimitry Andric   //           -----            |   |      |  |
310*c9157d92SDimitry Andric   //                          x0| x1|   y1 |  |
311*c9157d92SDimitry Andric   //                            V   V      ----
312*c9157d92SDimitry Andric   //                            Exit
313*c9157d92SDimitry Andric   //
314*c9157d92SDimitry Andric   // The following must hold:
315*c9157d92SDimitry Andric   //  -  x == x0 + x1        # counts to "exit" must stay the same.
316*c9157d92SDimitry Andric   //  - y0 == x - x0 == x1   # how often loop was entered at all.
317*c9157d92SDimitry Andric   //  - y1 == y - y0         # How often loop was repeated (after first iter.).
318*c9157d92SDimitry Andric   //
319*c9157d92SDimitry Andric   // We cannot generally deduce how often we had a zero-trip count loop so we
320*c9157d92SDimitry Andric   // have to make a guess for how to distribute x among the new x0 and x1.
321*c9157d92SDimitry Andric 
322*c9157d92SDimitry Andric   uint32_t ExitWeight0;    // aka x0
323*c9157d92SDimitry Andric   uint32_t ExitWeight1;    // aka x1
324*c9157d92SDimitry Andric   uint32_t EnterWeight;    // aka y0
325*c9157d92SDimitry Andric   uint32_t LoopBackWeight; // aka y1
326*c9157d92SDimitry Andric   if (OrigLoopExitWeight > 0 && OrigLoopBackedgeWeight > 0) {
327*c9157d92SDimitry Andric     ExitWeight0 = 0;
328*c9157d92SDimitry Andric     if (HasConditionalPreHeader) {
329*c9157d92SDimitry Andric       // Here we cannot know how many 0-trip count loops we have, so we guess:
330*c9157d92SDimitry Andric       if (OrigLoopBackedgeWeight >= OrigLoopExitWeight) {
331*c9157d92SDimitry Andric         // If the loop count is bigger than the exit count then we set
332*c9157d92SDimitry Andric         // probabilities as if 0-trip count nearly never happens.
333*c9157d92SDimitry Andric         ExitWeight0 = ZeroTripCountWeights[0];
334*c9157d92SDimitry Andric         // Scale up counts if necessary so we can match `ZeroTripCountWeights`
335*c9157d92SDimitry Andric         // for the `ExitWeight0`:`ExitWeight1` (aka `x0`:`x1` ratio`) ratio.
336*c9157d92SDimitry Andric         while (OrigLoopExitWeight < ZeroTripCountWeights[1] + ExitWeight0) {
337*c9157d92SDimitry Andric           // ... but don't overflow.
338*c9157d92SDimitry Andric           uint32_t const HighBit = uint32_t{1} << (sizeof(uint32_t) * 8 - 1);
339*c9157d92SDimitry Andric           if ((OrigLoopBackedgeWeight & HighBit) != 0 ||
340*c9157d92SDimitry Andric               (OrigLoopExitWeight & HighBit) != 0)
341*c9157d92SDimitry Andric             break;
342*c9157d92SDimitry Andric           OrigLoopBackedgeWeight <<= 1;
343*c9157d92SDimitry Andric           OrigLoopExitWeight <<= 1;
344*c9157d92SDimitry Andric         }
345*c9157d92SDimitry Andric       } else {
346*c9157d92SDimitry Andric         // If there's a higher exit-count than backedge-count then we set
347*c9157d92SDimitry Andric         // probabilities as if there are only 0-trip and 1-trip cases.
348*c9157d92SDimitry Andric         ExitWeight0 = OrigLoopExitWeight - OrigLoopBackedgeWeight;
349*c9157d92SDimitry Andric       }
350*c9157d92SDimitry Andric     }
351*c9157d92SDimitry Andric     ExitWeight1 = OrigLoopExitWeight - ExitWeight0;
352*c9157d92SDimitry Andric     EnterWeight = ExitWeight1;
353*c9157d92SDimitry Andric     LoopBackWeight = OrigLoopBackedgeWeight - EnterWeight;
354*c9157d92SDimitry Andric   } else if (OrigLoopExitWeight == 0) {
355*c9157d92SDimitry Andric     if (OrigLoopBackedgeWeight == 0) {
356*c9157d92SDimitry Andric       // degenerate case... keep everything zero...
357*c9157d92SDimitry Andric       ExitWeight0 = 0;
358*c9157d92SDimitry Andric       ExitWeight1 = 0;
359*c9157d92SDimitry Andric       EnterWeight = 0;
360*c9157d92SDimitry Andric       LoopBackWeight = 0;
361*c9157d92SDimitry Andric     } else {
362*c9157d92SDimitry Andric       // Special case "LoopExitWeight == 0" weights which behaves like an
363*c9157d92SDimitry Andric       // endless where we don't want loop-enttry (y0) to be the same as
364*c9157d92SDimitry Andric       // loop-exit (x1).
365*c9157d92SDimitry Andric       ExitWeight0 = 0;
366*c9157d92SDimitry Andric       ExitWeight1 = 0;
367*c9157d92SDimitry Andric       EnterWeight = 1;
368*c9157d92SDimitry Andric       LoopBackWeight = OrigLoopBackedgeWeight;
369*c9157d92SDimitry Andric     }
370*c9157d92SDimitry Andric   } else {
371*c9157d92SDimitry Andric     // loop is never entered.
372*c9157d92SDimitry Andric     assert(OrigLoopBackedgeWeight == 0 && "remaining case is backedge zero");
373*c9157d92SDimitry Andric     ExitWeight0 = 1;
374*c9157d92SDimitry Andric     ExitWeight1 = 1;
375*c9157d92SDimitry Andric     EnterWeight = 0;
376*c9157d92SDimitry Andric     LoopBackWeight = 0;
377*c9157d92SDimitry Andric   }
378*c9157d92SDimitry Andric 
379*c9157d92SDimitry Andric   const uint32_t LoopBIWeights[] = {
380*c9157d92SDimitry Andric       SuccsSwapped ? LoopBackWeight : ExitWeight1,
381*c9157d92SDimitry Andric       SuccsSwapped ? ExitWeight1 : LoopBackWeight,
382*c9157d92SDimitry Andric   };
383*c9157d92SDimitry Andric   setBranchWeights(LoopBI, LoopBIWeights);
384*c9157d92SDimitry Andric   if (HasConditionalPreHeader) {
385*c9157d92SDimitry Andric     const uint32_t PreHeaderBIWeights[] = {
386*c9157d92SDimitry Andric         SuccsSwapped ? EnterWeight : ExitWeight0,
387*c9157d92SDimitry Andric         SuccsSwapped ? ExitWeight0 : EnterWeight,
388*c9157d92SDimitry Andric     };
389*c9157d92SDimitry Andric     setBranchWeights(PreHeaderBI, PreHeaderBIWeights);
390*c9157d92SDimitry Andric   }
391*c9157d92SDimitry Andric }
392*c9157d92SDimitry Andric 
3930b57cec5SDimitry Andric /// Rotate loop LP. Return true if the loop is rotated.
3940b57cec5SDimitry Andric ///
3950b57cec5SDimitry Andric /// \param SimplifiedLatch is true if the latch was just folded into the final
3960b57cec5SDimitry Andric /// loop exit. In this case we may want to rotate even though the new latch is
3970b57cec5SDimitry Andric /// now an exiting branch. This rotation would have happened had the latch not
3980b57cec5SDimitry Andric /// been simplified. However, if SimplifiedLatch is false, then we avoid
3990b57cec5SDimitry Andric /// rotating loops in which the latch exits to avoid excessive or endless
4000b57cec5SDimitry Andric /// rotation. LoopRotate should be repeatable and converge to a canonical
4010b57cec5SDimitry Andric /// form. This property is satisfied because simplifying the loop latch can only
4020b57cec5SDimitry Andric /// happen once across multiple invocations of the LoopRotate pass.
4035ffd83dbSDimitry Andric ///
4045ffd83dbSDimitry Andric /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
4055ffd83dbSDimitry Andric /// so to reach a suitable (non-deoptimizing) exit.
rotateLoop(Loop * L,bool SimplifiedLatch)4060b57cec5SDimitry Andric bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
4070b57cec5SDimitry Andric   // If the loop has only one block then there is not much to rotate.
4080b57cec5SDimitry Andric   if (L->getBlocks().size() == 1)
4090b57cec5SDimitry Andric     return false;
4100b57cec5SDimitry Andric 
4115ffd83dbSDimitry Andric   bool Rotated = false;
4125ffd83dbSDimitry Andric   do {
4130b57cec5SDimitry Andric     BasicBlock *OrigHeader = L->getHeader();
4140b57cec5SDimitry Andric     BasicBlock *OrigLatch = L->getLoopLatch();
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
4170b57cec5SDimitry Andric     if (!BI || BI->isUnconditional())
4185ffd83dbSDimitry Andric       return Rotated;
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric     // If the loop header is not one of the loop exiting blocks then
4210b57cec5SDimitry Andric     // either this loop is already rotated or it is not
4220b57cec5SDimitry Andric     // suitable for loop rotation transformations.
4230b57cec5SDimitry Andric     if (!L->isLoopExiting(OrigHeader))
4245ffd83dbSDimitry Andric       return Rotated;
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric     // If the loop latch already contains a branch that leaves the loop then the
4270b57cec5SDimitry Andric     // loop is already rotated.
4280b57cec5SDimitry Andric     if (!OrigLatch)
4295ffd83dbSDimitry Andric       return Rotated;
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric     // Rotate if either the loop latch does *not* exit the loop, or if the loop
4320b57cec5SDimitry Andric     // latch was just simplified. Or if we think it will be profitable.
4330b57cec5SDimitry Andric     if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
4345ffd83dbSDimitry Andric         !profitableToRotateLoopExitingLatch(L) &&
4355ffd83dbSDimitry Andric         !canRotateDeoptimizingLatchExit(L))
4365ffd83dbSDimitry Andric       return Rotated;
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric     // Check size of original header and reject loop if it is very big or we can't
4390b57cec5SDimitry Andric     // duplicate blocks inside it.
4400b57cec5SDimitry Andric     {
4410b57cec5SDimitry Andric       SmallPtrSet<const Value *, 32> EphValues;
4420b57cec5SDimitry Andric       CodeMetrics::collectEphemeralValues(L, AC, EphValues);
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric       CodeMetrics Metrics;
445e8d8bef9SDimitry Andric       Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
4460b57cec5SDimitry Andric       if (Metrics.notDuplicatable) {
4470b57cec5SDimitry Andric         LLVM_DEBUG(
4480b57cec5SDimitry Andric                    dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
4490b57cec5SDimitry Andric                    << " instructions: ";
4500b57cec5SDimitry Andric                    L->dump());
4515ffd83dbSDimitry Andric         return Rotated;
4520b57cec5SDimitry Andric       }
4530b57cec5SDimitry Andric       if (Metrics.convergent) {
4540b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
4550b57cec5SDimitry Andric                    "instructions: ";
4560b57cec5SDimitry Andric                    L->dump());
4575ffd83dbSDimitry Andric         return Rotated;
4580b57cec5SDimitry Andric       }
45981ad6265SDimitry Andric       if (!Metrics.NumInsts.isValid()) {
46081ad6265SDimitry Andric         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains instructions"
46181ad6265SDimitry Andric                    " with invalid cost: ";
46281ad6265SDimitry Andric                    L->dump());
46381ad6265SDimitry Andric         return Rotated;
46481ad6265SDimitry Andric       }
465bdd1243dSDimitry Andric       if (Metrics.NumInsts > MaxHeaderSize) {
4665ffd83dbSDimitry Andric         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
4675ffd83dbSDimitry Andric                           << Metrics.NumInsts
4685ffd83dbSDimitry Andric                           << " instructions, which is more than the threshold ("
4695ffd83dbSDimitry Andric                           << MaxHeaderSize << " instructions): ";
4705ffd83dbSDimitry Andric                    L->dump());
471e8d8bef9SDimitry Andric         ++NumNotRotatedDueToHeaderSize;
4725ffd83dbSDimitry Andric         return Rotated;
4735ffd83dbSDimitry Andric       }
474e8d8bef9SDimitry Andric 
475e8d8bef9SDimitry Andric       // When preparing for LTO, avoid rotating loops with calls that could be
476e8d8bef9SDimitry Andric       // inlined during the LTO stage.
477e8d8bef9SDimitry Andric       if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
478e8d8bef9SDimitry Andric         return Rotated;
4790b57cec5SDimitry Andric     }
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric     // Now, this loop is suitable for rotation.
4820b57cec5SDimitry Andric     BasicBlock *OrigPreheader = L->getLoopPreheader();
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric     // If the loop could not be converted to canonical form, it must have an
4850b57cec5SDimitry Andric     // indirectbr in it, just give up.
4860b57cec5SDimitry Andric     if (!OrigPreheader || !L->hasDedicatedExits())
4875ffd83dbSDimitry Andric       return Rotated;
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric     // Anything ScalarEvolution may know about this loop or the PHI nodes
4900b57cec5SDimitry Andric     // in its header will soon be invalidated. We should also invalidate
4910b57cec5SDimitry Andric     // all outer loops because insertion and deletion of blocks that happens
4920b57cec5SDimitry Andric     // during the rotation may violate invariants related to backedge taken
4930b57cec5SDimitry Andric     // infos in them.
494bdd1243dSDimitry Andric     if (SE) {
4950b57cec5SDimitry Andric       SE->forgetTopmostLoop(L);
496bdd1243dSDimitry Andric       // We may hoist some instructions out of loop. In case if they were cached
497bdd1243dSDimitry Andric       // as "loop variant" or "loop computable", these caches must be dropped.
498bdd1243dSDimitry Andric       // We also may fold basic blocks, so cached block dispositions also need
499bdd1243dSDimitry Andric       // to be dropped.
500bdd1243dSDimitry Andric       SE->forgetBlockAndLoopDispositions();
501bdd1243dSDimitry Andric     }
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
5040b57cec5SDimitry Andric     if (MSSAU && VerifyMemorySSA)
5050b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric     // Find new Loop header. NewHeader is a Header's one and only successor
5080b57cec5SDimitry Andric     // that is inside loop.  Header's other successor is outside the
5090b57cec5SDimitry Andric     // loop.  Otherwise loop is not suitable for rotation.
5100b57cec5SDimitry Andric     BasicBlock *Exit = BI->getSuccessor(0);
5110b57cec5SDimitry Andric     BasicBlock *NewHeader = BI->getSuccessor(1);
512*c9157d92SDimitry Andric     bool BISuccsSwapped = L->contains(Exit);
513*c9157d92SDimitry Andric     if (BISuccsSwapped)
5140b57cec5SDimitry Andric       std::swap(Exit, NewHeader);
5150b57cec5SDimitry Andric     assert(NewHeader && "Unable to determine new loop header");
5160b57cec5SDimitry Andric     assert(L->contains(NewHeader) && !L->contains(Exit) &&
5170b57cec5SDimitry Andric            "Unable to determine loop header and exit blocks");
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric     // This code assumes that the new header has exactly one predecessor.
5200b57cec5SDimitry Andric     // Remove any single-entry PHI nodes in it.
5210b57cec5SDimitry Andric     assert(NewHeader->getSinglePredecessor() &&
5220b57cec5SDimitry Andric            "New header doesn't have one pred!");
5230b57cec5SDimitry Andric     FoldSingleEntryPHINodes(NewHeader);
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric     // Begin by walking OrigHeader and populating ValueMap with an entry for
5260b57cec5SDimitry Andric     // each Instruction.
5270b57cec5SDimitry Andric     BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
5280b57cec5SDimitry Andric     ValueToValueMapTy ValueMap, ValueMapMSSA;
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric     // For PHI nodes, the value available in OldPreHeader is just the
5310b57cec5SDimitry Andric     // incoming value from OldPreHeader.
5320b57cec5SDimitry Andric     for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
533480093f4SDimitry Andric       InsertNewValueIntoMap(ValueMap, PN,
534480093f4SDimitry Andric                             PN->getIncomingValueForBlock(OrigPreheader));
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric     // For the rest of the instructions, either hoist to the OrigPreheader if
5370b57cec5SDimitry Andric     // possible or create a clone in the OldPreHeader if not.
5380b57cec5SDimitry Andric     Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
5390b57cec5SDimitry Andric 
540fe6060f1SDimitry Andric     // Record all debug intrinsics preceding LoopEntryBranch to avoid
541fe6060f1SDimitry Andric     // duplication.
5420b57cec5SDimitry Andric     using DbgIntrinsicHash =
543fe6060f1SDimitry Andric         std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
544*c9157d92SDimitry Andric     auto makeHash = [](auto *D) -> DbgIntrinsicHash {
545fe6060f1SDimitry Andric       auto VarLocOps = D->location_ops();
546fe6060f1SDimitry Andric       return {{hash_combine_range(VarLocOps.begin(), VarLocOps.end()),
547fe6060f1SDimitry Andric                D->getVariable()},
548fe6060f1SDimitry Andric               D->getExpression()};
5490b57cec5SDimitry Andric     };
550*c9157d92SDimitry Andric 
5510b57cec5SDimitry Andric     SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
552349cc55cSDimitry Andric     for (Instruction &I : llvm::drop_begin(llvm::reverse(*OrigPreheader))) {
553*c9157d92SDimitry Andric       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
5540b57cec5SDimitry Andric         DbgIntrinsics.insert(makeHash(DII));
555*c9157d92SDimitry Andric         // Until RemoveDIs supports dbg.declares in DPValue format, we'll need
556*c9157d92SDimitry Andric         // to collect DPValues attached to any other debug intrinsics.
557*c9157d92SDimitry Andric         for (const DPValue &DPV : DII->getDbgValueRange())
558*c9157d92SDimitry Andric           DbgIntrinsics.insert(makeHash(&DPV));
559*c9157d92SDimitry Andric       } else {
5600b57cec5SDimitry Andric         break;
5610b57cec5SDimitry Andric       }
562*c9157d92SDimitry Andric     }
563*c9157d92SDimitry Andric 
564*c9157d92SDimitry Andric     // Build DPValue hashes for DPValues attached to the terminator, which isn't
565*c9157d92SDimitry Andric     // considered in the loop above.
566*c9157d92SDimitry Andric     for (const DPValue &DPV :
567*c9157d92SDimitry Andric          OrigPreheader->getTerminator()->getDbgValueRange())
568*c9157d92SDimitry Andric       DbgIntrinsics.insert(makeHash(&DPV));
5690b57cec5SDimitry Andric 
570e8d8bef9SDimitry Andric     // Remember the local noalias scope declarations in the header. After the
571e8d8bef9SDimitry Andric     // rotation, they must be duplicated and the scope must be cloned. This
572e8d8bef9SDimitry Andric     // avoids unwanted interaction across iterations.
573e8d8bef9SDimitry Andric     SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
574e8d8bef9SDimitry Andric     for (Instruction &I : *OrigHeader)
575e8d8bef9SDimitry Andric       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
576e8d8bef9SDimitry Andric         NoAliasDeclInstructions.push_back(Decl);
577e8d8bef9SDimitry Andric 
578*c9157d92SDimitry Andric     Module *M = OrigHeader->getModule();
579*c9157d92SDimitry Andric 
580*c9157d92SDimitry Andric     // Track the next DPValue to clone. If we have a sequence where an
581*c9157d92SDimitry Andric     // instruction is hoisted instead of being cloned:
582*c9157d92SDimitry Andric     //    DPValue blah
583*c9157d92SDimitry Andric     //    %foo = add i32 0, 0
584*c9157d92SDimitry Andric     //    DPValue xyzzy
585*c9157d92SDimitry Andric     //    %bar = call i32 @foobar()
586*c9157d92SDimitry Andric     // where %foo is hoisted, then the DPValue "blah" will be seen twice, once
587*c9157d92SDimitry Andric     // attached to %foo, then when %foo his hoisted it will "fall down" onto the
588*c9157d92SDimitry Andric     // function call:
589*c9157d92SDimitry Andric     //    DPValue blah
590*c9157d92SDimitry Andric     //    DPValue xyzzy
591*c9157d92SDimitry Andric     //    %bar = call i32 @foobar()
592*c9157d92SDimitry Andric     // causing it to appear attached to the call too.
593*c9157d92SDimitry Andric     //
594*c9157d92SDimitry Andric     // To avoid this, cloneDebugInfoFrom takes an optional "start cloning from
595*c9157d92SDimitry Andric     // here" position to account for this behaviour. We point it at any DPValues
596*c9157d92SDimitry Andric     // on the next instruction, here labelled xyzzy, before we hoist %foo.
597*c9157d92SDimitry Andric     // Later, we only only clone DPValues from that position (xyzzy) onwards,
598*c9157d92SDimitry Andric     // which avoids cloning DPValue "blah" multiple times.
599*c9157d92SDimitry Andric     std::optional<DPValue::self_iterator> NextDbgInst = std::nullopt;
600*c9157d92SDimitry Andric 
6010b57cec5SDimitry Andric     while (I != E) {
6020b57cec5SDimitry Andric       Instruction *Inst = &*I++;
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric       // If the instruction's operands are invariant and it doesn't read or write
6050b57cec5SDimitry Andric       // memory, then it is safe to hoist.  Doing this doesn't change the order of
6060b57cec5SDimitry Andric       // execution in the preheader, but does prevent the instruction from
6070b57cec5SDimitry Andric       // executing in each iteration of the loop.  This means it is safe to hoist
6080b57cec5SDimitry Andric       // something that might trap, but isn't safe to hoist something that reads
6090b57cec5SDimitry Andric       // memory (without proving that the loop doesn't write).
6100b57cec5SDimitry Andric       if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
6110b57cec5SDimitry Andric           !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
6120b57cec5SDimitry Andric           !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
613*c9157d92SDimitry Andric 
614*c9157d92SDimitry Andric         if (LoopEntryBranch->getParent()->IsNewDbgInfoFormat) {
615*c9157d92SDimitry Andric           auto DbgValueRange =
616*c9157d92SDimitry Andric               LoopEntryBranch->cloneDebugInfoFrom(Inst, NextDbgInst);
617*c9157d92SDimitry Andric           RemapDPValueRange(M, DbgValueRange, ValueMap,
618*c9157d92SDimitry Andric                             RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
619*c9157d92SDimitry Andric           // Erase anything we've seen before.
620*c9157d92SDimitry Andric           for (DPValue &DPV : make_early_inc_range(DbgValueRange))
621*c9157d92SDimitry Andric             if (DbgIntrinsics.count(makeHash(&DPV)))
622*c9157d92SDimitry Andric               DPV.eraseFromParent();
623*c9157d92SDimitry Andric         }
624*c9157d92SDimitry Andric 
625*c9157d92SDimitry Andric         NextDbgInst = I->getDbgValueRange().begin();
6260b57cec5SDimitry Andric         Inst->moveBefore(LoopEntryBranch);
627*c9157d92SDimitry Andric 
628fe6060f1SDimitry Andric         ++NumInstrsHoisted;
6290b57cec5SDimitry Andric         continue;
6300b57cec5SDimitry Andric       }
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric       // Otherwise, create a duplicate of the instruction.
6330b57cec5SDimitry Andric       Instruction *C = Inst->clone();
634fe013be4SDimitry Andric       C->insertBefore(LoopEntryBranch);
635fe013be4SDimitry Andric 
636fe6060f1SDimitry Andric       ++NumInstrsDuplicated;
6370b57cec5SDimitry Andric 
638*c9157d92SDimitry Andric       if (LoopEntryBranch->getParent()->IsNewDbgInfoFormat) {
639*c9157d92SDimitry Andric         auto Range = C->cloneDebugInfoFrom(Inst, NextDbgInst);
640*c9157d92SDimitry Andric         RemapDPValueRange(M, Range, ValueMap,
641*c9157d92SDimitry Andric                           RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
642*c9157d92SDimitry Andric         NextDbgInst = std::nullopt;
643*c9157d92SDimitry Andric         // Erase anything we've seen before.
644*c9157d92SDimitry Andric         for (DPValue &DPV : make_early_inc_range(Range))
645*c9157d92SDimitry Andric           if (DbgIntrinsics.count(makeHash(&DPV)))
646*c9157d92SDimitry Andric             DPV.eraseFromParent();
647*c9157d92SDimitry Andric       }
648*c9157d92SDimitry Andric 
6490b57cec5SDimitry Andric       // Eagerly remap the operands of the instruction.
6500b57cec5SDimitry Andric       RemapInstruction(C, ValueMap,
6510b57cec5SDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric       // Avoid inserting the same intrinsic twice.
6540b57cec5SDimitry Andric       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
6550b57cec5SDimitry Andric         if (DbgIntrinsics.count(makeHash(DII))) {
656fe013be4SDimitry Andric           C->eraseFromParent();
6570b57cec5SDimitry Andric           continue;
6580b57cec5SDimitry Andric         }
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric       // With the operands remapped, see if the instruction constant folds or is
6610b57cec5SDimitry Andric       // otherwise simplifyable.  This commonly occurs because the entry from PHI
6620b57cec5SDimitry Andric       // nodes allows icmps and other instructions to fold.
66381ad6265SDimitry Andric       Value *V = simplifyInstruction(C, SQ);
6640b57cec5SDimitry Andric       if (V && LI->replacementPreservesLCSSAForm(C, V)) {
6650b57cec5SDimitry Andric         // If so, then delete the temporary instruction and stick the folded value
6660b57cec5SDimitry Andric         // in the map.
667480093f4SDimitry Andric         InsertNewValueIntoMap(ValueMap, Inst, V);
6680b57cec5SDimitry Andric         if (!C->mayHaveSideEffects()) {
669fe013be4SDimitry Andric           C->eraseFromParent();
6700b57cec5SDimitry Andric           C = nullptr;
6710b57cec5SDimitry Andric         }
6720b57cec5SDimitry Andric       } else {
673480093f4SDimitry Andric         InsertNewValueIntoMap(ValueMap, Inst, C);
6740b57cec5SDimitry Andric       }
6750b57cec5SDimitry Andric       if (C) {
6760b57cec5SDimitry Andric         // Otherwise, stick the new instruction into the new block!
6770b57cec5SDimitry Andric         C->setName(Inst->getName());
6780b57cec5SDimitry Andric 
679fe6060f1SDimitry Andric         if (auto *II = dyn_cast<AssumeInst>(C))
6800b57cec5SDimitry Andric           AC->registerAssumption(II);
6810b57cec5SDimitry Andric         // MemorySSA cares whether the cloned instruction was inserted or not, and
6820b57cec5SDimitry Andric         // not whether it can be remapped to a simplified value.
683480093f4SDimitry Andric         if (MSSAU)
684480093f4SDimitry Andric           InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
6850b57cec5SDimitry Andric       }
6860b57cec5SDimitry Andric     }
6870b57cec5SDimitry Andric 
688e8d8bef9SDimitry Andric     if (!NoAliasDeclInstructions.empty()) {
689e8d8bef9SDimitry Andric       // There are noalias scope declarations:
690e8d8bef9SDimitry Andric       // (general):
691e8d8bef9SDimitry Andric       // Original:    OrigPre              { OrigHeader NewHeader ... Latch }
692e8d8bef9SDimitry Andric       // after:      (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
693e8d8bef9SDimitry Andric       //
694e8d8bef9SDimitry Andric       // with D: llvm.experimental.noalias.scope.decl,
695e8d8bef9SDimitry Andric       //      U: !noalias or !alias.scope depending on D
696e8d8bef9SDimitry Andric       //       ... { D U1 U2 }   can transform into:
697e8d8bef9SDimitry Andric       // (0) : ... { D U1 U2 }        // no relevant rotation for this part
698e8d8bef9SDimitry Andric       // (1) : ... D' { U1 U2 D }     // D is part of OrigHeader
699e8d8bef9SDimitry Andric       // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
700e8d8bef9SDimitry Andric       //
701e8d8bef9SDimitry Andric       // We now want to transform:
702e8d8bef9SDimitry Andric       // (1) -> : ... D' { D U1 U2 D'' }
703e8d8bef9SDimitry Andric       // (2) -> : ... D' U1' { D U2 D'' U1'' }
704e8d8bef9SDimitry Andric       // D: original llvm.experimental.noalias.scope.decl
705e8d8bef9SDimitry Andric       // D', U1': duplicate with replaced scopes
706e8d8bef9SDimitry Andric       // D'', U1'': different duplicate with replaced scopes
707e8d8bef9SDimitry Andric       // This ensures a safe fallback to 'may_alias' introduced by the rotate,
708e8d8bef9SDimitry Andric       // as U1'' and U1' scopes will not be compatible wrt to the local restrict
709e8d8bef9SDimitry Andric 
710e8d8bef9SDimitry Andric       // Clone the llvm.experimental.noalias.decl again for the NewHeader.
711*c9157d92SDimitry Andric       BasicBlock::iterator NewHeaderInsertionPoint =
712*c9157d92SDimitry Andric           NewHeader->getFirstNonPHIIt();
713e8d8bef9SDimitry Andric       for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
714e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "  Cloning llvm.experimental.noalias.scope.decl:"
715e8d8bef9SDimitry Andric                           << *NAD << "\n");
716e8d8bef9SDimitry Andric         Instruction *NewNAD = NAD->clone();
717*c9157d92SDimitry Andric         NewNAD->insertBefore(*NewHeader, NewHeaderInsertionPoint);
718e8d8bef9SDimitry Andric       }
719e8d8bef9SDimitry Andric 
720e8d8bef9SDimitry Andric       // Scopes must now be duplicated, once for OrigHeader and once for
721e8d8bef9SDimitry Andric       // OrigPreHeader'.
722e8d8bef9SDimitry Andric       {
723e8d8bef9SDimitry Andric         auto &Context = NewHeader->getContext();
724e8d8bef9SDimitry Andric 
725e8d8bef9SDimitry Andric         SmallVector<MDNode *, 8> NoAliasDeclScopes;
726e8d8bef9SDimitry Andric         for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
727e8d8bef9SDimitry Andric           NoAliasDeclScopes.push_back(NAD->getScopeList());
728e8d8bef9SDimitry Andric 
729e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "  Updating OrigHeader scopes\n");
730e8d8bef9SDimitry Andric         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
731e8d8bef9SDimitry Andric                                    "h.rot");
732e8d8bef9SDimitry Andric         LLVM_DEBUG(OrigHeader->dump());
733e8d8bef9SDimitry Andric 
734e8d8bef9SDimitry Andric         // Keep the compile time impact low by only adapting the inserted block
735e8d8bef9SDimitry Andric         // of instructions in the OrigPreHeader. This might result in slightly
736e8d8bef9SDimitry Andric         // more aliasing between these instructions and those that were already
737e8d8bef9SDimitry Andric         // present, but it will be much faster when the original PreHeader is
738e8d8bef9SDimitry Andric         // large.
739e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "  Updating part of OrigPreheader scopes\n");
740e8d8bef9SDimitry Andric         auto *FirstDecl =
741e8d8bef9SDimitry Andric             cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
742e8d8bef9SDimitry Andric         auto *LastInst = &OrigPreheader->back();
743e8d8bef9SDimitry Andric         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
744e8d8bef9SDimitry Andric                                    Context, "pre.rot");
745e8d8bef9SDimitry Andric         LLVM_DEBUG(OrigPreheader->dump());
746e8d8bef9SDimitry Andric 
747e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "  Updated NewHeader:\n");
748e8d8bef9SDimitry Andric         LLVM_DEBUG(NewHeader->dump());
749e8d8bef9SDimitry Andric       }
750e8d8bef9SDimitry Andric     }
751e8d8bef9SDimitry Andric 
7520b57cec5SDimitry Andric     // Along with all the other instructions, we just cloned OrigHeader's
7530b57cec5SDimitry Andric     // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
7540b57cec5SDimitry Andric     // successors by duplicating their incoming values for OrigHeader.
7550b57cec5SDimitry Andric     for (BasicBlock *SuccBB : successors(OrigHeader))
7560b57cec5SDimitry Andric       for (BasicBlock::iterator BI = SuccBB->begin();
7570b57cec5SDimitry Andric            PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
7580b57cec5SDimitry Andric         PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric     // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
7610b57cec5SDimitry Andric     // OrigPreHeader's old terminator (the original branch into the loop), and
7620b57cec5SDimitry Andric     // remove the corresponding incoming values from the PHI nodes in OrigHeader.
7630b57cec5SDimitry Andric     LoopEntryBranch->eraseFromParent();
764*c9157d92SDimitry Andric     OrigPreheader->flushTerminatorDbgValues();
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric     // Update MemorySSA before the rewrite call below changes the 1:1
7670b57cec5SDimitry Andric     // instruction:cloned_instruction_or_value mapping.
7680b57cec5SDimitry Andric     if (MSSAU) {
769480093f4SDimitry Andric       InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
7700b57cec5SDimitry Andric       MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
7710b57cec5SDimitry Andric                                           ValueMapMSSA);
7720b57cec5SDimitry Andric     }
7730b57cec5SDimitry Andric 
7740b57cec5SDimitry Andric     SmallVector<PHINode*, 2> InsertedPHIs;
7750b57cec5SDimitry Andric     // If there were any uses of instructions in the duplicated block outside the
7760b57cec5SDimitry Andric     // loop, update them, inserting PHI nodes as required
777349cc55cSDimitry Andric     RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
7780b57cec5SDimitry Andric                                     &InsertedPHIs);
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric     // Attach dbg.value intrinsics to the new phis if that phi uses a value that
7810b57cec5SDimitry Andric     // previously had debug metadata attached. This keeps the debug info
7820b57cec5SDimitry Andric     // up-to-date in the loop body.
7830b57cec5SDimitry Andric     if (!InsertedPHIs.empty())
7840b57cec5SDimitry Andric       insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric     // NewHeader is now the header of the loop.
7870b57cec5SDimitry Andric     L->moveToHeader(NewHeader);
7880b57cec5SDimitry Andric     assert(L->getHeader() == NewHeader && "Latch block is our new header");
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric     // Inform DT about changes to the CFG.
7910b57cec5SDimitry Andric     if (DT) {
7920b57cec5SDimitry Andric       // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
7930b57cec5SDimitry Andric       // the DT about the removed edge to the OrigHeader (that got removed).
7940b57cec5SDimitry Andric       SmallVector<DominatorTree::UpdateType, 3> Updates;
7950b57cec5SDimitry Andric       Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
7960b57cec5SDimitry Andric       Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
7970b57cec5SDimitry Andric       Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric       if (MSSAU) {
800e8d8bef9SDimitry Andric         MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
8010b57cec5SDimitry Andric         if (VerifyMemorySSA)
8020b57cec5SDimitry Andric           MSSAU->getMemorySSA()->verifyMemorySSA();
803e8d8bef9SDimitry Andric       } else {
804e8d8bef9SDimitry Andric         DT->applyUpdates(Updates);
8050b57cec5SDimitry Andric       }
8060b57cec5SDimitry Andric     }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric     // At this point, we've finished our major CFG changes.  As part of cloning
8090b57cec5SDimitry Andric     // the loop into the preheader we've simplified instructions and the
8100b57cec5SDimitry Andric     // duplicated conditional branch may now be branching on a constant.  If it is
8110b57cec5SDimitry Andric     // branching on a constant and if that constant means that we enter the loop,
8120b57cec5SDimitry Andric     // then we fold away the cond branch to an uncond branch.  This simplifies the
8130b57cec5SDimitry Andric     // loop in cases important for nested loops, and it also means we don't have
8140b57cec5SDimitry Andric     // to split as many edges.
8150b57cec5SDimitry Andric     BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
8160b57cec5SDimitry Andric     assert(PHBI->isConditional() && "Should be clone of BI condbr!");
817*c9157d92SDimitry Andric     const Value *Cond = PHBI->getCondition();
818*c9157d92SDimitry Andric     const bool HasConditionalPreHeader =
819*c9157d92SDimitry Andric         !isa<ConstantInt>(Cond) ||
820*c9157d92SDimitry Andric         PHBI->getSuccessor(cast<ConstantInt>(Cond)->isZero()) != NewHeader;
821*c9157d92SDimitry Andric 
822*c9157d92SDimitry Andric     updateBranchWeights(*PHBI, *BI, HasConditionalPreHeader, BISuccsSwapped);
823*c9157d92SDimitry Andric 
824*c9157d92SDimitry Andric     if (HasConditionalPreHeader) {
8250b57cec5SDimitry Andric       // The conditional branch can't be folded, handle the general case.
8260b57cec5SDimitry Andric       // Split edges as necessary to preserve LoopSimplify form.
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric       // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
8290b57cec5SDimitry Andric       // thus is not a preheader anymore.
8300b57cec5SDimitry Andric       // Split the edge to form a real preheader.
8310b57cec5SDimitry Andric       BasicBlock *NewPH = SplitCriticalEdge(
8320b57cec5SDimitry Andric                                             OrigPreheader, NewHeader,
8330b57cec5SDimitry Andric                                             CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
8340b57cec5SDimitry Andric       NewPH->setName(NewHeader->getName() + ".lr.ph");
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric       // Preserve canonical loop form, which means that 'Exit' should have only
8370b57cec5SDimitry Andric       // one predecessor. Note that Exit could be an exit block for multiple
8380b57cec5SDimitry Andric       // nested loops, causing both of the edges to now be critical and need to
8390b57cec5SDimitry Andric       // be split.
840349cc55cSDimitry Andric       SmallVector<BasicBlock *, 4> ExitPreds(predecessors(Exit));
8410b57cec5SDimitry Andric       bool SplitLatchEdge = false;
8420b57cec5SDimitry Andric       for (BasicBlock *ExitPred : ExitPreds) {
8430b57cec5SDimitry Andric         // We only need to split loop exit edges.
8440b57cec5SDimitry Andric         Loop *PredLoop = LI->getLoopFor(ExitPred);
8450b57cec5SDimitry Andric         if (!PredLoop || PredLoop->contains(Exit) ||
846fcaf7f86SDimitry Andric             isa<IndirectBrInst>(ExitPred->getTerminator()))
8470b57cec5SDimitry Andric           continue;
8480b57cec5SDimitry Andric         SplitLatchEdge |= L->getLoopLatch() == ExitPred;
8490b57cec5SDimitry Andric         BasicBlock *ExitSplit = SplitCriticalEdge(
8500b57cec5SDimitry Andric                                                   ExitPred, Exit,
8510b57cec5SDimitry Andric                                                   CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
8520b57cec5SDimitry Andric         ExitSplit->moveBefore(Exit);
8530b57cec5SDimitry Andric       }
8540b57cec5SDimitry Andric       assert(SplitLatchEdge &&
8550b57cec5SDimitry Andric              "Despite splitting all preds, failed to split latch exit?");
856fe6060f1SDimitry Andric       (void)SplitLatchEdge;
8570b57cec5SDimitry Andric     } else {
8580b57cec5SDimitry Andric       // We can fold the conditional branch in the preheader, this makes things
8590b57cec5SDimitry Andric       // simpler. The first step is to remove the extra edge to the Exit block.
8600b57cec5SDimitry Andric       Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
8610b57cec5SDimitry Andric       BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
8620b57cec5SDimitry Andric       NewBI->setDebugLoc(PHBI->getDebugLoc());
8630b57cec5SDimitry Andric       PHBI->eraseFromParent();
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric       // With our CFG finalized, update DomTree if it is available.
8660b57cec5SDimitry Andric       if (DT) DT->deleteEdge(OrigPreheader, Exit);
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric       // Update MSSA too, if available.
8690b57cec5SDimitry Andric       if (MSSAU)
8700b57cec5SDimitry Andric         MSSAU->removeEdge(OrigPreheader, Exit);
8710b57cec5SDimitry Andric     }
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric     assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
8740b57cec5SDimitry Andric     assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric     if (MSSAU && VerifyMemorySSA)
8770b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric     // Now that the CFG and DomTree are in a consistent state again, try to merge
8800b57cec5SDimitry Andric     // the OrigHeader block into OrigLatch.  This will succeed if they are
8810b57cec5SDimitry Andric     // connected by an unconditional branch.  This is just a cleanup so the
8820b57cec5SDimitry Andric     // emitted code isn't too gross in this common case.
8830b57cec5SDimitry Andric     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
884e8d8bef9SDimitry Andric     BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
885e8d8bef9SDimitry Andric     bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
886e8d8bef9SDimitry Andric     if (DidMerge)
887e8d8bef9SDimitry Andric       RemoveRedundantDbgInstrs(PredBB);
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric     if (MSSAU && VerifyMemorySSA)
8900b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric     ++NumRotated;
8955ffd83dbSDimitry Andric 
8965ffd83dbSDimitry Andric     Rotated = true;
8975ffd83dbSDimitry Andric     SimplifiedLatch = false;
8985ffd83dbSDimitry Andric 
8995ffd83dbSDimitry Andric     // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
9005ffd83dbSDimitry Andric     // Deoptimizing latch exit is not a generally typical case, so we just loop over.
9015ffd83dbSDimitry Andric     // TODO: if it becomes a performance bottleneck extend rotation algorithm
9025ffd83dbSDimitry Andric     // to handle multiple rotations in one go.
9035ffd83dbSDimitry Andric   } while (MultiRotate && canRotateDeoptimizingLatchExit(L));
9045ffd83dbSDimitry Andric 
9055ffd83dbSDimitry Andric 
9060b57cec5SDimitry Andric   return true;
9070b57cec5SDimitry Andric }
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric /// Determine whether the instructions in this range may be safely and cheaply
9100b57cec5SDimitry Andric /// speculated. This is not an important enough situation to develop complex
9110b57cec5SDimitry Andric /// heuristics. We handle a single arithmetic instruction along with any type
9120b57cec5SDimitry Andric /// conversions.
shouldSpeculateInstrs(BasicBlock::iterator Begin,BasicBlock::iterator End,Loop * L)9130b57cec5SDimitry Andric static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
9140b57cec5SDimitry Andric                                   BasicBlock::iterator End, Loop *L) {
9150b57cec5SDimitry Andric   bool seenIncrement = false;
9160b57cec5SDimitry Andric   bool MultiExitLoop = false;
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   if (!L->getExitingBlock())
9190b57cec5SDimitry Andric     MultiExitLoop = true;
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   for (BasicBlock::iterator I = Begin; I != End; ++I) {
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric     if (!isSafeToSpeculativelyExecute(&*I))
9240b57cec5SDimitry Andric       return false;
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric     if (isa<DbgInfoIntrinsic>(I))
9270b57cec5SDimitry Andric       continue;
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric     switch (I->getOpcode()) {
9300b57cec5SDimitry Andric     default:
9310b57cec5SDimitry Andric       return false;
9320b57cec5SDimitry Andric     case Instruction::GetElementPtr:
9330b57cec5SDimitry Andric       // GEPs are cheap if all indices are constant.
9340b57cec5SDimitry Andric       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
9350b57cec5SDimitry Andric         return false;
9360b57cec5SDimitry Andric       // fall-thru to increment case
937bdd1243dSDimitry Andric       [[fallthrough]];
9380b57cec5SDimitry Andric     case Instruction::Add:
9390b57cec5SDimitry Andric     case Instruction::Sub:
9400b57cec5SDimitry Andric     case Instruction::And:
9410b57cec5SDimitry Andric     case Instruction::Or:
9420b57cec5SDimitry Andric     case Instruction::Xor:
9430b57cec5SDimitry Andric     case Instruction::Shl:
9440b57cec5SDimitry Andric     case Instruction::LShr:
9450b57cec5SDimitry Andric     case Instruction::AShr: {
9460b57cec5SDimitry Andric       Value *IVOpnd =
9470b57cec5SDimitry Andric           !isa<Constant>(I->getOperand(0))
9480b57cec5SDimitry Andric               ? I->getOperand(0)
9490b57cec5SDimitry Andric               : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
9500b57cec5SDimitry Andric       if (!IVOpnd)
9510b57cec5SDimitry Andric         return false;
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric       // If increment operand is used outside of the loop, this speculation
9540b57cec5SDimitry Andric       // could cause extra live range interference.
9550b57cec5SDimitry Andric       if (MultiExitLoop) {
9560b57cec5SDimitry Andric         for (User *UseI : IVOpnd->users()) {
9570b57cec5SDimitry Andric           auto *UserInst = cast<Instruction>(UseI);
9580b57cec5SDimitry Andric           if (!L->contains(UserInst))
9590b57cec5SDimitry Andric             return false;
9600b57cec5SDimitry Andric         }
9610b57cec5SDimitry Andric       }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric       if (seenIncrement)
9640b57cec5SDimitry Andric         return false;
9650b57cec5SDimitry Andric       seenIncrement = true;
9660b57cec5SDimitry Andric       break;
9670b57cec5SDimitry Andric     }
9680b57cec5SDimitry Andric     case Instruction::Trunc:
9690b57cec5SDimitry Andric     case Instruction::ZExt:
9700b57cec5SDimitry Andric     case Instruction::SExt:
9710b57cec5SDimitry Andric       // ignore type conversions
9720b57cec5SDimitry Andric       break;
9730b57cec5SDimitry Andric     }
9740b57cec5SDimitry Andric   }
9750b57cec5SDimitry Andric   return true;
9760b57cec5SDimitry Andric }
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric /// Fold the loop tail into the loop exit by speculating the loop tail
9790b57cec5SDimitry Andric /// instructions. Typically, this is a single post-increment. In the case of a
9800b57cec5SDimitry Andric /// simple 2-block loop, hoisting the increment can be much better than
9810b57cec5SDimitry Andric /// duplicating the entire loop header. In the case of loops with early exits,
9820b57cec5SDimitry Andric /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
9830b57cec5SDimitry Andric /// canonical form so downstream passes can handle it.
9840b57cec5SDimitry Andric ///
9850b57cec5SDimitry Andric /// I don't believe this invalidates SCEV.
simplifyLoopLatch(Loop * L)9860b57cec5SDimitry Andric bool LoopRotate::simplifyLoopLatch(Loop *L) {
9870b57cec5SDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
9880b57cec5SDimitry Andric   if (!Latch || Latch->hasAddressTaken())
9890b57cec5SDimitry Andric     return false;
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
9920b57cec5SDimitry Andric   if (!Jmp || !Jmp->isUnconditional())
9930b57cec5SDimitry Andric     return false;
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric   BasicBlock *LastExit = Latch->getSinglePredecessor();
9960b57cec5SDimitry Andric   if (!LastExit || !L->isLoopExiting(LastExit))
9970b57cec5SDimitry Andric     return false;
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
10000b57cec5SDimitry Andric   if (!BI)
10010b57cec5SDimitry Andric     return false;
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
10040b57cec5SDimitry Andric     return false;
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
10070b57cec5SDimitry Andric                     << LastExit->getName() << "\n");
10080b57cec5SDimitry Andric 
10098bcb0991SDimitry Andric   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
10108bcb0991SDimitry Andric   MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
10118bcb0991SDimitry Andric                             /*PredecessorWithTwoSuccessors=*/true);
10120b57cec5SDimitry Andric 
1013bdd1243dSDimitry Andric     if (SE) {
1014bdd1243dSDimitry Andric       // Merging blocks may remove blocks reference in the block disposition cache. Clear the cache.
1015bdd1243dSDimitry Andric       SE->forgetBlockAndLoopDispositions();
1016bdd1243dSDimitry Andric     }
1017bdd1243dSDimitry Andric 
10180b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
10190b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
10200b57cec5SDimitry Andric 
10210b57cec5SDimitry Andric   return true;
10220b57cec5SDimitry Andric }
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric /// Rotate \c L, and return true if any modification was made.
processLoop(Loop * L)10250b57cec5SDimitry Andric bool LoopRotate::processLoop(Loop *L) {
10260b57cec5SDimitry Andric   // Save the loop metadata.
10270b57cec5SDimitry Andric   MDNode *LoopMD = L->getLoopID();
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   bool SimplifiedLatch = false;
10300b57cec5SDimitry Andric 
10310b57cec5SDimitry Andric   // Simplify the loop latch before attempting to rotate the header
10320b57cec5SDimitry Andric   // upward. Rotation may not be needed if the loop tail can be folded into the
10330b57cec5SDimitry Andric   // loop exit.
10340b57cec5SDimitry Andric   if (!RotationOnly)
10350b57cec5SDimitry Andric     SimplifiedLatch = simplifyLoopLatch(L);
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric   bool MadeChange = rotateLoop(L, SimplifiedLatch);
10380b57cec5SDimitry Andric   assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
10390b57cec5SDimitry Andric          "Loop latch should be exiting after loop-rotate.");
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric   // Restore the loop metadata.
10420b57cec5SDimitry Andric   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
10430b57cec5SDimitry Andric   if ((MadeChange || SimplifiedLatch) && LoopMD)
10440b57cec5SDimitry Andric     L->setLoopID(LoopMD);
10450b57cec5SDimitry Andric 
10460b57cec5SDimitry Andric   return MadeChange || SimplifiedLatch;
10470b57cec5SDimitry Andric }
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric /// The utility to convert a loop into a loop with bottom test.
LoopRotation(Loop * L,LoopInfo * LI,const TargetTransformInfo * TTI,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE,MemorySSAUpdater * MSSAU,const SimplifyQuery & SQ,bool RotationOnly=true,unsigned Threshold=unsigned (-1),bool IsUtilMode=true,bool PrepareForLTO)10510b57cec5SDimitry Andric bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
10520b57cec5SDimitry Andric                         AssumptionCache *AC, DominatorTree *DT,
10530b57cec5SDimitry Andric                         ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
10540b57cec5SDimitry Andric                         const SimplifyQuery &SQ, bool RotationOnly = true,
10550b57cec5SDimitry Andric                         unsigned Threshold = unsigned(-1),
1056e8d8bef9SDimitry Andric                         bool IsUtilMode = true, bool PrepareForLTO) {
10570b57cec5SDimitry Andric   LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
1058e8d8bef9SDimitry Andric                 IsUtilMode, PrepareForLTO);
10590b57cec5SDimitry Andric   return LR.processLoop(L);
10600b57cec5SDimitry Andric }
1061