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