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