Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopSink.cpp
35266 views
//===-- LoopSink.cpp - Loop Sink Pass -------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This pass does the inverse transformation of what LICM does.9// It traverses all of the instructions in the loop's preheader and sinks10// them to the loop body where frequency is lower than the loop's preheader.11// This pass is a reverse-transformation of LICM. It differs from the Sink12// pass in the following ways:13//14// * It only handles sinking of instructions from the loop's preheader to the15// loop's body16// * It uses alias set tracker to get more accurate alias info17// * It uses block frequency info to find the optimal sinking locations18//19// Overall algorithm:20//21// For I in Preheader:22// InsertBBs = BBs that uses I23// For BB in sorted(LoopBBs):24// DomBBs = BBs in InsertBBs that are dominated by BB25// if freq(DomBBs) > freq(BB)26// InsertBBs = UseBBs - DomBBs + BB27// For BB in InsertBBs:28// Insert I at BB's beginning29//30//===----------------------------------------------------------------------===//3132#include "llvm/Transforms/Scalar/LoopSink.h"33#include "llvm/ADT/SetOperations.h"34#include "llvm/ADT/Statistic.h"35#include "llvm/Analysis/AliasAnalysis.h"36#include "llvm/Analysis/BlockFrequencyInfo.h"37#include "llvm/Analysis/LoopInfo.h"38#include "llvm/Analysis/MemorySSA.h"39#include "llvm/Analysis/MemorySSAUpdater.h"40#include "llvm/Analysis/ScalarEvolution.h"41#include "llvm/IR/Dominators.h"42#include "llvm/IR/Instructions.h"43#include "llvm/Support/BranchProbability.h"44#include "llvm/Support/CommandLine.h"45#include "llvm/Transforms/Scalar.h"46#include "llvm/Transforms/Utils/Local.h"47#include "llvm/Transforms/Utils/LoopUtils.h"48using namespace llvm;4950#define DEBUG_TYPE "loopsink"5152STATISTIC(NumLoopSunk, "Number of instructions sunk into loop");53STATISTIC(NumLoopSunkCloned, "Number of cloned instructions sunk into loop");5455static cl::opt<unsigned> SinkFrequencyPercentThreshold(56"sink-freq-percent-threshold", cl::Hidden, cl::init(90),57cl::desc("Do not sink instructions that require cloning unless they "58"execute less than this percent of the time."));5960static cl::opt<unsigned> MaxNumberOfUseBBsForSinking(61"max-uses-for-sinking", cl::Hidden, cl::init(30),62cl::desc("Do not sink instructions that have too many uses."));6364/// Return adjusted total frequency of \p BBs.65///66/// * If there is only one BB, sinking instruction will not introduce code67/// size increase. Thus there is no need to adjust the frequency.68/// * If there are more than one BB, sinking would lead to code size increase.69/// In this case, we add some "tax" to the total frequency to make it harder70/// to sink. E.g.71/// Freq(Preheader) = 10072/// Freq(BBs) = sum(50, 49) = 9973/// Even if Freq(BBs) < Freq(Preheader), we will not sink from Preheade to74/// BBs as the difference is too small to justify the code size increase.75/// To model this, The adjusted Freq(BBs) will be:76/// AdjustedFreq(BBs) = 99 / SinkFrequencyPercentThreshold%77static BlockFrequency adjustedSumFreq(SmallPtrSetImpl<BasicBlock *> &BBs,78BlockFrequencyInfo &BFI) {79BlockFrequency T(0);80for (BasicBlock *B : BBs)81T += BFI.getBlockFreq(B);82if (BBs.size() > 1)83T /= BranchProbability(SinkFrequencyPercentThreshold, 100);84return T;85}8687/// Return a set of basic blocks to insert sinked instructions.88///89/// The returned set of basic blocks (BBsToSinkInto) should satisfy:90///91/// * Inside the loop \p L92/// * For each UseBB in \p UseBBs, there is at least one BB in BBsToSinkInto93/// that domintates the UseBB94/// * Has minimum total frequency that is no greater than preheader frequency95///96/// The purpose of the function is to find the optimal sinking points to97/// minimize execution cost, which is defined as "sum of frequency of98/// BBsToSinkInto".99/// As a result, the returned BBsToSinkInto needs to have minimum total100/// frequency.101/// Additionally, if the total frequency of BBsToSinkInto exceeds preheader102/// frequency, the optimal solution is not sinking (return empty set).103///104/// \p ColdLoopBBs is used to help find the optimal sinking locations.105/// It stores a list of BBs that is:106///107/// * Inside the loop \p L108/// * Has a frequency no larger than the loop's preheader109/// * Sorted by BB frequency110///111/// The complexity of the function is O(UseBBs.size() * ColdLoopBBs.size()).112/// To avoid expensive computation, we cap the maximum UseBBs.size() in its113/// caller.114static SmallPtrSet<BasicBlock *, 2>115findBBsToSinkInto(const Loop &L, const SmallPtrSetImpl<BasicBlock *> &UseBBs,116const SmallVectorImpl<BasicBlock *> &ColdLoopBBs,117DominatorTree &DT, BlockFrequencyInfo &BFI) {118SmallPtrSet<BasicBlock *, 2> BBsToSinkInto;119if (UseBBs.size() == 0)120return BBsToSinkInto;121122BBsToSinkInto.insert(UseBBs.begin(), UseBBs.end());123SmallPtrSet<BasicBlock *, 2> BBsDominatedByColdestBB;124125// For every iteration:126// * Pick the ColdestBB from ColdLoopBBs127// * Find the set BBsDominatedByColdestBB that satisfy:128// - BBsDominatedByColdestBB is a subset of BBsToSinkInto129// - Every BB in BBsDominatedByColdestBB is dominated by ColdestBB130// * If Freq(ColdestBB) < Freq(BBsDominatedByColdestBB), remove131// BBsDominatedByColdestBB from BBsToSinkInto, add ColdestBB to132// BBsToSinkInto133for (BasicBlock *ColdestBB : ColdLoopBBs) {134BBsDominatedByColdestBB.clear();135for (BasicBlock *SinkedBB : BBsToSinkInto)136if (DT.dominates(ColdestBB, SinkedBB))137BBsDominatedByColdestBB.insert(SinkedBB);138if (BBsDominatedByColdestBB.size() == 0)139continue;140if (adjustedSumFreq(BBsDominatedByColdestBB, BFI) >141BFI.getBlockFreq(ColdestBB)) {142for (BasicBlock *DominatedBB : BBsDominatedByColdestBB) {143BBsToSinkInto.erase(DominatedBB);144}145BBsToSinkInto.insert(ColdestBB);146}147}148149// Can't sink into blocks that have no valid insertion point.150for (BasicBlock *BB : BBsToSinkInto) {151if (BB->getFirstInsertionPt() == BB->end()) {152BBsToSinkInto.clear();153break;154}155}156157// If the total frequency of BBsToSinkInto is larger than preheader frequency,158// do not sink.159if (adjustedSumFreq(BBsToSinkInto, BFI) >160BFI.getBlockFreq(L.getLoopPreheader()))161BBsToSinkInto.clear();162return BBsToSinkInto;163}164165// Sinks \p I from the loop \p L's preheader to its uses. Returns true if166// sinking is successful.167// \p LoopBlockNumber is used to sort the insertion blocks to ensure168// determinism.169static bool sinkInstruction(170Loop &L, Instruction &I, const SmallVectorImpl<BasicBlock *> &ColdLoopBBs,171const SmallDenseMap<BasicBlock *, int, 16> &LoopBlockNumber, LoopInfo &LI,172DominatorTree &DT, BlockFrequencyInfo &BFI, MemorySSAUpdater *MSSAU) {173// Compute the set of blocks in loop L which contain a use of I.174SmallPtrSet<BasicBlock *, 2> BBs;175for (auto &U : I.uses()) {176Instruction *UI = cast<Instruction>(U.getUser());177178// We cannot sink I if it has uses outside of the loop.179if (!L.contains(LI.getLoopFor(UI->getParent())))180return false;181182if (!isa<PHINode>(UI)) {183BBs.insert(UI->getParent());184continue;185}186187// We cannot sink I to PHI-uses, try to look through PHI to find the incoming188// block of the value being used.189PHINode *PN = dyn_cast<PHINode>(UI);190BasicBlock *PhiBB = PN->getIncomingBlock(U);191192// If value's incoming block is from loop preheader directly, there's no193// place to sink to, bailout.194if (L.getLoopPreheader() == PhiBB)195return false;196197BBs.insert(PhiBB);198}199200// findBBsToSinkInto is O(BBs.size() * ColdLoopBBs.size()). We cap the max201// BBs.size() to avoid expensive computation.202// FIXME: Handle code size growth for min_size and opt_size.203if (BBs.size() > MaxNumberOfUseBBsForSinking)204return false;205206// Find the set of BBs that we should insert a copy of I.207SmallPtrSet<BasicBlock *, 2> BBsToSinkInto =208findBBsToSinkInto(L, BBs, ColdLoopBBs, DT, BFI);209if (BBsToSinkInto.empty())210return false;211212// Return if any of the candidate blocks to sink into is non-cold.213if (BBsToSinkInto.size() > 1 &&214!llvm::set_is_subset(BBsToSinkInto, LoopBlockNumber))215return false;216217// Copy the final BBs into a vector and sort them using the total ordering218// of the loop block numbers as iterating the set doesn't give a useful219// order. No need to stable sort as the block numbers are a total ordering.220SmallVector<BasicBlock *, 2> SortedBBsToSinkInto;221llvm::append_range(SortedBBsToSinkInto, BBsToSinkInto);222if (SortedBBsToSinkInto.size() > 1) {223llvm::sort(SortedBBsToSinkInto, [&](BasicBlock *A, BasicBlock *B) {224return LoopBlockNumber.find(A)->second < LoopBlockNumber.find(B)->second;225});226}227228BasicBlock *MoveBB = *SortedBBsToSinkInto.begin();229// FIXME: Optimize the efficiency for cloned value replacement. The current230// implementation is O(SortedBBsToSinkInto.size() * I.num_uses()).231for (BasicBlock *N : ArrayRef(SortedBBsToSinkInto).drop_front(1)) {232assert(LoopBlockNumber.find(N)->second >233LoopBlockNumber.find(MoveBB)->second &&234"BBs not sorted!");235// Clone I and replace its uses.236Instruction *IC = I.clone();237IC->setName(I.getName());238IC->insertBefore(&*N->getFirstInsertionPt());239240if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) {241// Create a new MemoryAccess and let MemorySSA set its defining access.242MemoryAccess *NewMemAcc =243MSSAU->createMemoryAccessInBB(IC, nullptr, N, MemorySSA::Beginning);244if (NewMemAcc) {245if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))246MSSAU->insertDef(MemDef, /*RenameUses=*/true);247else {248auto *MemUse = cast<MemoryUse>(NewMemAcc);249MSSAU->insertUse(MemUse, /*RenameUses=*/true);250}251}252}253254// Replaces uses of I with IC in N, except PHI-use which is being taken255// care of by defs in PHI's incoming blocks.256I.replaceUsesWithIf(IC, [N](Use &U) {257Instruction *UIToReplace = cast<Instruction>(U.getUser());258return UIToReplace->getParent() == N && !isa<PHINode>(UIToReplace);259});260// Replaces uses of I with IC in blocks dominated by N261replaceDominatedUsesWith(&I, IC, DT, N);262LLVM_DEBUG(dbgs() << "Sinking a clone of " << I << " To: " << N->getName()263<< '\n');264NumLoopSunkCloned++;265}266LLVM_DEBUG(dbgs() << "Sinking " << I << " To: " << MoveBB->getName() << '\n');267NumLoopSunk++;268I.moveBefore(&*MoveBB->getFirstInsertionPt());269270if (MSSAU)271if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>(272MSSAU->getMemorySSA()->getMemoryAccess(&I)))273MSSAU->moveToPlace(OldMemAcc, MoveBB, MemorySSA::Beginning);274275return true;276}277278/// Sinks instructions from loop's preheader to the loop body if the279/// sum frequency of inserted copy is smaller than preheader's frequency.280static bool sinkLoopInvariantInstructions(Loop &L, AAResults &AA, LoopInfo &LI,281DominatorTree &DT,282BlockFrequencyInfo &BFI,283MemorySSA &MSSA,284ScalarEvolution *SE) {285BasicBlock *Preheader = L.getLoopPreheader();286assert(Preheader && "Expected loop to have preheader");287288assert(Preheader->getParent()->hasProfileData() &&289"Unexpected call when profile data unavailable.");290291const BlockFrequency PreheaderFreq = BFI.getBlockFreq(Preheader);292// If there are no basic blocks with lower frequency than the preheader then293// we can avoid the detailed analysis as we will never find profitable sinking294// opportunities.295if (all_of(L.blocks(), [&](const BasicBlock *BB) {296return BFI.getBlockFreq(BB) > PreheaderFreq;297}))298return false;299300MemorySSAUpdater MSSAU(&MSSA);301SinkAndHoistLICMFlags LICMFlags(/*IsSink=*/true, L, MSSA);302303bool Changed = false;304305// Sort loop's basic blocks by frequency306SmallVector<BasicBlock *, 10> ColdLoopBBs;307SmallDenseMap<BasicBlock *, int, 16> LoopBlockNumber;308int i = 0;309for (BasicBlock *B : L.blocks())310if (BFI.getBlockFreq(B) < BFI.getBlockFreq(L.getLoopPreheader())) {311ColdLoopBBs.push_back(B);312LoopBlockNumber[B] = ++i;313}314llvm::stable_sort(ColdLoopBBs, [&](BasicBlock *A, BasicBlock *B) {315return BFI.getBlockFreq(A) < BFI.getBlockFreq(B);316});317318// Traverse preheader's instructions in reverse order because if A depends319// on B (A appears after B), A needs to be sunk first before B can be320// sinked.321for (Instruction &I : llvm::make_early_inc_range(llvm::reverse(*Preheader))) {322if (isa<PHINode>(&I))323continue;324// No need to check for instruction's operands are loop invariant.325assert(L.hasLoopInvariantOperands(&I) &&326"Insts in a loop's preheader should have loop invariant operands!");327if (!canSinkOrHoistInst(I, &AA, &DT, &L, MSSAU, false, LICMFlags))328continue;329if (sinkInstruction(L, I, ColdLoopBBs, LoopBlockNumber, LI, DT, BFI,330&MSSAU)) {331Changed = true;332if (SE)333SE->forgetBlockAndLoopDispositions(&I);334}335}336337return Changed;338}339340PreservedAnalyses LoopSinkPass::run(Function &F, FunctionAnalysisManager &FAM) {341// Enable LoopSink only when runtime profile is available.342// With static profile, the sinking decision may be sub-optimal.343if (!F.hasProfileData())344return PreservedAnalyses::all();345346LoopInfo &LI = FAM.getResult<LoopAnalysis>(F);347// Nothing to do if there are no loops.348if (LI.empty())349return PreservedAnalyses::all();350351AAResults &AA = FAM.getResult<AAManager>(F);352DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);353BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);354MemorySSA &MSSA = FAM.getResult<MemorySSAAnalysis>(F).getMSSA();355356// We want to do a postorder walk over the loops. Since loops are a tree this357// is equivalent to a reversed preorder walk and preorder is easy to compute358// without recursion. Since we reverse the preorder, we will visit siblings359// in reverse program order. This isn't expected to matter at all but is more360// consistent with sinking algorithms which generally work bottom-up.361SmallVector<Loop *, 4> PreorderLoops = LI.getLoopsInPreorder();362363bool Changed = false;364do {365Loop &L = *PreorderLoops.pop_back_val();366367BasicBlock *Preheader = L.getLoopPreheader();368if (!Preheader)369continue;370371// Note that we don't pass SCEV here because it is only used to invalidate372// loops in SCEV and we don't preserve (or request) SCEV at all making that373// unnecessary.374Changed |= sinkLoopInvariantInstructions(L, AA, LI, DT, BFI, MSSA,375/*ScalarEvolution*/ nullptr);376} while (!PreorderLoops.empty());377378if (!Changed)379return PreservedAnalyses::all();380381PreservedAnalyses PA;382PA.preserveSet<CFGAnalyses>();383PA.preserve<MemorySSAAnalysis>();384385if (VerifyMemorySSA)386MSSA.verifyMemorySSA();387388return PA;389}390391392