xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/Transforms/Scalar/LoopSink.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
17330f729Sjoerg //===-- LoopSink.cpp - Loop Sink Pass -------------------------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This pass does the inverse transformation of what LICM does.
107330f729Sjoerg // It traverses all of the instructions in the loop's preheader and sinks
117330f729Sjoerg // them to the loop body where frequency is lower than the loop's preheader.
127330f729Sjoerg // This pass is a reverse-transformation of LICM. It differs from the Sink
137330f729Sjoerg // pass in the following ways:
147330f729Sjoerg //
157330f729Sjoerg // * It only handles sinking of instructions from the loop's preheader to the
167330f729Sjoerg //   loop's body
177330f729Sjoerg // * It uses alias set tracker to get more accurate alias info
187330f729Sjoerg // * It uses block frequency info to find the optimal sinking locations
197330f729Sjoerg //
207330f729Sjoerg // Overall algorithm:
217330f729Sjoerg //
227330f729Sjoerg // For I in Preheader:
237330f729Sjoerg //   InsertBBs = BBs that uses I
247330f729Sjoerg //   For BB in sorted(LoopBBs):
257330f729Sjoerg //     DomBBs = BBs in InsertBBs that are dominated by BB
267330f729Sjoerg //     if freq(DomBBs) > freq(BB)
277330f729Sjoerg //       InsertBBs = UseBBs - DomBBs + BB
287330f729Sjoerg //   For BB in InsertBBs:
297330f729Sjoerg //     Insert I at BB's beginning
307330f729Sjoerg //
317330f729Sjoerg //===----------------------------------------------------------------------===//
327330f729Sjoerg 
337330f729Sjoerg #include "llvm/Transforms/Scalar/LoopSink.h"
34*82d56013Sjoerg #include "llvm/ADT/SetOperations.h"
357330f729Sjoerg #include "llvm/ADT/Statistic.h"
367330f729Sjoerg #include "llvm/Analysis/AliasAnalysis.h"
377330f729Sjoerg #include "llvm/Analysis/AliasSetTracker.h"
387330f729Sjoerg #include "llvm/Analysis/BasicAliasAnalysis.h"
397330f729Sjoerg #include "llvm/Analysis/BlockFrequencyInfo.h"
407330f729Sjoerg #include "llvm/Analysis/Loads.h"
417330f729Sjoerg #include "llvm/Analysis/LoopInfo.h"
427330f729Sjoerg #include "llvm/Analysis/LoopPass.h"
43*82d56013Sjoerg #include "llvm/Analysis/MemorySSA.h"
44*82d56013Sjoerg #include "llvm/Analysis/MemorySSAUpdater.h"
457330f729Sjoerg #include "llvm/Analysis/ScalarEvolution.h"
467330f729Sjoerg #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
477330f729Sjoerg #include "llvm/IR/Dominators.h"
487330f729Sjoerg #include "llvm/IR/Instructions.h"
497330f729Sjoerg #include "llvm/IR/LLVMContext.h"
507330f729Sjoerg #include "llvm/IR/Metadata.h"
51*82d56013Sjoerg #include "llvm/InitializePasses.h"
527330f729Sjoerg #include "llvm/Support/CommandLine.h"
537330f729Sjoerg #include "llvm/Transforms/Scalar.h"
547330f729Sjoerg #include "llvm/Transforms/Scalar/LoopPassManager.h"
55*82d56013Sjoerg #include "llvm/Transforms/Utils/Local.h"
567330f729Sjoerg #include "llvm/Transforms/Utils/LoopUtils.h"
577330f729Sjoerg using namespace llvm;
587330f729Sjoerg 
597330f729Sjoerg #define DEBUG_TYPE "loopsink"
607330f729Sjoerg 
617330f729Sjoerg STATISTIC(NumLoopSunk, "Number of instructions sunk into loop");
627330f729Sjoerg STATISTIC(NumLoopSunkCloned, "Number of cloned instructions sunk into loop");
637330f729Sjoerg 
647330f729Sjoerg static cl::opt<unsigned> SinkFrequencyPercentThreshold(
657330f729Sjoerg     "sink-freq-percent-threshold", cl::Hidden, cl::init(90),
667330f729Sjoerg     cl::desc("Do not sink instructions that require cloning unless they "
677330f729Sjoerg              "execute less than this percent of the time."));
687330f729Sjoerg 
697330f729Sjoerg static cl::opt<unsigned> MaxNumberOfUseBBsForSinking(
707330f729Sjoerg     "max-uses-for-sinking", cl::Hidden, cl::init(30),
717330f729Sjoerg     cl::desc("Do not sink instructions that have too many uses."));
727330f729Sjoerg 
73*82d56013Sjoerg static cl::opt<bool> EnableMSSAInLoopSink(
74*82d56013Sjoerg     "enable-mssa-in-loop-sink", cl::Hidden, cl::init(true),
75*82d56013Sjoerg     cl::desc("Enable MemorySSA for LoopSink in new pass manager"));
76*82d56013Sjoerg 
77*82d56013Sjoerg static cl::opt<bool> EnableMSSAInLegacyLoopSink(
78*82d56013Sjoerg     "enable-mssa-in-legacy-loop-sink", cl::Hidden, cl::init(false),
79*82d56013Sjoerg     cl::desc("Enable MemorySSA for LoopSink in legacy pass manager"));
80*82d56013Sjoerg 
817330f729Sjoerg /// Return adjusted total frequency of \p BBs.
827330f729Sjoerg ///
837330f729Sjoerg /// * If there is only one BB, sinking instruction will not introduce code
847330f729Sjoerg ///   size increase. Thus there is no need to adjust the frequency.
857330f729Sjoerg /// * If there are more than one BB, sinking would lead to code size increase.
867330f729Sjoerg ///   In this case, we add some "tax" to the total frequency to make it harder
877330f729Sjoerg ///   to sink. E.g.
887330f729Sjoerg ///     Freq(Preheader) = 100
897330f729Sjoerg ///     Freq(BBs) = sum(50, 49) = 99
907330f729Sjoerg ///   Even if Freq(BBs) < Freq(Preheader), we will not sink from Preheade to
917330f729Sjoerg ///   BBs as the difference is too small to justify the code size increase.
927330f729Sjoerg ///   To model this, The adjusted Freq(BBs) will be:
937330f729Sjoerg ///     AdjustedFreq(BBs) = 99 / SinkFrequencyPercentThreshold%
adjustedSumFreq(SmallPtrSetImpl<BasicBlock * > & BBs,BlockFrequencyInfo & BFI)947330f729Sjoerg static BlockFrequency adjustedSumFreq(SmallPtrSetImpl<BasicBlock *> &BBs,
957330f729Sjoerg                                       BlockFrequencyInfo &BFI) {
967330f729Sjoerg   BlockFrequency T = 0;
977330f729Sjoerg   for (BasicBlock *B : BBs)
987330f729Sjoerg     T += BFI.getBlockFreq(B);
997330f729Sjoerg   if (BBs.size() > 1)
1007330f729Sjoerg     T /= BranchProbability(SinkFrequencyPercentThreshold, 100);
1017330f729Sjoerg   return T;
1027330f729Sjoerg }
1037330f729Sjoerg 
1047330f729Sjoerg /// Return a set of basic blocks to insert sinked instructions.
1057330f729Sjoerg ///
1067330f729Sjoerg /// The returned set of basic blocks (BBsToSinkInto) should satisfy:
1077330f729Sjoerg ///
1087330f729Sjoerg /// * Inside the loop \p L
1097330f729Sjoerg /// * For each UseBB in \p UseBBs, there is at least one BB in BBsToSinkInto
1107330f729Sjoerg ///   that domintates the UseBB
1117330f729Sjoerg /// * Has minimum total frequency that is no greater than preheader frequency
1127330f729Sjoerg ///
1137330f729Sjoerg /// The purpose of the function is to find the optimal sinking points to
1147330f729Sjoerg /// minimize execution cost, which is defined as "sum of frequency of
1157330f729Sjoerg /// BBsToSinkInto".
1167330f729Sjoerg /// As a result, the returned BBsToSinkInto needs to have minimum total
1177330f729Sjoerg /// frequency.
1187330f729Sjoerg /// Additionally, if the total frequency of BBsToSinkInto exceeds preheader
1197330f729Sjoerg /// frequency, the optimal solution is not sinking (return empty set).
1207330f729Sjoerg ///
1217330f729Sjoerg /// \p ColdLoopBBs is used to help find the optimal sinking locations.
1227330f729Sjoerg /// It stores a list of BBs that is:
1237330f729Sjoerg ///
1247330f729Sjoerg /// * Inside the loop \p L
1257330f729Sjoerg /// * Has a frequency no larger than the loop's preheader
1267330f729Sjoerg /// * Sorted by BB frequency
1277330f729Sjoerg ///
1287330f729Sjoerg /// The complexity of the function is O(UseBBs.size() * ColdLoopBBs.size()).
1297330f729Sjoerg /// To avoid expensive computation, we cap the maximum UseBBs.size() in its
1307330f729Sjoerg /// caller.
1317330f729Sjoerg static SmallPtrSet<BasicBlock *, 2>
findBBsToSinkInto(const Loop & L,const SmallPtrSetImpl<BasicBlock * > & UseBBs,const SmallVectorImpl<BasicBlock * > & ColdLoopBBs,DominatorTree & DT,BlockFrequencyInfo & BFI)1327330f729Sjoerg findBBsToSinkInto(const Loop &L, const SmallPtrSetImpl<BasicBlock *> &UseBBs,
1337330f729Sjoerg                   const SmallVectorImpl<BasicBlock *> &ColdLoopBBs,
1347330f729Sjoerg                   DominatorTree &DT, BlockFrequencyInfo &BFI) {
1357330f729Sjoerg   SmallPtrSet<BasicBlock *, 2> BBsToSinkInto;
1367330f729Sjoerg   if (UseBBs.size() == 0)
1377330f729Sjoerg     return BBsToSinkInto;
1387330f729Sjoerg 
1397330f729Sjoerg   BBsToSinkInto.insert(UseBBs.begin(), UseBBs.end());
1407330f729Sjoerg   SmallPtrSet<BasicBlock *, 2> BBsDominatedByColdestBB;
1417330f729Sjoerg 
1427330f729Sjoerg   // For every iteration:
1437330f729Sjoerg   //   * Pick the ColdestBB from ColdLoopBBs
1447330f729Sjoerg   //   * Find the set BBsDominatedByColdestBB that satisfy:
1457330f729Sjoerg   //     - BBsDominatedByColdestBB is a subset of BBsToSinkInto
1467330f729Sjoerg   //     - Every BB in BBsDominatedByColdestBB is dominated by ColdestBB
1477330f729Sjoerg   //   * If Freq(ColdestBB) < Freq(BBsDominatedByColdestBB), remove
1487330f729Sjoerg   //     BBsDominatedByColdestBB from BBsToSinkInto, add ColdestBB to
1497330f729Sjoerg   //     BBsToSinkInto
1507330f729Sjoerg   for (BasicBlock *ColdestBB : ColdLoopBBs) {
1517330f729Sjoerg     BBsDominatedByColdestBB.clear();
1527330f729Sjoerg     for (BasicBlock *SinkedBB : BBsToSinkInto)
1537330f729Sjoerg       if (DT.dominates(ColdestBB, SinkedBB))
1547330f729Sjoerg         BBsDominatedByColdestBB.insert(SinkedBB);
1557330f729Sjoerg     if (BBsDominatedByColdestBB.size() == 0)
1567330f729Sjoerg       continue;
1577330f729Sjoerg     if (adjustedSumFreq(BBsDominatedByColdestBB, BFI) >
1587330f729Sjoerg         BFI.getBlockFreq(ColdestBB)) {
1597330f729Sjoerg       for (BasicBlock *DominatedBB : BBsDominatedByColdestBB) {
1607330f729Sjoerg         BBsToSinkInto.erase(DominatedBB);
1617330f729Sjoerg       }
1627330f729Sjoerg       BBsToSinkInto.insert(ColdestBB);
1637330f729Sjoerg     }
1647330f729Sjoerg   }
1657330f729Sjoerg 
1667330f729Sjoerg   // Can't sink into blocks that have no valid insertion point.
1677330f729Sjoerg   for (BasicBlock *BB : BBsToSinkInto) {
1687330f729Sjoerg     if (BB->getFirstInsertionPt() == BB->end()) {
1697330f729Sjoerg       BBsToSinkInto.clear();
1707330f729Sjoerg       break;
1717330f729Sjoerg     }
1727330f729Sjoerg   }
1737330f729Sjoerg 
1747330f729Sjoerg   // If the total frequency of BBsToSinkInto is larger than preheader frequency,
1757330f729Sjoerg   // do not sink.
1767330f729Sjoerg   if (adjustedSumFreq(BBsToSinkInto, BFI) >
1777330f729Sjoerg       BFI.getBlockFreq(L.getLoopPreheader()))
1787330f729Sjoerg     BBsToSinkInto.clear();
1797330f729Sjoerg   return BBsToSinkInto;
1807330f729Sjoerg }
1817330f729Sjoerg 
1827330f729Sjoerg // Sinks \p I from the loop \p L's preheader to its uses. Returns true if
1837330f729Sjoerg // sinking is successful.
1847330f729Sjoerg // \p LoopBlockNumber is used to sort the insertion blocks to ensure
1857330f729Sjoerg // determinism.
sinkInstruction(Loop & L,Instruction & I,const SmallVectorImpl<BasicBlock * > & ColdLoopBBs,const SmallDenseMap<BasicBlock *,int,16> & LoopBlockNumber,LoopInfo & LI,DominatorTree & DT,BlockFrequencyInfo & BFI,MemorySSAUpdater * MSSAU)186*82d56013Sjoerg static bool sinkInstruction(
187*82d56013Sjoerg     Loop &L, Instruction &I, const SmallVectorImpl<BasicBlock *> &ColdLoopBBs,
188*82d56013Sjoerg     const SmallDenseMap<BasicBlock *, int, 16> &LoopBlockNumber, LoopInfo &LI,
189*82d56013Sjoerg     DominatorTree &DT, BlockFrequencyInfo &BFI, MemorySSAUpdater *MSSAU) {
1907330f729Sjoerg   // Compute the set of blocks in loop L which contain a use of I.
1917330f729Sjoerg   SmallPtrSet<BasicBlock *, 2> BBs;
1927330f729Sjoerg   for (auto &U : I.uses()) {
1937330f729Sjoerg     Instruction *UI = cast<Instruction>(U.getUser());
1947330f729Sjoerg     // We cannot sink I to PHI-uses.
195*82d56013Sjoerg     if (isa<PHINode>(UI))
1967330f729Sjoerg       return false;
1977330f729Sjoerg     // We cannot sink I if it has uses outside of the loop.
1987330f729Sjoerg     if (!L.contains(LI.getLoopFor(UI->getParent())))
1997330f729Sjoerg       return false;
2007330f729Sjoerg     BBs.insert(UI->getParent());
2017330f729Sjoerg   }
2027330f729Sjoerg 
2037330f729Sjoerg   // findBBsToSinkInto is O(BBs.size() * ColdLoopBBs.size()). We cap the max
2047330f729Sjoerg   // BBs.size() to avoid expensive computation.
2057330f729Sjoerg   // FIXME: Handle code size growth for min_size and opt_size.
2067330f729Sjoerg   if (BBs.size() > MaxNumberOfUseBBsForSinking)
2077330f729Sjoerg     return false;
2087330f729Sjoerg 
2097330f729Sjoerg   // Find the set of BBs that we should insert a copy of I.
2107330f729Sjoerg   SmallPtrSet<BasicBlock *, 2> BBsToSinkInto =
2117330f729Sjoerg       findBBsToSinkInto(L, BBs, ColdLoopBBs, DT, BFI);
2127330f729Sjoerg   if (BBsToSinkInto.empty())
2137330f729Sjoerg     return false;
2147330f729Sjoerg 
2157330f729Sjoerg   // Return if any of the candidate blocks to sink into is non-cold.
216*82d56013Sjoerg   if (BBsToSinkInto.size() > 1 &&
217*82d56013Sjoerg       !llvm::set_is_subset(BBsToSinkInto, LoopBlockNumber))
2187330f729Sjoerg     return false;
2197330f729Sjoerg 
2207330f729Sjoerg   // Copy the final BBs into a vector and sort them using the total ordering
2217330f729Sjoerg   // of the loop block numbers as iterating the set doesn't give a useful
2227330f729Sjoerg   // order. No need to stable sort as the block numbers are a total ordering.
2237330f729Sjoerg   SmallVector<BasicBlock *, 2> SortedBBsToSinkInto;
224*82d56013Sjoerg   llvm::append_range(SortedBBsToSinkInto, BBsToSinkInto);
2257330f729Sjoerg   llvm::sort(SortedBBsToSinkInto, [&](BasicBlock *A, BasicBlock *B) {
2267330f729Sjoerg     return LoopBlockNumber.find(A)->second < LoopBlockNumber.find(B)->second;
2277330f729Sjoerg   });
2287330f729Sjoerg 
2297330f729Sjoerg   BasicBlock *MoveBB = *SortedBBsToSinkInto.begin();
2307330f729Sjoerg   // FIXME: Optimize the efficiency for cloned value replacement. The current
2317330f729Sjoerg   //        implementation is O(SortedBBsToSinkInto.size() * I.num_uses()).
2327330f729Sjoerg   for (BasicBlock *N : makeArrayRef(SortedBBsToSinkInto).drop_front(1)) {
2337330f729Sjoerg     assert(LoopBlockNumber.find(N)->second >
2347330f729Sjoerg                LoopBlockNumber.find(MoveBB)->second &&
2357330f729Sjoerg            "BBs not sorted!");
2367330f729Sjoerg     // Clone I and replace its uses.
2377330f729Sjoerg     Instruction *IC = I.clone();
2387330f729Sjoerg     IC->setName(I.getName());
2397330f729Sjoerg     IC->insertBefore(&*N->getFirstInsertionPt());
240*82d56013Sjoerg 
241*82d56013Sjoerg     if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
242*82d56013Sjoerg       // Create a new MemoryAccess and let MemorySSA set its defining access.
243*82d56013Sjoerg       MemoryAccess *NewMemAcc =
244*82d56013Sjoerg           MSSAU->createMemoryAccessInBB(IC, nullptr, N, MemorySSA::Beginning);
245*82d56013Sjoerg       if (NewMemAcc) {
246*82d56013Sjoerg         if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
247*82d56013Sjoerg           MSSAU->insertDef(MemDef, /*RenameUses=*/true);
248*82d56013Sjoerg         else {
249*82d56013Sjoerg           auto *MemUse = cast<MemoryUse>(NewMemAcc);
250*82d56013Sjoerg           MSSAU->insertUse(MemUse, /*RenameUses=*/true);
251*82d56013Sjoerg         }
252*82d56013Sjoerg       }
253*82d56013Sjoerg     }
254*82d56013Sjoerg 
2557330f729Sjoerg     // Replaces uses of I with IC in N
2567330f729Sjoerg     I.replaceUsesWithIf(IC, [N](Use &U) {
2577330f729Sjoerg       return cast<Instruction>(U.getUser())->getParent() == N;
2587330f729Sjoerg     });
2597330f729Sjoerg     // Replaces uses of I with IC in blocks dominated by N
2607330f729Sjoerg     replaceDominatedUsesWith(&I, IC, DT, N);
2617330f729Sjoerg     LLVM_DEBUG(dbgs() << "Sinking a clone of " << I << " To: " << N->getName()
2627330f729Sjoerg                       << '\n');
2637330f729Sjoerg     NumLoopSunkCloned++;
2647330f729Sjoerg   }
2657330f729Sjoerg   LLVM_DEBUG(dbgs() << "Sinking " << I << " To: " << MoveBB->getName() << '\n');
2667330f729Sjoerg   NumLoopSunk++;
2677330f729Sjoerg   I.moveBefore(&*MoveBB->getFirstInsertionPt());
2687330f729Sjoerg 
269*82d56013Sjoerg   if (MSSAU)
270*82d56013Sjoerg     if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>(
271*82d56013Sjoerg             MSSAU->getMemorySSA()->getMemoryAccess(&I)))
272*82d56013Sjoerg       MSSAU->moveToPlace(OldMemAcc, MoveBB, MemorySSA::Beginning);
273*82d56013Sjoerg 
2747330f729Sjoerg   return true;
2757330f729Sjoerg }
2767330f729Sjoerg 
2777330f729Sjoerg /// Sinks instructions from loop's preheader to the loop body if the
2787330f729Sjoerg /// sum frequency of inserted copy is smaller than preheader's frequency.
sinkLoopInvariantInstructions(Loop & L,AAResults & AA,LoopInfo & LI,DominatorTree & DT,BlockFrequencyInfo & BFI,ScalarEvolution * SE,AliasSetTracker * CurAST,MemorySSA * MSSA)2797330f729Sjoerg static bool sinkLoopInvariantInstructions(Loop &L, AAResults &AA, LoopInfo &LI,
2807330f729Sjoerg                                           DominatorTree &DT,
2817330f729Sjoerg                                           BlockFrequencyInfo &BFI,
282*82d56013Sjoerg                                           ScalarEvolution *SE,
283*82d56013Sjoerg                                           AliasSetTracker *CurAST,
284*82d56013Sjoerg                                           MemorySSA *MSSA) {
2857330f729Sjoerg   BasicBlock *Preheader = L.getLoopPreheader();
286*82d56013Sjoerg   assert(Preheader && "Expected loop to have preheader");
2877330f729Sjoerg 
288*82d56013Sjoerg   assert(Preheader->getParent()->hasProfileData() &&
289*82d56013Sjoerg          "Unexpected call when profile data unavailable.");
2907330f729Sjoerg 
2917330f729Sjoerg   const BlockFrequency PreheaderFreq = BFI.getBlockFreq(Preheader);
2927330f729Sjoerg   // If there are no basic blocks with lower frequency than the preheader then
2937330f729Sjoerg   // we can avoid the detailed analysis as we will never find profitable sinking
2947330f729Sjoerg   // opportunities.
2957330f729Sjoerg   if (all_of(L.blocks(), [&](const BasicBlock *BB) {
2967330f729Sjoerg         return BFI.getBlockFreq(BB) > PreheaderFreq;
2977330f729Sjoerg       }))
2987330f729Sjoerg     return false;
2997330f729Sjoerg 
300*82d56013Sjoerg   std::unique_ptr<MemorySSAUpdater> MSSAU;
301*82d56013Sjoerg   std::unique_ptr<SinkAndHoistLICMFlags> LICMFlags;
302*82d56013Sjoerg   if (MSSA) {
303*82d56013Sjoerg     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
304*82d56013Sjoerg     LICMFlags =
305*82d56013Sjoerg         std::make_unique<SinkAndHoistLICMFlags>(/*IsSink=*/true, &L, MSSA);
306*82d56013Sjoerg   }
3077330f729Sjoerg 
308*82d56013Sjoerg   bool Changed = false;
3097330f729Sjoerg 
3107330f729Sjoerg   // Sort loop's basic blocks by frequency
3117330f729Sjoerg   SmallVector<BasicBlock *, 10> ColdLoopBBs;
3127330f729Sjoerg   SmallDenseMap<BasicBlock *, int, 16> LoopBlockNumber;
3137330f729Sjoerg   int i = 0;
3147330f729Sjoerg   for (BasicBlock *B : L.blocks())
3157330f729Sjoerg     if (BFI.getBlockFreq(B) < BFI.getBlockFreq(L.getLoopPreheader())) {
3167330f729Sjoerg       ColdLoopBBs.push_back(B);
3177330f729Sjoerg       LoopBlockNumber[B] = ++i;
3187330f729Sjoerg     }
3197330f729Sjoerg   llvm::stable_sort(ColdLoopBBs, [&](BasicBlock *A, BasicBlock *B) {
3207330f729Sjoerg     return BFI.getBlockFreq(A) < BFI.getBlockFreq(B);
3217330f729Sjoerg   });
3227330f729Sjoerg 
3237330f729Sjoerg   // Traverse preheader's instructions in reverse order becaue if A depends
3247330f729Sjoerg   // on B (A appears after B), A needs to be sinked first before B can be
3257330f729Sjoerg   // sinked.
3267330f729Sjoerg   for (auto II = Preheader->rbegin(), E = Preheader->rend(); II != E;) {
3277330f729Sjoerg     Instruction *I = &*II++;
3287330f729Sjoerg     // No need to check for instruction's operands are loop invariant.
3297330f729Sjoerg     assert(L.hasLoopInvariantOperands(I) &&
3307330f729Sjoerg            "Insts in a loop's preheader should have loop invariant operands!");
331*82d56013Sjoerg     if (!canSinkOrHoistInst(*I, &AA, &DT, &L, CurAST, MSSAU.get(), false,
332*82d56013Sjoerg                             LICMFlags.get()))
3337330f729Sjoerg       continue;
334*82d56013Sjoerg     if (sinkInstruction(L, *I, ColdLoopBBs, LoopBlockNumber, LI, DT, BFI,
335*82d56013Sjoerg                         MSSAU.get()))
3367330f729Sjoerg       Changed = true;
3377330f729Sjoerg   }
3387330f729Sjoerg 
3397330f729Sjoerg   if (Changed && SE)
3407330f729Sjoerg     SE->forgetLoopDispositions(&L);
3417330f729Sjoerg   return Changed;
3427330f729Sjoerg }
3437330f729Sjoerg 
computeAliasSet(Loop & L,BasicBlock & Preheader,AliasSetTracker & CurAST)344*82d56013Sjoerg static void computeAliasSet(Loop &L, BasicBlock &Preheader,
345*82d56013Sjoerg                             AliasSetTracker &CurAST) {
346*82d56013Sjoerg   for (BasicBlock *BB : L.blocks())
347*82d56013Sjoerg     CurAST.add(*BB);
348*82d56013Sjoerg   CurAST.add(Preheader);
349*82d56013Sjoerg }
350*82d56013Sjoerg 
run(Function & F,FunctionAnalysisManager & FAM)3517330f729Sjoerg PreservedAnalyses LoopSinkPass::run(Function &F, FunctionAnalysisManager &FAM) {
3527330f729Sjoerg   LoopInfo &LI = FAM.getResult<LoopAnalysis>(F);
3537330f729Sjoerg   // Nothing to do if there are no loops.
3547330f729Sjoerg   if (LI.empty())
3557330f729Sjoerg     return PreservedAnalyses::all();
3567330f729Sjoerg 
3577330f729Sjoerg   AAResults &AA = FAM.getResult<AAManager>(F);
3587330f729Sjoerg   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
3597330f729Sjoerg   BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
3607330f729Sjoerg 
361*82d56013Sjoerg   MemorySSA *MSSA = EnableMSSAInLoopSink
362*82d56013Sjoerg                         ? &FAM.getResult<MemorySSAAnalysis>(F).getMSSA()
363*82d56013Sjoerg                         : nullptr;
364*82d56013Sjoerg 
3657330f729Sjoerg   // We want to do a postorder walk over the loops. Since loops are a tree this
3667330f729Sjoerg   // is equivalent to a reversed preorder walk and preorder is easy to compute
3677330f729Sjoerg   // without recursion. Since we reverse the preorder, we will visit siblings
3687330f729Sjoerg   // in reverse program order. This isn't expected to matter at all but is more
3697330f729Sjoerg   // consistent with sinking algorithms which generally work bottom-up.
3707330f729Sjoerg   SmallVector<Loop *, 4> PreorderLoops = LI.getLoopsInPreorder();
3717330f729Sjoerg 
3727330f729Sjoerg   bool Changed = false;
3737330f729Sjoerg   do {
3747330f729Sjoerg     Loop &L = *PreorderLoops.pop_back_val();
3757330f729Sjoerg 
376*82d56013Sjoerg     BasicBlock *Preheader = L.getLoopPreheader();
377*82d56013Sjoerg     if (!Preheader)
378*82d56013Sjoerg       continue;
379*82d56013Sjoerg 
380*82d56013Sjoerg     // Enable LoopSink only when runtime profile is available.
381*82d56013Sjoerg     // With static profile, the sinking decision may be sub-optimal.
382*82d56013Sjoerg     if (!Preheader->getParent()->hasProfileData())
383*82d56013Sjoerg       continue;
384*82d56013Sjoerg 
385*82d56013Sjoerg     std::unique_ptr<AliasSetTracker> CurAST;
386*82d56013Sjoerg     if (!EnableMSSAInLoopSink) {
387*82d56013Sjoerg       CurAST = std::make_unique<AliasSetTracker>(AA);
388*82d56013Sjoerg       computeAliasSet(L, *Preheader, *CurAST.get());
389*82d56013Sjoerg     }
390*82d56013Sjoerg 
3917330f729Sjoerg     // Note that we don't pass SCEV here because it is only used to invalidate
3927330f729Sjoerg     // loops in SCEV and we don't preserve (or request) SCEV at all making that
3937330f729Sjoerg     // unnecessary.
3947330f729Sjoerg     Changed |= sinkLoopInvariantInstructions(L, AA, LI, DT, BFI,
395*82d56013Sjoerg                                              /*ScalarEvolution*/ nullptr,
396*82d56013Sjoerg                                              CurAST.get(), MSSA);
3977330f729Sjoerg   } while (!PreorderLoops.empty());
3987330f729Sjoerg 
3997330f729Sjoerg   if (!Changed)
4007330f729Sjoerg     return PreservedAnalyses::all();
4017330f729Sjoerg 
4027330f729Sjoerg   PreservedAnalyses PA;
4037330f729Sjoerg   PA.preserveSet<CFGAnalyses>();
404*82d56013Sjoerg 
405*82d56013Sjoerg   if (MSSA) {
406*82d56013Sjoerg     PA.preserve<MemorySSAAnalysis>();
407*82d56013Sjoerg 
408*82d56013Sjoerg     if (VerifyMemorySSA)
409*82d56013Sjoerg       MSSA->verifyMemorySSA();
410*82d56013Sjoerg   }
411*82d56013Sjoerg 
4127330f729Sjoerg   return PA;
4137330f729Sjoerg }
4147330f729Sjoerg 
4157330f729Sjoerg namespace {
4167330f729Sjoerg struct LegacyLoopSinkPass : public LoopPass {
4177330f729Sjoerg   static char ID;
LegacyLoopSinkPass__anon1b91e94d0511::LegacyLoopSinkPass4187330f729Sjoerg   LegacyLoopSinkPass() : LoopPass(ID) {
4197330f729Sjoerg     initializeLegacyLoopSinkPassPass(*PassRegistry::getPassRegistry());
4207330f729Sjoerg   }
4217330f729Sjoerg 
runOnLoop__anon1b91e94d0511::LegacyLoopSinkPass4227330f729Sjoerg   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
4237330f729Sjoerg     if (skipLoop(L))
4247330f729Sjoerg       return false;
4257330f729Sjoerg 
426*82d56013Sjoerg     BasicBlock *Preheader = L->getLoopPreheader();
427*82d56013Sjoerg     if (!Preheader)
428*82d56013Sjoerg       return false;
429*82d56013Sjoerg 
430*82d56013Sjoerg     // Enable LoopSink only when runtime profile is available.
431*82d56013Sjoerg     // With static profile, the sinking decision may be sub-optimal.
432*82d56013Sjoerg     if (!Preheader->getParent()->hasProfileData())
433*82d56013Sjoerg       return false;
434*82d56013Sjoerg 
435*82d56013Sjoerg     AAResults &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4367330f729Sjoerg     auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
437*82d56013Sjoerg     std::unique_ptr<AliasSetTracker> CurAST;
438*82d56013Sjoerg     MemorySSA *MSSA = nullptr;
439*82d56013Sjoerg     if (EnableMSSAInLegacyLoopSink)
440*82d56013Sjoerg       MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
441*82d56013Sjoerg     else {
442*82d56013Sjoerg       CurAST = std::make_unique<AliasSetTracker>(AA);
443*82d56013Sjoerg       computeAliasSet(*L, *Preheader, *CurAST.get());
444*82d56013Sjoerg     }
445*82d56013Sjoerg 
446*82d56013Sjoerg     bool Changed = sinkLoopInvariantInstructions(
447*82d56013Sjoerg         *L, AA, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
4487330f729Sjoerg         getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4497330f729Sjoerg         getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI(),
450*82d56013Sjoerg         SE ? &SE->getSE() : nullptr, CurAST.get(), MSSA);
451*82d56013Sjoerg 
452*82d56013Sjoerg     if (MSSA && VerifyMemorySSA)
453*82d56013Sjoerg       MSSA->verifyMemorySSA();
454*82d56013Sjoerg 
455*82d56013Sjoerg     return Changed;
4567330f729Sjoerg   }
4577330f729Sjoerg 
getAnalysisUsage__anon1b91e94d0511::LegacyLoopSinkPass4587330f729Sjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {
4597330f729Sjoerg     AU.setPreservesCFG();
4607330f729Sjoerg     AU.addRequired<BlockFrequencyInfoWrapperPass>();
4617330f729Sjoerg     getLoopAnalysisUsage(AU);
462*82d56013Sjoerg     if (EnableMSSAInLegacyLoopSink) {
463*82d56013Sjoerg       AU.addRequired<MemorySSAWrapperPass>();
464*82d56013Sjoerg       AU.addPreserved<MemorySSAWrapperPass>();
465*82d56013Sjoerg     }
4667330f729Sjoerg   }
4677330f729Sjoerg };
4687330f729Sjoerg }
4697330f729Sjoerg 
4707330f729Sjoerg char LegacyLoopSinkPass::ID = 0;
4717330f729Sjoerg INITIALIZE_PASS_BEGIN(LegacyLoopSinkPass, "loop-sink", "Loop Sink", false,
4727330f729Sjoerg                       false)
INITIALIZE_PASS_DEPENDENCY(LoopPass)4737330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(LoopPass)
4747330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
475*82d56013Sjoerg INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
4767330f729Sjoerg INITIALIZE_PASS_END(LegacyLoopSinkPass, "loop-sink", "Loop Sink", false, false)
4777330f729Sjoerg 
4787330f729Sjoerg Pass *llvm::createLoopSinkPass() { return new LegacyLoopSinkPass(); }
479