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/BasicAliasAnalysis.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/LoopPass.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
280b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
29*5f7ddb14SDimitry Andric #include "llvm/IR/DebugInfo.h"
300b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
310b57cec5SDimitry Andric #include "llvm/IR/Function.h"
320b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
330b57cec5SDimitry Andric #include "llvm/IR/Module.h"
340b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
350b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
360b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
370b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38af732203SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
390b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
400b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
410b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdater.h"
420b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
430b57cec5SDimitry Andric using namespace llvm;
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric #define DEBUG_TYPE "loop-rotate"
460b57cec5SDimitry Andric 
47af732203SDimitry Andric STATISTIC(NumNotRotatedDueToHeaderSize,
48af732203SDimitry Andric           "Number of loops not rotated due to the header size");
49*5f7ddb14SDimitry Andric STATISTIC(NumInstrsHoisted,
50*5f7ddb14SDimitry Andric           "Number of instructions hoisted into loop preheader");
51*5f7ddb14SDimitry Andric STATISTIC(NumInstrsDuplicated,
52*5f7ddb14SDimitry Andric           "Number of instructions cloned into loop preheader");
530b57cec5SDimitry Andric STATISTIC(NumRotated, "Number of loops rotated");
540b57cec5SDimitry Andric 
555ffd83dbSDimitry Andric static cl::opt<bool>
565ffd83dbSDimitry Andric     MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
575ffd83dbSDimitry Andric                 cl::desc("Allow loop rotation multiple times in order to reach "
585ffd83dbSDimitry Andric                          "a better latch exit"));
595ffd83dbSDimitry Andric 
600b57cec5SDimitry Andric namespace {
610b57cec5SDimitry Andric /// A simple loop rotation transformation.
620b57cec5SDimitry Andric class LoopRotate {
630b57cec5SDimitry Andric   const unsigned MaxHeaderSize;
640b57cec5SDimitry Andric   LoopInfo *LI;
650b57cec5SDimitry Andric   const TargetTransformInfo *TTI;
660b57cec5SDimitry Andric   AssumptionCache *AC;
670b57cec5SDimitry Andric   DominatorTree *DT;
680b57cec5SDimitry Andric   ScalarEvolution *SE;
690b57cec5SDimitry Andric   MemorySSAUpdater *MSSAU;
700b57cec5SDimitry Andric   const SimplifyQuery &SQ;
710b57cec5SDimitry Andric   bool RotationOnly;
720b57cec5SDimitry Andric   bool IsUtilMode;
73af732203SDimitry Andric   bool PrepareForLTO;
740b57cec5SDimitry Andric 
750b57cec5SDimitry 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)760b57cec5SDimitry Andric   LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
770b57cec5SDimitry Andric              const TargetTransformInfo *TTI, AssumptionCache *AC,
780b57cec5SDimitry Andric              DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
79af732203SDimitry Andric              const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
80af732203SDimitry Andric              bool PrepareForLTO)
810b57cec5SDimitry Andric       : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
820b57cec5SDimitry Andric         MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
83af732203SDimitry Andric         IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
840b57cec5SDimitry Andric   bool processLoop(Loop *L);
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric private:
870b57cec5SDimitry Andric   bool rotateLoop(Loop *L, bool SimplifiedLatch);
880b57cec5SDimitry Andric   bool simplifyLoopLatch(Loop *L);
890b57cec5SDimitry Andric };
900b57cec5SDimitry Andric } // end anonymous namespace
910b57cec5SDimitry Andric 
92480093f4SDimitry Andric /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
93480093f4SDimitry Andric /// previously exist in the map, and the value was inserted.
InsertNewValueIntoMap(ValueToValueMapTy & VM,Value * K,Value * V)94480093f4SDimitry Andric static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) {
95480093f4SDimitry Andric   bool Inserted = VM.insert({K, V}).second;
96480093f4SDimitry Andric   assert(Inserted);
97480093f4SDimitry Andric   (void)Inserted;
98480093f4SDimitry Andric }
990b57cec5SDimitry Andric /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
1000b57cec5SDimitry Andric /// old header into the preheader.  If there were uses of the values produced by
1010b57cec5SDimitry Andric /// these instruction that were outside of the loop, we have to insert PHI nodes
1020b57cec5SDimitry Andric /// to merge the two values.  Do this now.
RewriteUsesOfClonedInstructions(BasicBlock * OrigHeader,BasicBlock * OrigPreheader,ValueToValueMapTy & ValueMap,SmallVectorImpl<PHINode * > * InsertedPHIs)1030b57cec5SDimitry Andric static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
1040b57cec5SDimitry Andric                                             BasicBlock *OrigPreheader,
1050b57cec5SDimitry Andric                                             ValueToValueMapTy &ValueMap,
1060b57cec5SDimitry Andric                                 SmallVectorImpl<PHINode*> *InsertedPHIs) {
1070b57cec5SDimitry Andric   // Remove PHI node entries that are no longer live.
1080b57cec5SDimitry Andric   BasicBlock::iterator I, E = OrigHeader->end();
1090b57cec5SDimitry Andric   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
1100b57cec5SDimitry Andric     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
1130b57cec5SDimitry Andric   // as necessary.
1140b57cec5SDimitry Andric   SSAUpdater SSA(InsertedPHIs);
1150b57cec5SDimitry Andric   for (I = OrigHeader->begin(); I != E; ++I) {
1160b57cec5SDimitry Andric     Value *OrigHeaderVal = &*I;
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric     // If there are no uses of the value (e.g. because it returns void), there
1190b57cec5SDimitry Andric     // is nothing to rewrite.
1200b57cec5SDimitry Andric     if (OrigHeaderVal->use_empty())
1210b57cec5SDimitry Andric       continue;
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric     Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric     // The value now exits in two versions: the initial value in the preheader
1260b57cec5SDimitry Andric     // and the loop "next" value in the original header.
1270b57cec5SDimitry Andric     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
1280b57cec5SDimitry Andric     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
1290b57cec5SDimitry Andric     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric     // Visit each use of the OrigHeader instruction.
1320b57cec5SDimitry Andric     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
1330b57cec5SDimitry Andric                              UE = OrigHeaderVal->use_end();
1340b57cec5SDimitry Andric          UI != UE;) {
1350b57cec5SDimitry Andric       // Grab the use before incrementing the iterator.
1360b57cec5SDimitry Andric       Use &U = *UI;
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric       // Increment the iterator before removing the use from the list.
1390b57cec5SDimitry Andric       ++UI;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric       // SSAUpdater can't handle a non-PHI use in the same block as an
1420b57cec5SDimitry Andric       // earlier def. We can easily handle those cases manually.
1430b57cec5SDimitry Andric       Instruction *UserInst = cast<Instruction>(U.getUser());
1440b57cec5SDimitry Andric       if (!isa<PHINode>(UserInst)) {
1450b57cec5SDimitry Andric         BasicBlock *UserBB = UserInst->getParent();
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric         // The original users in the OrigHeader are already using the
1480b57cec5SDimitry Andric         // original definitions.
1490b57cec5SDimitry Andric         if (UserBB == OrigHeader)
1500b57cec5SDimitry Andric           continue;
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric         // Users in the OrigPreHeader need to use the value to which the
1530b57cec5SDimitry Andric         // original definitions are mapped.
1540b57cec5SDimitry Andric         if (UserBB == OrigPreheader) {
1550b57cec5SDimitry Andric           U = OrigPreHeaderVal;
1560b57cec5SDimitry Andric           continue;
1570b57cec5SDimitry Andric         }
1580b57cec5SDimitry Andric       }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric       // Anything else can be handled by SSAUpdater.
1610b57cec5SDimitry Andric       SSA.RewriteUse(U);
1620b57cec5SDimitry Andric     }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric     // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
1650b57cec5SDimitry Andric     // intrinsics.
1660b57cec5SDimitry Andric     SmallVector<DbgValueInst *, 1> DbgValues;
1670b57cec5SDimitry Andric     llvm::findDbgValues(DbgValues, OrigHeaderVal);
1680b57cec5SDimitry Andric     for (auto &DbgValue : DbgValues) {
1690b57cec5SDimitry Andric       // The original users in the OrigHeader are already using the original
1700b57cec5SDimitry Andric       // definitions.
1710b57cec5SDimitry Andric       BasicBlock *UserBB = DbgValue->getParent();
1720b57cec5SDimitry Andric       if (UserBB == OrigHeader)
1730b57cec5SDimitry Andric         continue;
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric       // Users in the OrigPreHeader need to use the value to which the
1760b57cec5SDimitry Andric       // original definitions are mapped and anything else can be handled by
1770b57cec5SDimitry Andric       // the SSAUpdater. To avoid adding PHINodes, check if the value is
1780b57cec5SDimitry Andric       // available in UserBB, if not substitute undef.
1790b57cec5SDimitry Andric       Value *NewVal;
1800b57cec5SDimitry Andric       if (UserBB == OrigPreheader)
1810b57cec5SDimitry Andric         NewVal = OrigPreHeaderVal;
1820b57cec5SDimitry Andric       else if (SSA.HasValueForBlock(UserBB))
1830b57cec5SDimitry Andric         NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
1840b57cec5SDimitry Andric       else
1850b57cec5SDimitry Andric         NewVal = UndefValue::get(OrigHeaderVal->getType());
186*5f7ddb14SDimitry Andric       DbgValue->replaceVariableLocationOp(OrigHeaderVal, NewVal);
1870b57cec5SDimitry Andric     }
1880b57cec5SDimitry Andric   }
1890b57cec5SDimitry Andric }
1900b57cec5SDimitry Andric 
1915ffd83dbSDimitry Andric // Assuming both header and latch are exiting, look for a phi which is only
1925ffd83dbSDimitry Andric // used outside the loop (via a LCSSA phi) in the exit from the header.
1935ffd83dbSDimitry Andric // This means that rotating the loop can remove the phi.
profitableToRotateLoopExitingLatch(Loop * L)1945ffd83dbSDimitry Andric static bool profitableToRotateLoopExitingLatch(Loop *L) {
1950b57cec5SDimitry Andric   BasicBlock *Header = L->getHeader();
1965ffd83dbSDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
1975ffd83dbSDimitry Andric   assert(BI && BI->isConditional() && "need header with conditional exit");
1985ffd83dbSDimitry Andric   BasicBlock *HeaderExit = BI->getSuccessor(0);
1990b57cec5SDimitry Andric   if (L->contains(HeaderExit))
2005ffd83dbSDimitry Andric     HeaderExit = BI->getSuccessor(1);
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   for (auto &Phi : Header->phis()) {
2030b57cec5SDimitry Andric     // Look for uses of this phi in the loop/via exits other than the header.
2040b57cec5SDimitry Andric     if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
2050b57cec5SDimitry Andric           return cast<Instruction>(U)->getParent() != HeaderExit;
2060b57cec5SDimitry Andric         }))
2070b57cec5SDimitry Andric       continue;
2080b57cec5SDimitry Andric     return true;
2090b57cec5SDimitry Andric   }
2105ffd83dbSDimitry Andric   return false;
2115ffd83dbSDimitry Andric }
2120b57cec5SDimitry Andric 
2135ffd83dbSDimitry Andric // Check that latch exit is deoptimizing (which means - very unlikely to happen)
2145ffd83dbSDimitry Andric // and there is another exit from the loop which is non-deoptimizing.
2155ffd83dbSDimitry Andric // If we rotate latch to that exit our loop has a better chance of being fully
2165ffd83dbSDimitry Andric // canonical.
2175ffd83dbSDimitry Andric //
2185ffd83dbSDimitry Andric // It can give false positives in some rare cases.
canRotateDeoptimizingLatchExit(Loop * L)2195ffd83dbSDimitry Andric static bool canRotateDeoptimizingLatchExit(Loop *L) {
2205ffd83dbSDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
2215ffd83dbSDimitry Andric   assert(Latch && "need latch");
2225ffd83dbSDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
2235ffd83dbSDimitry Andric   // Need normal exiting latch.
2245ffd83dbSDimitry Andric   if (!BI || !BI->isConditional())
2255ffd83dbSDimitry Andric     return false;
2265ffd83dbSDimitry Andric 
2275ffd83dbSDimitry Andric   BasicBlock *Exit = BI->getSuccessor(1);
2285ffd83dbSDimitry Andric   if (L->contains(Exit))
2295ffd83dbSDimitry Andric     Exit = BI->getSuccessor(0);
2305ffd83dbSDimitry Andric 
2315ffd83dbSDimitry Andric   // Latch exit is non-deoptimizing, no need to rotate.
2325ffd83dbSDimitry Andric   if (!Exit->getPostdominatingDeoptimizeCall())
2335ffd83dbSDimitry Andric     return false;
2345ffd83dbSDimitry Andric 
2355ffd83dbSDimitry Andric   SmallVector<BasicBlock *, 4> Exits;
2365ffd83dbSDimitry Andric   L->getUniqueExitBlocks(Exits);
2375ffd83dbSDimitry Andric   if (!Exits.empty()) {
2385ffd83dbSDimitry Andric     // There is at least one non-deoptimizing exit.
2395ffd83dbSDimitry Andric     //
2405ffd83dbSDimitry Andric     // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
2415ffd83dbSDimitry Andric     // as it can conservatively return false for deoptimizing exits with
2425ffd83dbSDimitry Andric     // complex enough control flow down to deoptimize call.
2435ffd83dbSDimitry Andric     //
2445ffd83dbSDimitry Andric     // That means here we can report success for a case where
2455ffd83dbSDimitry Andric     // all exits are deoptimizing but one of them has complex enough
2465ffd83dbSDimitry Andric     // control flow (e.g. with loops).
2475ffd83dbSDimitry Andric     //
2485ffd83dbSDimitry Andric     // That should be a very rare case and false positives for this function
2495ffd83dbSDimitry Andric     // have compile-time effect only.
2505ffd83dbSDimitry Andric     return any_of(Exits, [](const BasicBlock *BB) {
2515ffd83dbSDimitry Andric       return !BB->getPostdominatingDeoptimizeCall();
2525ffd83dbSDimitry Andric     });
2535ffd83dbSDimitry Andric   }
2540b57cec5SDimitry Andric   return false;
2550b57cec5SDimitry Andric }
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric /// Rotate loop LP. Return true if the loop is rotated.
2580b57cec5SDimitry Andric ///
2590b57cec5SDimitry Andric /// \param SimplifiedLatch is true if the latch was just folded into the final
2600b57cec5SDimitry Andric /// loop exit. In this case we may want to rotate even though the new latch is
2610b57cec5SDimitry Andric /// now an exiting branch. This rotation would have happened had the latch not
2620b57cec5SDimitry Andric /// been simplified. However, if SimplifiedLatch is false, then we avoid
2630b57cec5SDimitry Andric /// rotating loops in which the latch exits to avoid excessive or endless
2640b57cec5SDimitry Andric /// rotation. LoopRotate should be repeatable and converge to a canonical
2650b57cec5SDimitry Andric /// form. This property is satisfied because simplifying the loop latch can only
2660b57cec5SDimitry Andric /// happen once across multiple invocations of the LoopRotate pass.
2675ffd83dbSDimitry Andric ///
2685ffd83dbSDimitry Andric /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
2695ffd83dbSDimitry Andric /// so to reach a suitable (non-deoptimizing) exit.
rotateLoop(Loop * L,bool SimplifiedLatch)2700b57cec5SDimitry Andric bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
2710b57cec5SDimitry Andric   // If the loop has only one block then there is not much to rotate.
2720b57cec5SDimitry Andric   if (L->getBlocks().size() == 1)
2730b57cec5SDimitry Andric     return false;
2740b57cec5SDimitry Andric 
2755ffd83dbSDimitry Andric   bool Rotated = false;
2765ffd83dbSDimitry Andric   do {
2770b57cec5SDimitry Andric     BasicBlock *OrigHeader = L->getHeader();
2780b57cec5SDimitry Andric     BasicBlock *OrigLatch = L->getLoopLatch();
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
2810b57cec5SDimitry Andric     if (!BI || BI->isUnconditional())
2825ffd83dbSDimitry Andric       return Rotated;
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric     // If the loop header is not one of the loop exiting blocks then
2850b57cec5SDimitry Andric     // either this loop is already rotated or it is not
2860b57cec5SDimitry Andric     // suitable for loop rotation transformations.
2870b57cec5SDimitry Andric     if (!L->isLoopExiting(OrigHeader))
2885ffd83dbSDimitry Andric       return Rotated;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric     // If the loop latch already contains a branch that leaves the loop then the
2910b57cec5SDimitry Andric     // loop is already rotated.
2920b57cec5SDimitry Andric     if (!OrigLatch)
2935ffd83dbSDimitry Andric       return Rotated;
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric     // Rotate if either the loop latch does *not* exit the loop, or if the loop
2960b57cec5SDimitry Andric     // latch was just simplified. Or if we think it will be profitable.
2970b57cec5SDimitry Andric     if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
2985ffd83dbSDimitry Andric         !profitableToRotateLoopExitingLatch(L) &&
2995ffd83dbSDimitry Andric         !canRotateDeoptimizingLatchExit(L))
3005ffd83dbSDimitry Andric       return Rotated;
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric     // Check size of original header and reject loop if it is very big or we can't
3030b57cec5SDimitry Andric     // duplicate blocks inside it.
3040b57cec5SDimitry Andric     {
3050b57cec5SDimitry Andric       SmallPtrSet<const Value *, 32> EphValues;
3060b57cec5SDimitry Andric       CodeMetrics::collectEphemeralValues(L, AC, EphValues);
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric       CodeMetrics Metrics;
309af732203SDimitry Andric       Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
3100b57cec5SDimitry Andric       if (Metrics.notDuplicatable) {
3110b57cec5SDimitry Andric         LLVM_DEBUG(
3120b57cec5SDimitry Andric                    dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
3130b57cec5SDimitry Andric                    << " instructions: ";
3140b57cec5SDimitry Andric                    L->dump());
3155ffd83dbSDimitry Andric         return Rotated;
3160b57cec5SDimitry Andric       }
3170b57cec5SDimitry Andric       if (Metrics.convergent) {
3180b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
3190b57cec5SDimitry Andric                    "instructions: ";
3200b57cec5SDimitry Andric                    L->dump());
3215ffd83dbSDimitry Andric         return Rotated;
3220b57cec5SDimitry Andric       }
3235ffd83dbSDimitry Andric       if (Metrics.NumInsts > MaxHeaderSize) {
3245ffd83dbSDimitry Andric         LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
3255ffd83dbSDimitry Andric                           << Metrics.NumInsts
3265ffd83dbSDimitry Andric                           << " instructions, which is more than the threshold ("
3275ffd83dbSDimitry Andric                           << MaxHeaderSize << " instructions): ";
3285ffd83dbSDimitry Andric                    L->dump());
329af732203SDimitry Andric         ++NumNotRotatedDueToHeaderSize;
3305ffd83dbSDimitry Andric         return Rotated;
3315ffd83dbSDimitry Andric       }
332af732203SDimitry Andric 
333af732203SDimitry Andric       // When preparing for LTO, avoid rotating loops with calls that could be
334af732203SDimitry Andric       // inlined during the LTO stage.
335af732203SDimitry Andric       if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
336af732203SDimitry Andric         return Rotated;
3370b57cec5SDimitry Andric     }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric     // Now, this loop is suitable for rotation.
3400b57cec5SDimitry Andric     BasicBlock *OrigPreheader = L->getLoopPreheader();
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric     // If the loop could not be converted to canonical form, it must have an
3430b57cec5SDimitry Andric     // indirectbr in it, just give up.
3440b57cec5SDimitry Andric     if (!OrigPreheader || !L->hasDedicatedExits())
3455ffd83dbSDimitry Andric       return Rotated;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric     // Anything ScalarEvolution may know about this loop or the PHI nodes
3480b57cec5SDimitry Andric     // in its header will soon be invalidated. We should also invalidate
3490b57cec5SDimitry Andric     // all outer loops because insertion and deletion of blocks that happens
3500b57cec5SDimitry Andric     // during the rotation may violate invariants related to backedge taken
3510b57cec5SDimitry Andric     // infos in them.
3520b57cec5SDimitry Andric     if (SE)
3530b57cec5SDimitry Andric       SE->forgetTopmostLoop(L);
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
3560b57cec5SDimitry Andric     if (MSSAU && VerifyMemorySSA)
3570b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric     // Find new Loop header. NewHeader is a Header's one and only successor
3600b57cec5SDimitry Andric     // that is inside loop.  Header's other successor is outside the
3610b57cec5SDimitry Andric     // loop.  Otherwise loop is not suitable for rotation.
3620b57cec5SDimitry Andric     BasicBlock *Exit = BI->getSuccessor(0);
3630b57cec5SDimitry Andric     BasicBlock *NewHeader = BI->getSuccessor(1);
3640b57cec5SDimitry Andric     if (L->contains(Exit))
3650b57cec5SDimitry Andric       std::swap(Exit, NewHeader);
3660b57cec5SDimitry Andric     assert(NewHeader && "Unable to determine new loop header");
3670b57cec5SDimitry Andric     assert(L->contains(NewHeader) && !L->contains(Exit) &&
3680b57cec5SDimitry Andric            "Unable to determine loop header and exit blocks");
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric     // This code assumes that the new header has exactly one predecessor.
3710b57cec5SDimitry Andric     // Remove any single-entry PHI nodes in it.
3720b57cec5SDimitry Andric     assert(NewHeader->getSinglePredecessor() &&
3730b57cec5SDimitry Andric            "New header doesn't have one pred!");
3740b57cec5SDimitry Andric     FoldSingleEntryPHINodes(NewHeader);
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric     // Begin by walking OrigHeader and populating ValueMap with an entry for
3770b57cec5SDimitry Andric     // each Instruction.
3780b57cec5SDimitry Andric     BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
3790b57cec5SDimitry Andric     ValueToValueMapTy ValueMap, ValueMapMSSA;
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric     // For PHI nodes, the value available in OldPreHeader is just the
3820b57cec5SDimitry Andric     // incoming value from OldPreHeader.
3830b57cec5SDimitry Andric     for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
384480093f4SDimitry Andric       InsertNewValueIntoMap(ValueMap, PN,
385480093f4SDimitry Andric                             PN->getIncomingValueForBlock(OrigPreheader));
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric     // For the rest of the instructions, either hoist to the OrigPreheader if
3880b57cec5SDimitry Andric     // possible or create a clone in the OldPreHeader if not.
3890b57cec5SDimitry Andric     Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
3900b57cec5SDimitry Andric 
391*5f7ddb14SDimitry Andric     // Record all debug intrinsics preceding LoopEntryBranch to avoid
392*5f7ddb14SDimitry Andric     // duplication.
3930b57cec5SDimitry Andric     using DbgIntrinsicHash =
394*5f7ddb14SDimitry Andric         std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
3950b57cec5SDimitry Andric     auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
396*5f7ddb14SDimitry Andric       auto VarLocOps = D->location_ops();
397*5f7ddb14SDimitry Andric       return {{hash_combine_range(VarLocOps.begin(), VarLocOps.end()),
398*5f7ddb14SDimitry Andric                D->getVariable()},
399*5f7ddb14SDimitry Andric               D->getExpression()};
4000b57cec5SDimitry Andric     };
4010b57cec5SDimitry Andric     SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
4020b57cec5SDimitry Andric     for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend();
4030b57cec5SDimitry Andric          I != E; ++I) {
4040b57cec5SDimitry Andric       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&*I))
4050b57cec5SDimitry Andric         DbgIntrinsics.insert(makeHash(DII));
4060b57cec5SDimitry Andric       else
4070b57cec5SDimitry Andric         break;
4080b57cec5SDimitry Andric     }
4090b57cec5SDimitry Andric 
410af732203SDimitry Andric     // Remember the local noalias scope declarations in the header. After the
411af732203SDimitry Andric     // rotation, they must be duplicated and the scope must be cloned. This
412af732203SDimitry Andric     // avoids unwanted interaction across iterations.
413af732203SDimitry Andric     SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
414af732203SDimitry Andric     for (Instruction &I : *OrigHeader)
415af732203SDimitry Andric       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
416af732203SDimitry Andric         NoAliasDeclInstructions.push_back(Decl);
417af732203SDimitry Andric 
4180b57cec5SDimitry Andric     while (I != E) {
4190b57cec5SDimitry Andric       Instruction *Inst = &*I++;
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric       // If the instruction's operands are invariant and it doesn't read or write
4220b57cec5SDimitry Andric       // memory, then it is safe to hoist.  Doing this doesn't change the order of
4230b57cec5SDimitry Andric       // execution in the preheader, but does prevent the instruction from
4240b57cec5SDimitry Andric       // executing in each iteration of the loop.  This means it is safe to hoist
4250b57cec5SDimitry Andric       // something that might trap, but isn't safe to hoist something that reads
4260b57cec5SDimitry Andric       // memory (without proving that the loop doesn't write).
4270b57cec5SDimitry Andric       if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
4280b57cec5SDimitry Andric           !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
4290b57cec5SDimitry Andric           !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
4300b57cec5SDimitry Andric         Inst->moveBefore(LoopEntryBranch);
431*5f7ddb14SDimitry Andric         ++NumInstrsHoisted;
4320b57cec5SDimitry Andric         continue;
4330b57cec5SDimitry Andric       }
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric       // Otherwise, create a duplicate of the instruction.
4360b57cec5SDimitry Andric       Instruction *C = Inst->clone();
437*5f7ddb14SDimitry Andric       ++NumInstrsDuplicated;
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric       // Eagerly remap the operands of the instruction.
4400b57cec5SDimitry Andric       RemapInstruction(C, ValueMap,
4410b57cec5SDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric       // Avoid inserting the same intrinsic twice.
4440b57cec5SDimitry Andric       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
4450b57cec5SDimitry Andric         if (DbgIntrinsics.count(makeHash(DII))) {
4460b57cec5SDimitry Andric           C->deleteValue();
4470b57cec5SDimitry Andric           continue;
4480b57cec5SDimitry Andric         }
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric       // With the operands remapped, see if the instruction constant folds or is
4510b57cec5SDimitry Andric       // otherwise simplifyable.  This commonly occurs because the entry from PHI
4520b57cec5SDimitry Andric       // nodes allows icmps and other instructions to fold.
4530b57cec5SDimitry Andric       Value *V = SimplifyInstruction(C, SQ);
4540b57cec5SDimitry Andric       if (V && LI->replacementPreservesLCSSAForm(C, V)) {
4550b57cec5SDimitry Andric         // If so, then delete the temporary instruction and stick the folded value
4560b57cec5SDimitry Andric         // in the map.
457480093f4SDimitry Andric         InsertNewValueIntoMap(ValueMap, Inst, V);
4580b57cec5SDimitry Andric         if (!C->mayHaveSideEffects()) {
4590b57cec5SDimitry Andric           C->deleteValue();
4600b57cec5SDimitry Andric           C = nullptr;
4610b57cec5SDimitry Andric         }
4620b57cec5SDimitry Andric       } else {
463480093f4SDimitry Andric         InsertNewValueIntoMap(ValueMap, Inst, C);
4640b57cec5SDimitry Andric       }
4650b57cec5SDimitry Andric       if (C) {
4660b57cec5SDimitry Andric         // Otherwise, stick the new instruction into the new block!
4670b57cec5SDimitry Andric         C->setName(Inst->getName());
4680b57cec5SDimitry Andric         C->insertBefore(LoopEntryBranch);
4690b57cec5SDimitry Andric 
470*5f7ddb14SDimitry Andric         if (auto *II = dyn_cast<AssumeInst>(C))
4710b57cec5SDimitry Andric           AC->registerAssumption(II);
4720b57cec5SDimitry Andric         // MemorySSA cares whether the cloned instruction was inserted or not, and
4730b57cec5SDimitry Andric         // not whether it can be remapped to a simplified value.
474480093f4SDimitry Andric         if (MSSAU)
475480093f4SDimitry Andric           InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
4760b57cec5SDimitry Andric       }
4770b57cec5SDimitry Andric     }
4780b57cec5SDimitry Andric 
479af732203SDimitry Andric     if (!NoAliasDeclInstructions.empty()) {
480af732203SDimitry Andric       // There are noalias scope declarations:
481af732203SDimitry Andric       // (general):
482af732203SDimitry Andric       // Original:    OrigPre              { OrigHeader NewHeader ... Latch }
483af732203SDimitry Andric       // after:      (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
484af732203SDimitry Andric       //
485af732203SDimitry Andric       // with D: llvm.experimental.noalias.scope.decl,
486af732203SDimitry Andric       //      U: !noalias or !alias.scope depending on D
487af732203SDimitry Andric       //       ... { D U1 U2 }   can transform into:
488af732203SDimitry Andric       // (0) : ... { D U1 U2 }        // no relevant rotation for this part
489af732203SDimitry Andric       // (1) : ... D' { U1 U2 D }     // D is part of OrigHeader
490af732203SDimitry Andric       // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
491af732203SDimitry Andric       //
492af732203SDimitry Andric       // We now want to transform:
493af732203SDimitry Andric       // (1) -> : ... D' { D U1 U2 D'' }
494af732203SDimitry Andric       // (2) -> : ... D' U1' { D U2 D'' U1'' }
495af732203SDimitry Andric       // D: original llvm.experimental.noalias.scope.decl
496af732203SDimitry Andric       // D', U1': duplicate with replaced scopes
497af732203SDimitry Andric       // D'', U1'': different duplicate with replaced scopes
498af732203SDimitry Andric       // This ensures a safe fallback to 'may_alias' introduced by the rotate,
499af732203SDimitry Andric       // as U1'' and U1' scopes will not be compatible wrt to the local restrict
500af732203SDimitry Andric 
501af732203SDimitry Andric       // Clone the llvm.experimental.noalias.decl again for the NewHeader.
502af732203SDimitry Andric       Instruction *NewHeaderInsertionPoint = &(*NewHeader->getFirstNonPHI());
503af732203SDimitry Andric       for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
504af732203SDimitry Andric         LLVM_DEBUG(dbgs() << "  Cloning llvm.experimental.noalias.scope.decl:"
505af732203SDimitry Andric                           << *NAD << "\n");
506af732203SDimitry Andric         Instruction *NewNAD = NAD->clone();
507af732203SDimitry Andric         NewNAD->insertBefore(NewHeaderInsertionPoint);
508af732203SDimitry Andric       }
509af732203SDimitry Andric 
510af732203SDimitry Andric       // Scopes must now be duplicated, once for OrigHeader and once for
511af732203SDimitry Andric       // OrigPreHeader'.
512af732203SDimitry Andric       {
513af732203SDimitry Andric         auto &Context = NewHeader->getContext();
514af732203SDimitry Andric 
515af732203SDimitry Andric         SmallVector<MDNode *, 8> NoAliasDeclScopes;
516af732203SDimitry Andric         for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
517af732203SDimitry Andric           NoAliasDeclScopes.push_back(NAD->getScopeList());
518af732203SDimitry Andric 
519af732203SDimitry Andric         LLVM_DEBUG(dbgs() << "  Updating OrigHeader scopes\n");
520af732203SDimitry Andric         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
521af732203SDimitry Andric                                    "h.rot");
522af732203SDimitry Andric         LLVM_DEBUG(OrigHeader->dump());
523af732203SDimitry Andric 
524af732203SDimitry Andric         // Keep the compile time impact low by only adapting the inserted block
525af732203SDimitry Andric         // of instructions in the OrigPreHeader. This might result in slightly
526af732203SDimitry Andric         // more aliasing between these instructions and those that were already
527af732203SDimitry Andric         // present, but it will be much faster when the original PreHeader is
528af732203SDimitry Andric         // large.
529af732203SDimitry Andric         LLVM_DEBUG(dbgs() << "  Updating part of OrigPreheader scopes\n");
530af732203SDimitry Andric         auto *FirstDecl =
531af732203SDimitry Andric             cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
532af732203SDimitry Andric         auto *LastInst = &OrigPreheader->back();
533af732203SDimitry Andric         cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
534af732203SDimitry Andric                                    Context, "pre.rot");
535af732203SDimitry Andric         LLVM_DEBUG(OrigPreheader->dump());
536af732203SDimitry Andric 
537af732203SDimitry Andric         LLVM_DEBUG(dbgs() << "  Updated NewHeader:\n");
538af732203SDimitry Andric         LLVM_DEBUG(NewHeader->dump());
539af732203SDimitry Andric       }
540af732203SDimitry Andric     }
541af732203SDimitry Andric 
5420b57cec5SDimitry Andric     // Along with all the other instructions, we just cloned OrigHeader's
5430b57cec5SDimitry Andric     // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
5440b57cec5SDimitry Andric     // successors by duplicating their incoming values for OrigHeader.
5450b57cec5SDimitry Andric     for (BasicBlock *SuccBB : successors(OrigHeader))
5460b57cec5SDimitry Andric       for (BasicBlock::iterator BI = SuccBB->begin();
5470b57cec5SDimitry Andric            PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
5480b57cec5SDimitry Andric         PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric     // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
5510b57cec5SDimitry Andric     // OrigPreHeader's old terminator (the original branch into the loop), and
5520b57cec5SDimitry Andric     // remove the corresponding incoming values from the PHI nodes in OrigHeader.
5530b57cec5SDimitry Andric     LoopEntryBranch->eraseFromParent();
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric     // Update MemorySSA before the rewrite call below changes the 1:1
5560b57cec5SDimitry Andric     // instruction:cloned_instruction_or_value mapping.
5570b57cec5SDimitry Andric     if (MSSAU) {
558480093f4SDimitry Andric       InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
5590b57cec5SDimitry Andric       MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
5600b57cec5SDimitry Andric                                           ValueMapMSSA);
5610b57cec5SDimitry Andric     }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric     SmallVector<PHINode*, 2> InsertedPHIs;
5640b57cec5SDimitry Andric     // If there were any uses of instructions in the duplicated block outside the
5650b57cec5SDimitry Andric     // loop, update them, inserting PHI nodes as required
5660b57cec5SDimitry Andric     RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
5670b57cec5SDimitry Andric                                     &InsertedPHIs);
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric     // Attach dbg.value intrinsics to the new phis if that phi uses a value that
5700b57cec5SDimitry Andric     // previously had debug metadata attached. This keeps the debug info
5710b57cec5SDimitry Andric     // up-to-date in the loop body.
5720b57cec5SDimitry Andric     if (!InsertedPHIs.empty())
5730b57cec5SDimitry Andric       insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric     // NewHeader is now the header of the loop.
5760b57cec5SDimitry Andric     L->moveToHeader(NewHeader);
5770b57cec5SDimitry Andric     assert(L->getHeader() == NewHeader && "Latch block is our new header");
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric     // Inform DT about changes to the CFG.
5800b57cec5SDimitry Andric     if (DT) {
5810b57cec5SDimitry Andric       // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
5820b57cec5SDimitry Andric       // the DT about the removed edge to the OrigHeader (that got removed).
5830b57cec5SDimitry Andric       SmallVector<DominatorTree::UpdateType, 3> Updates;
5840b57cec5SDimitry Andric       Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
5850b57cec5SDimitry Andric       Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
5860b57cec5SDimitry Andric       Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric       if (MSSAU) {
589af732203SDimitry Andric         MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
5900b57cec5SDimitry Andric         if (VerifyMemorySSA)
5910b57cec5SDimitry Andric           MSSAU->getMemorySSA()->verifyMemorySSA();
592af732203SDimitry Andric       } else {
593af732203SDimitry Andric         DT->applyUpdates(Updates);
5940b57cec5SDimitry Andric       }
5950b57cec5SDimitry Andric     }
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric     // At this point, we've finished our major CFG changes.  As part of cloning
5980b57cec5SDimitry Andric     // the loop into the preheader we've simplified instructions and the
5990b57cec5SDimitry Andric     // duplicated conditional branch may now be branching on a constant.  If it is
6000b57cec5SDimitry Andric     // branching on a constant and if that constant means that we enter the loop,
6010b57cec5SDimitry Andric     // then we fold away the cond branch to an uncond branch.  This simplifies the
6020b57cec5SDimitry Andric     // loop in cases important for nested loops, and it also means we don't have
6030b57cec5SDimitry Andric     // to split as many edges.
6040b57cec5SDimitry Andric     BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
6050b57cec5SDimitry Andric     assert(PHBI->isConditional() && "Should be clone of BI condbr!");
6060b57cec5SDimitry Andric     if (!isa<ConstantInt>(PHBI->getCondition()) ||
6070b57cec5SDimitry Andric         PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
6080b57cec5SDimitry Andric         NewHeader) {
6090b57cec5SDimitry Andric       // The conditional branch can't be folded, handle the general case.
6100b57cec5SDimitry Andric       // Split edges as necessary to preserve LoopSimplify form.
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric       // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
6130b57cec5SDimitry Andric       // thus is not a preheader anymore.
6140b57cec5SDimitry Andric       // Split the edge to form a real preheader.
6150b57cec5SDimitry Andric       BasicBlock *NewPH = SplitCriticalEdge(
6160b57cec5SDimitry Andric                                             OrigPreheader, NewHeader,
6170b57cec5SDimitry Andric                                             CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
6180b57cec5SDimitry Andric       NewPH->setName(NewHeader->getName() + ".lr.ph");
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric       // Preserve canonical loop form, which means that 'Exit' should have only
6210b57cec5SDimitry Andric       // one predecessor. Note that Exit could be an exit block for multiple
6220b57cec5SDimitry Andric       // nested loops, causing both of the edges to now be critical and need to
6230b57cec5SDimitry Andric       // be split.
6240b57cec5SDimitry Andric       SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
6250b57cec5SDimitry Andric       bool SplitLatchEdge = false;
6260b57cec5SDimitry Andric       for (BasicBlock *ExitPred : ExitPreds) {
6270b57cec5SDimitry Andric         // We only need to split loop exit edges.
6280b57cec5SDimitry Andric         Loop *PredLoop = LI->getLoopFor(ExitPred);
6290b57cec5SDimitry Andric         if (!PredLoop || PredLoop->contains(Exit) ||
6300b57cec5SDimitry Andric             ExitPred->getTerminator()->isIndirectTerminator())
6310b57cec5SDimitry Andric           continue;
6320b57cec5SDimitry Andric         SplitLatchEdge |= L->getLoopLatch() == ExitPred;
6330b57cec5SDimitry Andric         BasicBlock *ExitSplit = SplitCriticalEdge(
6340b57cec5SDimitry Andric                                                   ExitPred, Exit,
6350b57cec5SDimitry Andric                                                   CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
6360b57cec5SDimitry Andric         ExitSplit->moveBefore(Exit);
6370b57cec5SDimitry Andric       }
6380b57cec5SDimitry Andric       assert(SplitLatchEdge &&
6390b57cec5SDimitry Andric              "Despite splitting all preds, failed to split latch exit?");
640*5f7ddb14SDimitry Andric       (void)SplitLatchEdge;
6410b57cec5SDimitry Andric     } else {
6420b57cec5SDimitry Andric       // We can fold the conditional branch in the preheader, this makes things
6430b57cec5SDimitry Andric       // simpler. The first step is to remove the extra edge to the Exit block.
6440b57cec5SDimitry Andric       Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
6450b57cec5SDimitry Andric       BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
6460b57cec5SDimitry Andric       NewBI->setDebugLoc(PHBI->getDebugLoc());
6470b57cec5SDimitry Andric       PHBI->eraseFromParent();
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric       // With our CFG finalized, update DomTree if it is available.
6500b57cec5SDimitry Andric       if (DT) DT->deleteEdge(OrigPreheader, Exit);
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric       // Update MSSA too, if available.
6530b57cec5SDimitry Andric       if (MSSAU)
6540b57cec5SDimitry Andric         MSSAU->removeEdge(OrigPreheader, Exit);
6550b57cec5SDimitry Andric     }
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric     assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
6580b57cec5SDimitry Andric     assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric     if (MSSAU && VerifyMemorySSA)
6610b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric     // Now that the CFG and DomTree are in a consistent state again, try to merge
6640b57cec5SDimitry Andric     // the OrigHeader block into OrigLatch.  This will succeed if they are
6650b57cec5SDimitry Andric     // connected by an unconditional branch.  This is just a cleanup so the
6660b57cec5SDimitry Andric     // emitted code isn't too gross in this common case.
6670b57cec5SDimitry Andric     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
668af732203SDimitry Andric     BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
669af732203SDimitry Andric     bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
670af732203SDimitry Andric     if (DidMerge)
671af732203SDimitry Andric       RemoveRedundantDbgInstrs(PredBB);
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric     if (MSSAU && VerifyMemorySSA)
6740b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric     ++NumRotated;
6795ffd83dbSDimitry Andric 
6805ffd83dbSDimitry Andric     Rotated = true;
6815ffd83dbSDimitry Andric     SimplifiedLatch = false;
6825ffd83dbSDimitry Andric 
6835ffd83dbSDimitry Andric     // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
6845ffd83dbSDimitry Andric     // Deoptimizing latch exit is not a generally typical case, so we just loop over.
6855ffd83dbSDimitry Andric     // TODO: if it becomes a performance bottleneck extend rotation algorithm
6865ffd83dbSDimitry Andric     // to handle multiple rotations in one go.
6875ffd83dbSDimitry Andric   } while (MultiRotate && canRotateDeoptimizingLatchExit(L));
6885ffd83dbSDimitry Andric 
6895ffd83dbSDimitry Andric 
6900b57cec5SDimitry Andric   return true;
6910b57cec5SDimitry Andric }
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric /// Determine whether the instructions in this range may be safely and cheaply
6940b57cec5SDimitry Andric /// speculated. This is not an important enough situation to develop complex
6950b57cec5SDimitry Andric /// heuristics. We handle a single arithmetic instruction along with any type
6960b57cec5SDimitry Andric /// conversions.
shouldSpeculateInstrs(BasicBlock::iterator Begin,BasicBlock::iterator End,Loop * L)6970b57cec5SDimitry Andric static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
6980b57cec5SDimitry Andric                                   BasicBlock::iterator End, Loop *L) {
6990b57cec5SDimitry Andric   bool seenIncrement = false;
7000b57cec5SDimitry Andric   bool MultiExitLoop = false;
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric   if (!L->getExitingBlock())
7030b57cec5SDimitry Andric     MultiExitLoop = true;
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   for (BasicBlock::iterator I = Begin; I != End; ++I) {
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric     if (!isSafeToSpeculativelyExecute(&*I))
7080b57cec5SDimitry Andric       return false;
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric     if (isa<DbgInfoIntrinsic>(I))
7110b57cec5SDimitry Andric       continue;
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric     switch (I->getOpcode()) {
7140b57cec5SDimitry Andric     default:
7150b57cec5SDimitry Andric       return false;
7160b57cec5SDimitry Andric     case Instruction::GetElementPtr:
7170b57cec5SDimitry Andric       // GEPs are cheap if all indices are constant.
7180b57cec5SDimitry Andric       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
7190b57cec5SDimitry Andric         return false;
7200b57cec5SDimitry Andric       // fall-thru to increment case
7210b57cec5SDimitry Andric       LLVM_FALLTHROUGH;
7220b57cec5SDimitry Andric     case Instruction::Add:
7230b57cec5SDimitry Andric     case Instruction::Sub:
7240b57cec5SDimitry Andric     case Instruction::And:
7250b57cec5SDimitry Andric     case Instruction::Or:
7260b57cec5SDimitry Andric     case Instruction::Xor:
7270b57cec5SDimitry Andric     case Instruction::Shl:
7280b57cec5SDimitry Andric     case Instruction::LShr:
7290b57cec5SDimitry Andric     case Instruction::AShr: {
7300b57cec5SDimitry Andric       Value *IVOpnd =
7310b57cec5SDimitry Andric           !isa<Constant>(I->getOperand(0))
7320b57cec5SDimitry Andric               ? I->getOperand(0)
7330b57cec5SDimitry Andric               : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
7340b57cec5SDimitry Andric       if (!IVOpnd)
7350b57cec5SDimitry Andric         return false;
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric       // If increment operand is used outside of the loop, this speculation
7380b57cec5SDimitry Andric       // could cause extra live range interference.
7390b57cec5SDimitry Andric       if (MultiExitLoop) {
7400b57cec5SDimitry Andric         for (User *UseI : IVOpnd->users()) {
7410b57cec5SDimitry Andric           auto *UserInst = cast<Instruction>(UseI);
7420b57cec5SDimitry Andric           if (!L->contains(UserInst))
7430b57cec5SDimitry Andric             return false;
7440b57cec5SDimitry Andric         }
7450b57cec5SDimitry Andric       }
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric       if (seenIncrement)
7480b57cec5SDimitry Andric         return false;
7490b57cec5SDimitry Andric       seenIncrement = true;
7500b57cec5SDimitry Andric       break;
7510b57cec5SDimitry Andric     }
7520b57cec5SDimitry Andric     case Instruction::Trunc:
7530b57cec5SDimitry Andric     case Instruction::ZExt:
7540b57cec5SDimitry Andric     case Instruction::SExt:
7550b57cec5SDimitry Andric       // ignore type conversions
7560b57cec5SDimitry Andric       break;
7570b57cec5SDimitry Andric     }
7580b57cec5SDimitry Andric   }
7590b57cec5SDimitry Andric   return true;
7600b57cec5SDimitry Andric }
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric /// Fold the loop tail into the loop exit by speculating the loop tail
7630b57cec5SDimitry Andric /// instructions. Typically, this is a single post-increment. In the case of a
7640b57cec5SDimitry Andric /// simple 2-block loop, hoisting the increment can be much better than
7650b57cec5SDimitry Andric /// duplicating the entire loop header. In the case of loops with early exits,
7660b57cec5SDimitry Andric /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
7670b57cec5SDimitry Andric /// canonical form so downstream passes can handle it.
7680b57cec5SDimitry Andric ///
7690b57cec5SDimitry Andric /// I don't believe this invalidates SCEV.
simplifyLoopLatch(Loop * L)7700b57cec5SDimitry Andric bool LoopRotate::simplifyLoopLatch(Loop *L) {
7710b57cec5SDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
7720b57cec5SDimitry Andric   if (!Latch || Latch->hasAddressTaken())
7730b57cec5SDimitry Andric     return false;
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
7760b57cec5SDimitry Andric   if (!Jmp || !Jmp->isUnconditional())
7770b57cec5SDimitry Andric     return false;
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   BasicBlock *LastExit = Latch->getSinglePredecessor();
7800b57cec5SDimitry Andric   if (!LastExit || !L->isLoopExiting(LastExit))
7810b57cec5SDimitry Andric     return false;
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
7840b57cec5SDimitry Andric   if (!BI)
7850b57cec5SDimitry Andric     return false;
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
7880b57cec5SDimitry Andric     return false;
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
7910b57cec5SDimitry Andric                     << LastExit->getName() << "\n");
7920b57cec5SDimitry Andric 
7938bcb0991SDimitry Andric   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
7948bcb0991SDimitry Andric   MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
7958bcb0991SDimitry Andric                             /*PredecessorWithTwoSuccessors=*/true);
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   if (MSSAU && VerifyMemorySSA)
7980b57cec5SDimitry Andric     MSSAU->getMemorySSA()->verifyMemorySSA();
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   return true;
8010b57cec5SDimitry Andric }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric /// Rotate \c L, and return true if any modification was made.
processLoop(Loop * L)8040b57cec5SDimitry Andric bool LoopRotate::processLoop(Loop *L) {
8050b57cec5SDimitry Andric   // Save the loop metadata.
8060b57cec5SDimitry Andric   MDNode *LoopMD = L->getLoopID();
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric   bool SimplifiedLatch = false;
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   // Simplify the loop latch before attempting to rotate the header
8110b57cec5SDimitry Andric   // upward. Rotation may not be needed if the loop tail can be folded into the
8120b57cec5SDimitry Andric   // loop exit.
8130b57cec5SDimitry Andric   if (!RotationOnly)
8140b57cec5SDimitry Andric     SimplifiedLatch = simplifyLoopLatch(L);
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   bool MadeChange = rotateLoop(L, SimplifiedLatch);
8170b57cec5SDimitry Andric   assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
8180b57cec5SDimitry Andric          "Loop latch should be exiting after loop-rotate.");
8190b57cec5SDimitry Andric 
8200b57cec5SDimitry Andric   // Restore the loop metadata.
8210b57cec5SDimitry Andric   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
8220b57cec5SDimitry Andric   if ((MadeChange || SimplifiedLatch) && LoopMD)
8230b57cec5SDimitry Andric     L->setLoopID(LoopMD);
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   return MadeChange || SimplifiedLatch;
8260b57cec5SDimitry Andric }
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry 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)8300b57cec5SDimitry Andric bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
8310b57cec5SDimitry Andric                         AssumptionCache *AC, DominatorTree *DT,
8320b57cec5SDimitry Andric                         ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
8330b57cec5SDimitry Andric                         const SimplifyQuery &SQ, bool RotationOnly = true,
8340b57cec5SDimitry Andric                         unsigned Threshold = unsigned(-1),
835af732203SDimitry Andric                         bool IsUtilMode = true, bool PrepareForLTO) {
8360b57cec5SDimitry Andric   LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
837af732203SDimitry Andric                 IsUtilMode, PrepareForLTO);
8380b57cec5SDimitry Andric   return LR.processLoop(L);
8390b57cec5SDimitry Andric }
840