1 //===- ProfileSummaryInfo.cpp - Global profile summary information --------===// 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 file contains a pass that provides access to the global profile summary 10 // information. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Analysis/ProfileSummaryInfo.h" 15 #include "llvm/Analysis/BlockFrequencyInfo.h" 16 #include "llvm/IR/BasicBlock.h" 17 #include "llvm/IR/CallSite.h" 18 #include "llvm/IR/Metadata.h" 19 #include "llvm/IR/Module.h" 20 #include "llvm/IR/ProfileSummary.h" 21 #include "llvm/InitializePasses.h" 22 #include "llvm/Support/CommandLine.h" 23 using namespace llvm; 24 25 // The following two parameters determine the threshold for a count to be 26 // considered hot/cold. These two parameters are percentile values (multiplied 27 // by 10000). If the counts are sorted in descending order, the minimum count to 28 // reach ProfileSummaryCutoffHot gives the threshold to determine a hot count. 29 // Similarly, the minimum count to reach ProfileSummaryCutoffCold gives the 30 // threshold for determining cold count (everything <= this threshold is 31 // considered cold). 32 33 static cl::opt<int> ProfileSummaryCutoffHot( 34 "profile-summary-cutoff-hot", cl::Hidden, cl::init(990000), cl::ZeroOrMore, 35 cl::desc("A count is hot if it exceeds the minimum count to" 36 " reach this percentile of total counts.")); 37 38 static cl::opt<int> ProfileSummaryCutoffCold( 39 "profile-summary-cutoff-cold", cl::Hidden, cl::init(999999), cl::ZeroOrMore, 40 cl::desc("A count is cold if it is below the minimum count" 41 " to reach this percentile of total counts.")); 42 43 static cl::opt<unsigned> ProfileSummaryHugeWorkingSetSizeThreshold( 44 "profile-summary-huge-working-set-size-threshold", cl::Hidden, 45 cl::init(15000), cl::ZeroOrMore, 46 cl::desc("The code working set size is considered huge if the number of" 47 " blocks required to reach the -profile-summary-cutoff-hot" 48 " percentile exceeds this count.")); 49 50 static cl::opt<unsigned> ProfileSummaryLargeWorkingSetSizeThreshold( 51 "profile-summary-large-working-set-size-threshold", cl::Hidden, 52 cl::init(12500), cl::ZeroOrMore, 53 cl::desc("The code working set size is considered large if the number of" 54 " blocks required to reach the -profile-summary-cutoff-hot" 55 " percentile exceeds this count.")); 56 57 // The next two options override the counts derived from summary computation and 58 // are useful for debugging purposes. 59 static cl::opt<int> ProfileSummaryHotCount( 60 "profile-summary-hot-count", cl::ReallyHidden, cl::ZeroOrMore, 61 cl::desc("A fixed hot count that overrides the count derived from" 62 " profile-summary-cutoff-hot")); 63 64 static cl::opt<int> ProfileSummaryColdCount( 65 "profile-summary-cold-count", cl::ReallyHidden, cl::ZeroOrMore, 66 cl::desc("A fixed cold count that overrides the count derived from" 67 " profile-summary-cutoff-cold")); 68 69 // Find the summary entry for a desired percentile of counts. 70 static const ProfileSummaryEntry &getEntryForPercentile(SummaryEntryVector &DS, 71 uint64_t Percentile) { 72 auto It = partition_point(DS, [=](const ProfileSummaryEntry &Entry) { 73 return Entry.Cutoff < Percentile; 74 }); 75 // The required percentile has to be <= one of the percentiles in the 76 // detailed summary. 77 if (It == DS.end()) 78 report_fatal_error("Desired percentile exceeds the maximum cutoff"); 79 return *It; 80 } 81 82 // The profile summary metadata may be attached either by the frontend or by 83 // any backend passes (IR level instrumentation, for example). This method 84 // checks if the Summary is null and if so checks if the summary metadata is now 85 // available in the module and parses it to get the Summary object. Returns true 86 // if a valid Summary is available. 87 bool ProfileSummaryInfo::computeSummary() { 88 if (Summary) 89 return true; 90 // First try to get context sensitive ProfileSummary. 91 auto *SummaryMD = M.getProfileSummary(/* IsCS */ true); 92 if (SummaryMD) { 93 Summary.reset(ProfileSummary::getFromMD(SummaryMD)); 94 return true; 95 } 96 // This will actually return PSK_Instr or PSK_Sample summary. 97 SummaryMD = M.getProfileSummary(/* IsCS */ false); 98 if (!SummaryMD) 99 return false; 100 Summary.reset(ProfileSummary::getFromMD(SummaryMD)); 101 return true; 102 } 103 104 Optional<uint64_t> 105 ProfileSummaryInfo::getProfileCount(const Instruction *Inst, 106 BlockFrequencyInfo *BFI, 107 bool AllowSynthetic) { 108 if (!Inst) 109 return None; 110 assert((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) && 111 "We can only get profile count for call/invoke instruction."); 112 if (hasSampleProfile()) { 113 // In sample PGO mode, check if there is a profile metadata on the 114 // instruction. If it is present, determine hotness solely based on that, 115 // since the sampled entry count may not be accurate. If there is no 116 // annotated on the instruction, return None. 117 uint64_t TotalCount; 118 if (Inst->extractProfTotalWeight(TotalCount)) 119 return TotalCount; 120 return None; 121 } 122 if (BFI) 123 return BFI->getBlockProfileCount(Inst->getParent(), AllowSynthetic); 124 return None; 125 } 126 127 /// Returns true if the function's entry is hot. If it returns false, it 128 /// either means it is not hot or it is unknown whether it is hot or not (for 129 /// example, no profile data is available). 130 bool ProfileSummaryInfo::isFunctionEntryHot(const Function *F) { 131 if (!F || !computeSummary()) 132 return false; 133 auto FunctionCount = F->getEntryCount(); 134 // FIXME: The heuristic used below for determining hotness is based on 135 // preliminary SPEC tuning for inliner. This will eventually be a 136 // convenience method that calls isHotCount. 137 return FunctionCount && isHotCount(FunctionCount.getCount()); 138 } 139 140 /// Returns true if the function contains hot code. This can include a hot 141 /// function entry count, hot basic block, or (in the case of Sample PGO) 142 /// hot total call edge count. 143 /// If it returns false, it either means it is not hot or it is unknown 144 /// (for example, no profile data is available). 145 bool ProfileSummaryInfo::isFunctionHotInCallGraph(const Function *F, 146 BlockFrequencyInfo &BFI) { 147 if (!F || !computeSummary()) 148 return false; 149 if (auto FunctionCount = F->getEntryCount()) 150 if (isHotCount(FunctionCount.getCount())) 151 return true; 152 153 if (hasSampleProfile()) { 154 uint64_t TotalCallCount = 0; 155 for (const auto &BB : *F) 156 for (const auto &I : BB) 157 if (isa<CallInst>(I) || isa<InvokeInst>(I)) 158 if (auto CallCount = getProfileCount(&I, nullptr)) 159 TotalCallCount += CallCount.getValue(); 160 if (isHotCount(TotalCallCount)) 161 return true; 162 } 163 for (const auto &BB : *F) 164 if (isHotBlock(&BB, &BFI)) 165 return true; 166 return false; 167 } 168 169 /// Returns true if the function only contains cold code. This means that 170 /// the function entry and blocks are all cold, and (in the case of Sample PGO) 171 /// the total call edge count is cold. 172 /// If it returns false, it either means it is not cold or it is unknown 173 /// (for example, no profile data is available). 174 bool ProfileSummaryInfo::isFunctionColdInCallGraph(const Function *F, 175 BlockFrequencyInfo &BFI) { 176 if (!F || !computeSummary()) 177 return false; 178 if (auto FunctionCount = F->getEntryCount()) 179 if (!isColdCount(FunctionCount.getCount())) 180 return false; 181 182 if (hasSampleProfile()) { 183 uint64_t TotalCallCount = 0; 184 for (const auto &BB : *F) 185 for (const auto &I : BB) 186 if (isa<CallInst>(I) || isa<InvokeInst>(I)) 187 if (auto CallCount = getProfileCount(&I, nullptr)) 188 TotalCallCount += CallCount.getValue(); 189 if (!isColdCount(TotalCallCount)) 190 return false; 191 } 192 for (const auto &BB : *F) 193 if (!isColdBlock(&BB, &BFI)) 194 return false; 195 return true; 196 } 197 198 template<bool isHot> 199 bool ProfileSummaryInfo::isFunctionHotOrColdInCallGraphNthPercentile( 200 int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) { 201 if (!F || !computeSummary()) 202 return false; 203 if (auto FunctionCount = F->getEntryCount()) { 204 if (isHot && 205 isHotCountNthPercentile(PercentileCutoff, FunctionCount.getCount())) 206 return true; 207 if (!isHot && 208 !isColdCountNthPercentile(PercentileCutoff, FunctionCount.getCount())) 209 return false; 210 } 211 if (hasSampleProfile()) { 212 uint64_t TotalCallCount = 0; 213 for (const auto &BB : *F) 214 for (const auto &I : BB) 215 if (isa<CallInst>(I) || isa<InvokeInst>(I)) 216 if (auto CallCount = getProfileCount(&I, nullptr)) 217 TotalCallCount += CallCount.getValue(); 218 if (isHot && isHotCountNthPercentile(PercentileCutoff, TotalCallCount)) 219 return true; 220 if (!isHot && !isColdCountNthPercentile(PercentileCutoff, TotalCallCount)) 221 return false; 222 } 223 for (const auto &BB : *F) { 224 if (isHot && isHotBlockNthPercentile(PercentileCutoff, &BB, &BFI)) 225 return true; 226 if (!isHot && !isColdBlockNthPercentile(PercentileCutoff, &BB, &BFI)) 227 return false; 228 } 229 return !isHot; 230 } 231 232 // Like isFunctionHotInCallGraph but for a given cutoff. 233 bool ProfileSummaryInfo::isFunctionHotInCallGraphNthPercentile( 234 int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) { 235 return isFunctionHotOrColdInCallGraphNthPercentile<true>( 236 PercentileCutoff, F, BFI); 237 } 238 239 bool ProfileSummaryInfo::isFunctionColdInCallGraphNthPercentile( 240 int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) { 241 return isFunctionHotOrColdInCallGraphNthPercentile<false>( 242 PercentileCutoff, F, BFI); 243 } 244 245 /// Returns true if the function's entry is a cold. If it returns false, it 246 /// either means it is not cold or it is unknown whether it is cold or not (for 247 /// example, no profile data is available). 248 bool ProfileSummaryInfo::isFunctionEntryCold(const Function *F) { 249 if (!F) 250 return false; 251 if (F->hasFnAttribute(Attribute::Cold)) 252 return true; 253 if (!computeSummary()) 254 return false; 255 auto FunctionCount = F->getEntryCount(); 256 // FIXME: The heuristic used below for determining coldness is based on 257 // preliminary SPEC tuning for inliner. This will eventually be a 258 // convenience method that calls isHotCount. 259 return FunctionCount && isColdCount(FunctionCount.getCount()); 260 } 261 262 /// Compute the hot and cold thresholds. 263 void ProfileSummaryInfo::computeThresholds() { 264 if (!computeSummary()) 265 return; 266 auto &DetailedSummary = Summary->getDetailedSummary(); 267 auto &HotEntry = 268 getEntryForPercentile(DetailedSummary, ProfileSummaryCutoffHot); 269 HotCountThreshold = HotEntry.MinCount; 270 if (ProfileSummaryHotCount.getNumOccurrences() > 0) 271 HotCountThreshold = ProfileSummaryHotCount; 272 auto &ColdEntry = 273 getEntryForPercentile(DetailedSummary, ProfileSummaryCutoffCold); 274 ColdCountThreshold = ColdEntry.MinCount; 275 if (ProfileSummaryColdCount.getNumOccurrences() > 0) 276 ColdCountThreshold = ProfileSummaryColdCount; 277 assert(ColdCountThreshold <= HotCountThreshold && 278 "Cold count threshold cannot exceed hot count threshold!"); 279 HasHugeWorkingSetSize = 280 HotEntry.NumCounts > ProfileSummaryHugeWorkingSetSizeThreshold; 281 HasLargeWorkingSetSize = 282 HotEntry.NumCounts > ProfileSummaryLargeWorkingSetSizeThreshold; 283 } 284 285 Optional<uint64_t> ProfileSummaryInfo::computeThreshold(int PercentileCutoff) { 286 if (!computeSummary()) 287 return None; 288 auto iter = ThresholdCache.find(PercentileCutoff); 289 if (iter != ThresholdCache.end()) { 290 return iter->second; 291 } 292 auto &DetailedSummary = Summary->getDetailedSummary(); 293 auto &Entry = 294 getEntryForPercentile(DetailedSummary, PercentileCutoff); 295 uint64_t CountThreshold = Entry.MinCount; 296 ThresholdCache[PercentileCutoff] = CountThreshold; 297 return CountThreshold; 298 } 299 300 bool ProfileSummaryInfo::hasHugeWorkingSetSize() { 301 if (!HasHugeWorkingSetSize) 302 computeThresholds(); 303 return HasHugeWorkingSetSize && HasHugeWorkingSetSize.getValue(); 304 } 305 306 bool ProfileSummaryInfo::hasLargeWorkingSetSize() { 307 if (!HasLargeWorkingSetSize) 308 computeThresholds(); 309 return HasLargeWorkingSetSize && HasLargeWorkingSetSize.getValue(); 310 } 311 312 bool ProfileSummaryInfo::isHotCount(uint64_t C) { 313 if (!HotCountThreshold) 314 computeThresholds(); 315 return HotCountThreshold && C >= HotCountThreshold.getValue(); 316 } 317 318 bool ProfileSummaryInfo::isColdCount(uint64_t C) { 319 if (!ColdCountThreshold) 320 computeThresholds(); 321 return ColdCountThreshold && C <= ColdCountThreshold.getValue(); 322 } 323 324 template<bool isHot> 325 bool ProfileSummaryInfo::isHotOrColdCountNthPercentile(int PercentileCutoff, 326 uint64_t C) { 327 auto CountThreshold = computeThreshold(PercentileCutoff); 328 if (isHot) 329 return CountThreshold && C >= CountThreshold.getValue(); 330 else 331 return CountThreshold && C <= CountThreshold.getValue(); 332 } 333 334 bool ProfileSummaryInfo::isHotCountNthPercentile(int PercentileCutoff, uint64_t C) { 335 return isHotOrColdCountNthPercentile<true>(PercentileCutoff, C); 336 } 337 338 bool ProfileSummaryInfo::isColdCountNthPercentile(int PercentileCutoff, uint64_t C) { 339 return isHotOrColdCountNthPercentile<false>(PercentileCutoff, C); 340 } 341 342 uint64_t ProfileSummaryInfo::getOrCompHotCountThreshold() { 343 if (!HotCountThreshold) 344 computeThresholds(); 345 return HotCountThreshold ? HotCountThreshold.getValue() : UINT64_MAX; 346 } 347 348 uint64_t ProfileSummaryInfo::getOrCompColdCountThreshold() { 349 if (!ColdCountThreshold) 350 computeThresholds(); 351 return ColdCountThreshold ? ColdCountThreshold.getValue() : 0; 352 } 353 354 bool ProfileSummaryInfo::isHotBlock(const BasicBlock *BB, BlockFrequencyInfo *BFI) { 355 auto Count = BFI->getBlockProfileCount(BB); 356 return Count && isHotCount(*Count); 357 } 358 359 bool ProfileSummaryInfo::isColdBlock(const BasicBlock *BB, 360 BlockFrequencyInfo *BFI) { 361 auto Count = BFI->getBlockProfileCount(BB); 362 return Count && isColdCount(*Count); 363 } 364 365 template<bool isHot> 366 bool ProfileSummaryInfo::isHotOrColdBlockNthPercentile(int PercentileCutoff, 367 const BasicBlock *BB, 368 BlockFrequencyInfo *BFI) { 369 auto Count = BFI->getBlockProfileCount(BB); 370 if (isHot) 371 return Count && isHotCountNthPercentile(PercentileCutoff, *Count); 372 else 373 return Count && isColdCountNthPercentile(PercentileCutoff, *Count); 374 } 375 376 bool ProfileSummaryInfo::isHotBlockNthPercentile(int PercentileCutoff, 377 const BasicBlock *BB, 378 BlockFrequencyInfo *BFI) { 379 return isHotOrColdBlockNthPercentile<true>(PercentileCutoff, BB, BFI); 380 } 381 382 bool ProfileSummaryInfo::isColdBlockNthPercentile(int PercentileCutoff, 383 const BasicBlock *BB, 384 BlockFrequencyInfo *BFI) { 385 return isHotOrColdBlockNthPercentile<false>(PercentileCutoff, BB, BFI); 386 } 387 388 bool ProfileSummaryInfo::isHotCallSite(const CallSite &CS, 389 BlockFrequencyInfo *BFI) { 390 auto C = getProfileCount(CS.getInstruction(), BFI); 391 return C && isHotCount(*C); 392 } 393 394 bool ProfileSummaryInfo::isColdCallSite(const CallSite &CS, 395 BlockFrequencyInfo *BFI) { 396 auto C = getProfileCount(CS.getInstruction(), BFI); 397 if (C) 398 return isColdCount(*C); 399 400 // In SamplePGO, if the caller has been sampled, and there is no profile 401 // annotated on the callsite, we consider the callsite as cold. 402 return hasSampleProfile() && CS.getCaller()->hasProfileData(); 403 } 404 405 INITIALIZE_PASS(ProfileSummaryInfoWrapperPass, "profile-summary-info", 406 "Profile summary info", false, true) 407 408 ProfileSummaryInfoWrapperPass::ProfileSummaryInfoWrapperPass() 409 : ImmutablePass(ID) { 410 initializeProfileSummaryInfoWrapperPassPass(*PassRegistry::getPassRegistry()); 411 } 412 413 bool ProfileSummaryInfoWrapperPass::doInitialization(Module &M) { 414 PSI.reset(new ProfileSummaryInfo(M)); 415 return false; 416 } 417 418 bool ProfileSummaryInfoWrapperPass::doFinalization(Module &M) { 419 PSI.reset(); 420 return false; 421 } 422 423 AnalysisKey ProfileSummaryAnalysis::Key; 424 ProfileSummaryInfo ProfileSummaryAnalysis::run(Module &M, 425 ModuleAnalysisManager &) { 426 return ProfileSummaryInfo(M); 427 } 428 429 PreservedAnalyses ProfileSummaryPrinterPass::run(Module &M, 430 ModuleAnalysisManager &AM) { 431 ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M); 432 433 OS << "Functions in " << M.getName() << " with hot/cold annotations: \n"; 434 for (auto &F : M) { 435 OS << F.getName(); 436 if (PSI.isFunctionEntryHot(&F)) 437 OS << " :hot entry "; 438 else if (PSI.isFunctionEntryCold(&F)) 439 OS << " :cold entry "; 440 OS << "\n"; 441 } 442 return PreservedAnalyses::all(); 443 } 444 445 char ProfileSummaryInfoWrapperPass::ID = 0; 446