1 //===-- LoopSink.cpp - Loop Sink Pass -------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass does the inverse transformation of what LICM does. 10 // It traverses all of the instructions in the loop's preheader and sinks 11 // them to the loop body where frequency is lower than the loop's preheader. 12 // This pass is a reverse-transformation of LICM. It differs from the Sink 13 // pass in the following ways: 14 // 15 // * It only handles sinking of instructions from the loop's preheader to the 16 // loop's body 17 // * It uses alias set tracker to get more accurate alias info 18 // * It uses block frequency info to find the optimal sinking locations 19 // 20 // Overall algorithm: 21 // 22 // For I in Preheader: 23 // InsertBBs = BBs that uses I 24 // For BB in sorted(LoopBBs): 25 // DomBBs = BBs in InsertBBs that are dominated by BB 26 // if freq(DomBBs) > freq(BB) 27 // InsertBBs = UseBBs - DomBBs + BB 28 // For BB in InsertBBs: 29 // Insert I at BB's beginning 30 // 31 //===----------------------------------------------------------------------===// 32 33 #include "llvm/Transforms/Scalar/LoopSink.h" 34 #include "llvm/ADT/SetOperations.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/Analysis/AliasAnalysis.h" 37 #include "llvm/Analysis/AliasSetTracker.h" 38 #include "llvm/Analysis/BlockFrequencyInfo.h" 39 #include "llvm/Analysis/LoopInfo.h" 40 #include "llvm/Analysis/LoopPass.h" 41 #include "llvm/Analysis/MemorySSA.h" 42 #include "llvm/Analysis/MemorySSAUpdater.h" 43 #include "llvm/Analysis/ScalarEvolution.h" 44 #include "llvm/IR/Dominators.h" 45 #include "llvm/IR/Instructions.h" 46 #include "llvm/InitializePasses.h" 47 #include "llvm/Support/BranchProbability.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Transforms/Scalar.h" 50 #include "llvm/Transforms/Utils/Local.h" 51 #include "llvm/Transforms/Utils/LoopUtils.h" 52 using namespace llvm; 53 54 #define DEBUG_TYPE "loopsink" 55 56 STATISTIC(NumLoopSunk, "Number of instructions sunk into loop"); 57 STATISTIC(NumLoopSunkCloned, "Number of cloned instructions sunk into loop"); 58 59 static cl::opt<unsigned> SinkFrequencyPercentThreshold( 60 "sink-freq-percent-threshold", cl::Hidden, cl::init(90), 61 cl::desc("Do not sink instructions that require cloning unless they " 62 "execute less than this percent of the time.")); 63 64 static cl::opt<unsigned> MaxNumberOfUseBBsForSinking( 65 "max-uses-for-sinking", cl::Hidden, cl::init(30), 66 cl::desc("Do not sink instructions that have too many uses.")); 67 68 static cl::opt<bool> EnableMSSAInLoopSink( 69 "enable-mssa-in-loop-sink", cl::Hidden, cl::init(true), 70 cl::desc("Enable MemorySSA for LoopSink in new pass manager")); 71 72 static cl::opt<bool> EnableMSSAInLegacyLoopSink( 73 "enable-mssa-in-legacy-loop-sink", cl::Hidden, cl::init(false), 74 cl::desc("Enable MemorySSA for LoopSink in legacy pass manager")); 75 76 /// Return adjusted total frequency of \p BBs. 77 /// 78 /// * If there is only one BB, sinking instruction will not introduce code 79 /// size increase. Thus there is no need to adjust the frequency. 80 /// * If there are more than one BB, sinking would lead to code size increase. 81 /// In this case, we add some "tax" to the total frequency to make it harder 82 /// to sink. E.g. 83 /// Freq(Preheader) = 100 84 /// Freq(BBs) = sum(50, 49) = 99 85 /// Even if Freq(BBs) < Freq(Preheader), we will not sink from Preheade to 86 /// BBs as the difference is too small to justify the code size increase. 87 /// To model this, The adjusted Freq(BBs) will be: 88 /// AdjustedFreq(BBs) = 99 / SinkFrequencyPercentThreshold% 89 static BlockFrequency adjustedSumFreq(SmallPtrSetImpl<BasicBlock *> &BBs, 90 BlockFrequencyInfo &BFI) { 91 BlockFrequency T = 0; 92 for (BasicBlock *B : BBs) 93 T += BFI.getBlockFreq(B); 94 if (BBs.size() > 1) 95 T /= BranchProbability(SinkFrequencyPercentThreshold, 100); 96 return T; 97 } 98 99 /// Return a set of basic blocks to insert sinked instructions. 100 /// 101 /// The returned set of basic blocks (BBsToSinkInto) should satisfy: 102 /// 103 /// * Inside the loop \p L 104 /// * For each UseBB in \p UseBBs, there is at least one BB in BBsToSinkInto 105 /// that domintates the UseBB 106 /// * Has minimum total frequency that is no greater than preheader frequency 107 /// 108 /// The purpose of the function is to find the optimal sinking points to 109 /// minimize execution cost, which is defined as "sum of frequency of 110 /// BBsToSinkInto". 111 /// As a result, the returned BBsToSinkInto needs to have minimum total 112 /// frequency. 113 /// Additionally, if the total frequency of BBsToSinkInto exceeds preheader 114 /// frequency, the optimal solution is not sinking (return empty set). 115 /// 116 /// \p ColdLoopBBs is used to help find the optimal sinking locations. 117 /// It stores a list of BBs that is: 118 /// 119 /// * Inside the loop \p L 120 /// * Has a frequency no larger than the loop's preheader 121 /// * Sorted by BB frequency 122 /// 123 /// The complexity of the function is O(UseBBs.size() * ColdLoopBBs.size()). 124 /// To avoid expensive computation, we cap the maximum UseBBs.size() in its 125 /// caller. 126 static SmallPtrSet<BasicBlock *, 2> 127 findBBsToSinkInto(const Loop &L, const SmallPtrSetImpl<BasicBlock *> &UseBBs, 128 const SmallVectorImpl<BasicBlock *> &ColdLoopBBs, 129 DominatorTree &DT, BlockFrequencyInfo &BFI) { 130 SmallPtrSet<BasicBlock *, 2> BBsToSinkInto; 131 if (UseBBs.size() == 0) 132 return BBsToSinkInto; 133 134 BBsToSinkInto.insert(UseBBs.begin(), UseBBs.end()); 135 SmallPtrSet<BasicBlock *, 2> BBsDominatedByColdestBB; 136 137 // For every iteration: 138 // * Pick the ColdestBB from ColdLoopBBs 139 // * Find the set BBsDominatedByColdestBB that satisfy: 140 // - BBsDominatedByColdestBB is a subset of BBsToSinkInto 141 // - Every BB in BBsDominatedByColdestBB is dominated by ColdestBB 142 // * If Freq(ColdestBB) < Freq(BBsDominatedByColdestBB), remove 143 // BBsDominatedByColdestBB from BBsToSinkInto, add ColdestBB to 144 // BBsToSinkInto 145 for (BasicBlock *ColdestBB : ColdLoopBBs) { 146 BBsDominatedByColdestBB.clear(); 147 for (BasicBlock *SinkedBB : BBsToSinkInto) 148 if (DT.dominates(ColdestBB, SinkedBB)) 149 BBsDominatedByColdestBB.insert(SinkedBB); 150 if (BBsDominatedByColdestBB.size() == 0) 151 continue; 152 if (adjustedSumFreq(BBsDominatedByColdestBB, BFI) > 153 BFI.getBlockFreq(ColdestBB)) { 154 for (BasicBlock *DominatedBB : BBsDominatedByColdestBB) { 155 BBsToSinkInto.erase(DominatedBB); 156 } 157 BBsToSinkInto.insert(ColdestBB); 158 } 159 } 160 161 // Can't sink into blocks that have no valid insertion point. 162 for (BasicBlock *BB : BBsToSinkInto) { 163 if (BB->getFirstInsertionPt() == BB->end()) { 164 BBsToSinkInto.clear(); 165 break; 166 } 167 } 168 169 // If the total frequency of BBsToSinkInto is larger than preheader frequency, 170 // do not sink. 171 if (adjustedSumFreq(BBsToSinkInto, BFI) > 172 BFI.getBlockFreq(L.getLoopPreheader())) 173 BBsToSinkInto.clear(); 174 return BBsToSinkInto; 175 } 176 177 // Sinks \p I from the loop \p L's preheader to its uses. Returns true if 178 // sinking is successful. 179 // \p LoopBlockNumber is used to sort the insertion blocks to ensure 180 // determinism. 181 static bool sinkInstruction( 182 Loop &L, Instruction &I, const SmallVectorImpl<BasicBlock *> &ColdLoopBBs, 183 const SmallDenseMap<BasicBlock *, int, 16> &LoopBlockNumber, LoopInfo &LI, 184 DominatorTree &DT, BlockFrequencyInfo &BFI, MemorySSAUpdater *MSSAU) { 185 // Compute the set of blocks in loop L which contain a use of I. 186 SmallPtrSet<BasicBlock *, 2> BBs; 187 for (auto &U : I.uses()) { 188 Instruction *UI = cast<Instruction>(U.getUser()); 189 // We cannot sink I to PHI-uses. 190 if (isa<PHINode>(UI)) 191 return false; 192 // We cannot sink I if it has uses outside of the loop. 193 if (!L.contains(LI.getLoopFor(UI->getParent()))) 194 return false; 195 BBs.insert(UI->getParent()); 196 } 197 198 // findBBsToSinkInto is O(BBs.size() * ColdLoopBBs.size()). We cap the max 199 // BBs.size() to avoid expensive computation. 200 // FIXME: Handle code size growth for min_size and opt_size. 201 if (BBs.size() > MaxNumberOfUseBBsForSinking) 202 return false; 203 204 // Find the set of BBs that we should insert a copy of I. 205 SmallPtrSet<BasicBlock *, 2> BBsToSinkInto = 206 findBBsToSinkInto(L, BBs, ColdLoopBBs, DT, BFI); 207 if (BBsToSinkInto.empty()) 208 return false; 209 210 // Return if any of the candidate blocks to sink into is non-cold. 211 if (BBsToSinkInto.size() > 1 && 212 !llvm::set_is_subset(BBsToSinkInto, LoopBlockNumber)) 213 return false; 214 215 // Copy the final BBs into a vector and sort them using the total ordering 216 // of the loop block numbers as iterating the set doesn't give a useful 217 // order. No need to stable sort as the block numbers are a total ordering. 218 SmallVector<BasicBlock *, 2> SortedBBsToSinkInto; 219 llvm::append_range(SortedBBsToSinkInto, BBsToSinkInto); 220 llvm::sort(SortedBBsToSinkInto, [&](BasicBlock *A, BasicBlock *B) { 221 return LoopBlockNumber.find(A)->second < LoopBlockNumber.find(B)->second; 222 }); 223 224 BasicBlock *MoveBB = *SortedBBsToSinkInto.begin(); 225 // FIXME: Optimize the efficiency for cloned value replacement. The current 226 // implementation is O(SortedBBsToSinkInto.size() * I.num_uses()). 227 for (BasicBlock *N : makeArrayRef(SortedBBsToSinkInto).drop_front(1)) { 228 assert(LoopBlockNumber.find(N)->second > 229 LoopBlockNumber.find(MoveBB)->second && 230 "BBs not sorted!"); 231 // Clone I and replace its uses. 232 Instruction *IC = I.clone(); 233 IC->setName(I.getName()); 234 IC->insertBefore(&*N->getFirstInsertionPt()); 235 236 if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) { 237 // Create a new MemoryAccess and let MemorySSA set its defining access. 238 MemoryAccess *NewMemAcc = 239 MSSAU->createMemoryAccessInBB(IC, nullptr, N, MemorySSA::Beginning); 240 if (NewMemAcc) { 241 if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc)) 242 MSSAU->insertDef(MemDef, /*RenameUses=*/true); 243 else { 244 auto *MemUse = cast<MemoryUse>(NewMemAcc); 245 MSSAU->insertUse(MemUse, /*RenameUses=*/true); 246 } 247 } 248 } 249 250 // Replaces uses of I with IC in N 251 I.replaceUsesWithIf(IC, [N](Use &U) { 252 return cast<Instruction>(U.getUser())->getParent() == N; 253 }); 254 // Replaces uses of I with IC in blocks dominated by N 255 replaceDominatedUsesWith(&I, IC, DT, N); 256 LLVM_DEBUG(dbgs() << "Sinking a clone of " << I << " To: " << N->getName() 257 << '\n'); 258 NumLoopSunkCloned++; 259 } 260 LLVM_DEBUG(dbgs() << "Sinking " << I << " To: " << MoveBB->getName() << '\n'); 261 NumLoopSunk++; 262 I.moveBefore(&*MoveBB->getFirstInsertionPt()); 263 264 if (MSSAU) 265 if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>( 266 MSSAU->getMemorySSA()->getMemoryAccess(&I))) 267 MSSAU->moveToPlace(OldMemAcc, MoveBB, MemorySSA::Beginning); 268 269 return true; 270 } 271 272 /// Sinks instructions from loop's preheader to the loop body if the 273 /// sum frequency of inserted copy is smaller than preheader's frequency. 274 static bool sinkLoopInvariantInstructions(Loop &L, AAResults &AA, LoopInfo &LI, 275 DominatorTree &DT, 276 BlockFrequencyInfo &BFI, 277 ScalarEvolution *SE, 278 AliasSetTracker *CurAST, 279 MemorySSA *MSSA) { 280 BasicBlock *Preheader = L.getLoopPreheader(); 281 assert(Preheader && "Expected loop to have preheader"); 282 283 assert(Preheader->getParent()->hasProfileData() && 284 "Unexpected call when profile data unavailable."); 285 286 const BlockFrequency PreheaderFreq = BFI.getBlockFreq(Preheader); 287 // If there are no basic blocks with lower frequency than the preheader then 288 // we can avoid the detailed analysis as we will never find profitable sinking 289 // opportunities. 290 if (all_of(L.blocks(), [&](const BasicBlock *BB) { 291 return BFI.getBlockFreq(BB) > PreheaderFreq; 292 })) 293 return false; 294 295 std::unique_ptr<MemorySSAUpdater> MSSAU; 296 std::unique_ptr<SinkAndHoistLICMFlags> LICMFlags; 297 if (MSSA) { 298 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 299 LICMFlags = 300 std::make_unique<SinkAndHoistLICMFlags>(/*IsSink=*/true, &L, MSSA); 301 } 302 303 bool Changed = false; 304 305 // Sort loop's basic blocks by frequency 306 SmallVector<BasicBlock *, 10> ColdLoopBBs; 307 SmallDenseMap<BasicBlock *, int, 16> LoopBlockNumber; 308 int i = 0; 309 for (BasicBlock *B : L.blocks()) 310 if (BFI.getBlockFreq(B) < BFI.getBlockFreq(L.getLoopPreheader())) { 311 ColdLoopBBs.push_back(B); 312 LoopBlockNumber[B] = ++i; 313 } 314 llvm::stable_sort(ColdLoopBBs, [&](BasicBlock *A, BasicBlock *B) { 315 return BFI.getBlockFreq(A) < BFI.getBlockFreq(B); 316 }); 317 318 // Traverse preheader's instructions in reverse order becaue if A depends 319 // on B (A appears after B), A needs to be sinked first before B can be 320 // sinked. 321 for (Instruction &I : llvm::make_early_inc_range(llvm::reverse(*Preheader))) { 322 if (isa<PHINode>(&I)) 323 continue; 324 // No need to check for instruction's operands are loop invariant. 325 assert(L.hasLoopInvariantOperands(&I) && 326 "Insts in a loop's preheader should have loop invariant operands!"); 327 if (!canSinkOrHoistInst(I, &AA, &DT, &L, CurAST, MSSAU.get(), false, 328 LICMFlags.get())) 329 continue; 330 if (sinkInstruction(L, I, ColdLoopBBs, LoopBlockNumber, LI, DT, BFI, 331 MSSAU.get())) 332 Changed = true; 333 } 334 335 if (Changed && SE) 336 SE->forgetLoopDispositions(&L); 337 return Changed; 338 } 339 340 static void computeAliasSet(Loop &L, BasicBlock &Preheader, 341 AliasSetTracker &CurAST) { 342 for (BasicBlock *BB : L.blocks()) 343 CurAST.add(*BB); 344 CurAST.add(Preheader); 345 } 346 347 PreservedAnalyses LoopSinkPass::run(Function &F, FunctionAnalysisManager &FAM) { 348 LoopInfo &LI = FAM.getResult<LoopAnalysis>(F); 349 // Nothing to do if there are no loops. 350 if (LI.empty()) 351 return PreservedAnalyses::all(); 352 353 AAResults &AA = FAM.getResult<AAManager>(F); 354 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); 355 BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F); 356 357 MemorySSA *MSSA = EnableMSSAInLoopSink 358 ? &FAM.getResult<MemorySSAAnalysis>(F).getMSSA() 359 : nullptr; 360 361 // We want to do a postorder walk over the loops. Since loops are a tree this 362 // is equivalent to a reversed preorder walk and preorder is easy to compute 363 // without recursion. Since we reverse the preorder, we will visit siblings 364 // in reverse program order. This isn't expected to matter at all but is more 365 // consistent with sinking algorithms which generally work bottom-up. 366 SmallVector<Loop *, 4> PreorderLoops = LI.getLoopsInPreorder(); 367 368 bool Changed = false; 369 do { 370 Loop &L = *PreorderLoops.pop_back_val(); 371 372 BasicBlock *Preheader = L.getLoopPreheader(); 373 if (!Preheader) 374 continue; 375 376 // Enable LoopSink only when runtime profile is available. 377 // With static profile, the sinking decision may be sub-optimal. 378 if (!Preheader->getParent()->hasProfileData()) 379 continue; 380 381 std::unique_ptr<AliasSetTracker> CurAST; 382 if (!EnableMSSAInLoopSink) { 383 CurAST = std::make_unique<AliasSetTracker>(AA); 384 computeAliasSet(L, *Preheader, *CurAST); 385 } 386 387 // Note that we don't pass SCEV here because it is only used to invalidate 388 // loops in SCEV and we don't preserve (or request) SCEV at all making that 389 // unnecessary. 390 Changed |= sinkLoopInvariantInstructions(L, AA, LI, DT, BFI, 391 /*ScalarEvolution*/ nullptr, 392 CurAST.get(), MSSA); 393 } while (!PreorderLoops.empty()); 394 395 if (!Changed) 396 return PreservedAnalyses::all(); 397 398 PreservedAnalyses PA; 399 PA.preserveSet<CFGAnalyses>(); 400 401 if (MSSA) { 402 PA.preserve<MemorySSAAnalysis>(); 403 404 if (VerifyMemorySSA) 405 MSSA->verifyMemorySSA(); 406 } 407 408 return PA; 409 } 410 411 namespace { 412 struct LegacyLoopSinkPass : public LoopPass { 413 static char ID; 414 LegacyLoopSinkPass() : LoopPass(ID) { 415 initializeLegacyLoopSinkPassPass(*PassRegistry::getPassRegistry()); 416 } 417 418 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 419 if (skipLoop(L)) 420 return false; 421 422 BasicBlock *Preheader = L->getLoopPreheader(); 423 if (!Preheader) 424 return false; 425 426 // Enable LoopSink only when runtime profile is available. 427 // With static profile, the sinking decision may be sub-optimal. 428 if (!Preheader->getParent()->hasProfileData()) 429 return false; 430 431 AAResults &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 432 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 433 std::unique_ptr<AliasSetTracker> CurAST; 434 MemorySSA *MSSA = nullptr; 435 if (EnableMSSAInLegacyLoopSink) 436 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA(); 437 else { 438 CurAST = std::make_unique<AliasSetTracker>(AA); 439 computeAliasSet(*L, *Preheader, *CurAST); 440 } 441 442 bool Changed = sinkLoopInvariantInstructions( 443 *L, AA, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), 444 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 445 getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI(), 446 SE ? &SE->getSE() : nullptr, CurAST.get(), MSSA); 447 448 if (MSSA && VerifyMemorySSA) 449 MSSA->verifyMemorySSA(); 450 451 return Changed; 452 } 453 454 void getAnalysisUsage(AnalysisUsage &AU) const override { 455 AU.setPreservesCFG(); 456 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 457 getLoopAnalysisUsage(AU); 458 if (EnableMSSAInLegacyLoopSink) { 459 AU.addRequired<MemorySSAWrapperPass>(); 460 AU.addPreserved<MemorySSAWrapperPass>(); 461 } 462 } 463 }; 464 } 465 466 char LegacyLoopSinkPass::ID = 0; 467 INITIALIZE_PASS_BEGIN(LegacyLoopSinkPass, "loop-sink", "Loop Sink", false, 468 false) 469 INITIALIZE_PASS_DEPENDENCY(LoopPass) 470 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 471 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 472 INITIALIZE_PASS_END(LegacyLoopSinkPass, "loop-sink", "Loop Sink", false, false) 473 474 Pass *llvm::createLoopSinkPass() { return new LegacyLoopSinkPass(); } 475