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/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> ProfileSummaryInfo::getProfileCount(const CallBase &Call,
105                                                        BlockFrequencyInfo *BFI,
106                                                        bool AllowSynthetic) {
107   assert((isa<CallInst>(Call) || isa<InvokeInst>(Call)) &&
108          "We can only get profile count for call/invoke instruction.");
109   if (hasSampleProfile()) {
110     // In sample PGO mode, check if there is a profile metadata on the
111     // instruction. If it is present, determine hotness solely based on that,
112     // since the sampled entry count may not be accurate. If there is no
113     // annotated on the instruction, return None.
114     uint64_t TotalCount;
115     if (Call.extractProfTotalWeight(TotalCount))
116       return TotalCount;
117     return None;
118   }
119   if (BFI)
120     return BFI->getBlockProfileCount(Call.getParent(), AllowSynthetic);
121   return None;
122 }
123 
124 /// Returns true if the function's entry is hot. If it returns false, it
125 /// either means it is not hot or it is unknown whether it is hot or not (for
126 /// example, no profile data is available).
127 bool ProfileSummaryInfo::isFunctionEntryHot(const Function *F) {
128   if (!F || !computeSummary())
129     return false;
130   auto FunctionCount = F->getEntryCount();
131   // FIXME: The heuristic used below for determining hotness is based on
132   // preliminary SPEC tuning for inliner. This will eventually be a
133   // convenience method that calls isHotCount.
134   return FunctionCount && isHotCount(FunctionCount.getCount());
135 }
136 
137 /// Returns true if the function contains hot code. This can include a hot
138 /// function entry count, hot basic block, or (in the case of Sample PGO)
139 /// hot total call edge count.
140 /// If it returns false, it either means it is not hot or it is unknown
141 /// (for example, no profile data is available).
142 bool ProfileSummaryInfo::isFunctionHotInCallGraph(const Function *F,
143                                                   BlockFrequencyInfo &BFI) {
144   if (!F || !computeSummary())
145     return false;
146   if (auto FunctionCount = F->getEntryCount())
147     if (isHotCount(FunctionCount.getCount()))
148       return true;
149 
150   if (hasSampleProfile()) {
151     uint64_t TotalCallCount = 0;
152     for (const auto &BB : *F)
153       for (const auto &I : BB)
154         if (isa<CallInst>(I) || isa<InvokeInst>(I))
155           if (auto CallCount = getProfileCount(cast<CallBase>(I), nullptr))
156             TotalCallCount += CallCount.getValue();
157     if (isHotCount(TotalCallCount))
158       return true;
159   }
160   for (const auto &BB : *F)
161     if (isHotBlock(&BB, &BFI))
162       return true;
163   return false;
164 }
165 
166 /// Returns true if the function only contains cold code. This means that
167 /// the function entry and blocks are all cold, and (in the case of Sample PGO)
168 /// the total call edge count is cold.
169 /// If it returns false, it either means it is not cold or it is unknown
170 /// (for example, no profile data is available).
171 bool ProfileSummaryInfo::isFunctionColdInCallGraph(const Function *F,
172                                                    BlockFrequencyInfo &BFI) {
173   if (!F || !computeSummary())
174     return false;
175   if (auto FunctionCount = F->getEntryCount())
176     if (!isColdCount(FunctionCount.getCount()))
177       return false;
178 
179   if (hasSampleProfile()) {
180     uint64_t TotalCallCount = 0;
181     for (const auto &BB : *F)
182       for (const auto &I : BB)
183         if (isa<CallInst>(I) || isa<InvokeInst>(I))
184           if (auto CallCount = getProfileCount(cast<CallBase>(I), nullptr))
185             TotalCallCount += CallCount.getValue();
186     if (!isColdCount(TotalCallCount))
187       return false;
188   }
189   for (const auto &BB : *F)
190     if (!isColdBlock(&BB, &BFI))
191       return false;
192   return true;
193 }
194 
195 template<bool isHot>
196 bool ProfileSummaryInfo::isFunctionHotOrColdInCallGraphNthPercentile(
197     int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) {
198   if (!F || !computeSummary())
199     return false;
200   if (auto FunctionCount = F->getEntryCount()) {
201     if (isHot &&
202         isHotCountNthPercentile(PercentileCutoff, FunctionCount.getCount()))
203       return true;
204     if (!isHot &&
205         !isColdCountNthPercentile(PercentileCutoff, FunctionCount.getCount()))
206       return false;
207   }
208   if (hasSampleProfile()) {
209     uint64_t TotalCallCount = 0;
210     for (const auto &BB : *F)
211       for (const auto &I : BB)
212         if (isa<CallInst>(I) || isa<InvokeInst>(I))
213           if (auto CallCount = getProfileCount(cast<CallBase>(I), nullptr))
214             TotalCallCount += CallCount.getValue();
215     if (isHot && isHotCountNthPercentile(PercentileCutoff, TotalCallCount))
216       return true;
217     if (!isHot && !isColdCountNthPercentile(PercentileCutoff, TotalCallCount))
218       return false;
219   }
220   for (const auto &BB : *F) {
221     if (isHot && isHotBlockNthPercentile(PercentileCutoff, &BB, &BFI))
222       return true;
223     if (!isHot && !isColdBlockNthPercentile(PercentileCutoff, &BB, &BFI))
224       return false;
225   }
226   return !isHot;
227 }
228 
229 // Like isFunctionHotInCallGraph but for a given cutoff.
230 bool ProfileSummaryInfo::isFunctionHotInCallGraphNthPercentile(
231     int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) {
232   return isFunctionHotOrColdInCallGraphNthPercentile<true>(
233       PercentileCutoff, F, BFI);
234 }
235 
236 bool ProfileSummaryInfo::isFunctionColdInCallGraphNthPercentile(
237     int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) {
238   return isFunctionHotOrColdInCallGraphNthPercentile<false>(
239       PercentileCutoff, F, BFI);
240 }
241 
242 /// Returns true if the function's entry is a cold. If it returns false, it
243 /// either means it is not cold or it is unknown whether it is cold or not (for
244 /// example, no profile data is available).
245 bool ProfileSummaryInfo::isFunctionEntryCold(const Function *F) {
246   if (!F)
247     return false;
248   if (F->hasFnAttribute(Attribute::Cold))
249     return true;
250   if (!computeSummary())
251     return false;
252   auto FunctionCount = F->getEntryCount();
253   // FIXME: The heuristic used below for determining coldness is based on
254   // preliminary SPEC tuning for inliner. This will eventually be a
255   // convenience method that calls isHotCount.
256   return FunctionCount && isColdCount(FunctionCount.getCount());
257 }
258 
259 /// Compute the hot and cold thresholds.
260 void ProfileSummaryInfo::computeThresholds() {
261   if (!computeSummary())
262     return;
263   auto &DetailedSummary = Summary->getDetailedSummary();
264   auto &HotEntry =
265       getEntryForPercentile(DetailedSummary, ProfileSummaryCutoffHot);
266   HotCountThreshold = HotEntry.MinCount;
267   if (ProfileSummaryHotCount.getNumOccurrences() > 0)
268     HotCountThreshold = ProfileSummaryHotCount;
269   auto &ColdEntry =
270       getEntryForPercentile(DetailedSummary, ProfileSummaryCutoffCold);
271   ColdCountThreshold = ColdEntry.MinCount;
272   if (ProfileSummaryColdCount.getNumOccurrences() > 0)
273     ColdCountThreshold = ProfileSummaryColdCount;
274   assert(ColdCountThreshold <= HotCountThreshold &&
275          "Cold count threshold cannot exceed hot count threshold!");
276   HasHugeWorkingSetSize =
277       HotEntry.NumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
278   HasLargeWorkingSetSize =
279       HotEntry.NumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
280 }
281 
282 Optional<uint64_t> ProfileSummaryInfo::computeThreshold(int PercentileCutoff) {
283   if (!computeSummary())
284     return None;
285   auto iter = ThresholdCache.find(PercentileCutoff);
286   if (iter != ThresholdCache.end()) {
287     return iter->second;
288   }
289   auto &DetailedSummary = Summary->getDetailedSummary();
290   auto &Entry =
291       getEntryForPercentile(DetailedSummary, PercentileCutoff);
292   uint64_t CountThreshold = Entry.MinCount;
293   ThresholdCache[PercentileCutoff] = CountThreshold;
294   return CountThreshold;
295 }
296 
297 bool ProfileSummaryInfo::hasHugeWorkingSetSize() {
298   if (!HasHugeWorkingSetSize)
299     computeThresholds();
300   return HasHugeWorkingSetSize && HasHugeWorkingSetSize.getValue();
301 }
302 
303 bool ProfileSummaryInfo::hasLargeWorkingSetSize() {
304   if (!HasLargeWorkingSetSize)
305     computeThresholds();
306   return HasLargeWorkingSetSize && HasLargeWorkingSetSize.getValue();
307 }
308 
309 bool ProfileSummaryInfo::isHotCount(uint64_t C) {
310   if (!HotCountThreshold)
311     computeThresholds();
312   return HotCountThreshold && C >= HotCountThreshold.getValue();
313 }
314 
315 bool ProfileSummaryInfo::isColdCount(uint64_t C) {
316   if (!ColdCountThreshold)
317     computeThresholds();
318   return ColdCountThreshold && C <= ColdCountThreshold.getValue();
319 }
320 
321 template<bool isHot>
322 bool ProfileSummaryInfo::isHotOrColdCountNthPercentile(int PercentileCutoff,
323                                                        uint64_t C) {
324   auto CountThreshold = computeThreshold(PercentileCutoff);
325   if (isHot)
326     return CountThreshold && C >= CountThreshold.getValue();
327   else
328     return CountThreshold && C <= CountThreshold.getValue();
329 }
330 
331 bool ProfileSummaryInfo::isHotCountNthPercentile(int PercentileCutoff, uint64_t C) {
332   return isHotOrColdCountNthPercentile<true>(PercentileCutoff, C);
333 }
334 
335 bool ProfileSummaryInfo::isColdCountNthPercentile(int PercentileCutoff, uint64_t C) {
336   return isHotOrColdCountNthPercentile<false>(PercentileCutoff, C);
337 }
338 
339 uint64_t ProfileSummaryInfo::getOrCompHotCountThreshold() {
340   if (!HotCountThreshold)
341     computeThresholds();
342   return HotCountThreshold ? HotCountThreshold.getValue() : UINT64_MAX;
343 }
344 
345 uint64_t ProfileSummaryInfo::getOrCompColdCountThreshold() {
346   if (!ColdCountThreshold)
347     computeThresholds();
348   return ColdCountThreshold ? ColdCountThreshold.getValue() : 0;
349 }
350 
351 bool ProfileSummaryInfo::isHotBlock(const BasicBlock *BB, BlockFrequencyInfo *BFI) {
352   auto Count = BFI->getBlockProfileCount(BB);
353   return Count && isHotCount(*Count);
354 }
355 
356 bool ProfileSummaryInfo::isColdBlock(const BasicBlock *BB,
357                                   BlockFrequencyInfo *BFI) {
358   auto Count = BFI->getBlockProfileCount(BB);
359   return Count && isColdCount(*Count);
360 }
361 
362 template<bool isHot>
363 bool ProfileSummaryInfo::isHotOrColdBlockNthPercentile(int PercentileCutoff,
364                                                        const BasicBlock *BB,
365                                                        BlockFrequencyInfo *BFI) {
366   auto Count = BFI->getBlockProfileCount(BB);
367   if (isHot)
368     return Count && isHotCountNthPercentile(PercentileCutoff, *Count);
369   else
370     return Count && isColdCountNthPercentile(PercentileCutoff, *Count);
371 }
372 
373 bool ProfileSummaryInfo::isHotBlockNthPercentile(int PercentileCutoff,
374                                                  const BasicBlock *BB,
375                                                  BlockFrequencyInfo *BFI) {
376   return isHotOrColdBlockNthPercentile<true>(PercentileCutoff, BB, BFI);
377 }
378 
379 bool ProfileSummaryInfo::isColdBlockNthPercentile(int PercentileCutoff,
380                                                   const BasicBlock *BB,
381                                                   BlockFrequencyInfo *BFI) {
382   return isHotOrColdBlockNthPercentile<false>(PercentileCutoff, BB, BFI);
383 }
384 
385 bool ProfileSummaryInfo::isHotCallSite(const CallBase &CB,
386                                        BlockFrequencyInfo *BFI) {
387   auto C = getProfileCount(CB, BFI);
388   return C && isHotCount(*C);
389 }
390 
391 bool ProfileSummaryInfo::isColdCallSite(const CallBase &CB,
392                                         BlockFrequencyInfo *BFI) {
393   auto C = getProfileCount(CB, BFI);
394   if (C)
395     return isColdCount(*C);
396 
397   // In SamplePGO, if the caller has been sampled, and there is no profile
398   // annotated on the callsite, we consider the callsite as cold.
399   return hasSampleProfile() && CB.getCaller()->hasProfileData();
400 }
401 
402 INITIALIZE_PASS(ProfileSummaryInfoWrapperPass, "profile-summary-info",
403                 "Profile summary info", false, true)
404 
405 ProfileSummaryInfoWrapperPass::ProfileSummaryInfoWrapperPass()
406     : ImmutablePass(ID) {
407   initializeProfileSummaryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
408 }
409 
410 bool ProfileSummaryInfoWrapperPass::doInitialization(Module &M) {
411   PSI.reset(new ProfileSummaryInfo(M));
412   return false;
413 }
414 
415 bool ProfileSummaryInfoWrapperPass::doFinalization(Module &M) {
416   PSI.reset();
417   return false;
418 }
419 
420 AnalysisKey ProfileSummaryAnalysis::Key;
421 ProfileSummaryInfo ProfileSummaryAnalysis::run(Module &M,
422                                                ModuleAnalysisManager &) {
423   return ProfileSummaryInfo(M);
424 }
425 
426 PreservedAnalyses ProfileSummaryPrinterPass::run(Module &M,
427                                                  ModuleAnalysisManager &AM) {
428   ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
429 
430   OS << "Functions in " << M.getName() << " with hot/cold annotations: \n";
431   for (auto &F : M) {
432     OS << F.getName();
433     if (PSI.isFunctionEntryHot(&F))
434       OS << " :hot entry ";
435     else if (PSI.isFunctionEntryCold(&F))
436       OS << " :cold entry ";
437     OS << "\n";
438   }
439   return PreservedAnalyses::all();
440 }
441 
442 char ProfileSummaryInfoWrapperPass::ID = 0;
443