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/Module.h"
19 #include "llvm/IR/ProfileSummary.h"
20 #include "llvm/InitializePasses.h"
21 #include "llvm/ProfileData/ProfileCommon.h"
22 #include "llvm/Support/CommandLine.h"
23 #include <optional>
24 using namespace llvm;
25 
26 // Knobs for profile summary based thresholds.
27 namespace llvm {
28 extern cl::opt<int> ProfileSummaryCutoffHot;
29 extern cl::opt<int> ProfileSummaryCutoffCold;
30 extern cl::opt<unsigned> ProfileSummaryHugeWorkingSetSizeThreshold;
31 extern cl::opt<unsigned> ProfileSummaryLargeWorkingSetSizeThreshold;
32 extern cl::opt<int> ProfileSummaryHotCount;
33 extern cl::opt<int> ProfileSummaryColdCount;
34 } // namespace llvm
35 
36 static cl::opt<bool> PartialProfile(
37     "partial-profile", cl::Hidden, cl::init(false),
38     cl::desc("Specify the current profile is used as a partial profile."));
39 
40 cl::opt<bool> ScalePartialSampleProfileWorkingSetSize(
41     "scale-partial-sample-profile-working-set-size", cl::Hidden, cl::init(true),
42     cl::desc(
43         "If true, scale the working set size of the partial sample profile "
44         "by the partial profile ratio to reflect the size of the program "
45         "being compiled."));
46 
47 static cl::opt<double> PartialSampleProfileWorkingSetSizeScaleFactor(
48     "partial-sample-profile-working-set-size-scale-factor", cl::Hidden,
49     cl::init(0.008),
50     cl::desc("The scale factor used to scale the working set size of the "
51              "partial sample profile along with the partial profile ratio. "
52              "This includes the factor of the profile counter per block "
53              "and the factor to scale the working set size to use the same "
54              "shared thresholds as PGO."));
55 
56 // The profile summary metadata may be attached either by the frontend or by
57 // any backend passes (IR level instrumentation, for example). This method
58 // checks if the Summary is null and if so checks if the summary metadata is now
59 // available in the module and parses it to get the Summary object.
refresh()60 void ProfileSummaryInfo::refresh() {
61   if (hasProfileSummary())
62     return;
63   // First try to get context sensitive ProfileSummary.
64   auto *SummaryMD = M->getProfileSummary(/* IsCS */ true);
65   if (SummaryMD)
66     Summary.reset(ProfileSummary::getFromMD(SummaryMD));
67 
68   if (!hasProfileSummary()) {
69     // This will actually return PSK_Instr or PSK_Sample summary.
70     SummaryMD = M->getProfileSummary(/* IsCS */ false);
71     if (SummaryMD)
72       Summary.reset(ProfileSummary::getFromMD(SummaryMD));
73   }
74   if (!hasProfileSummary())
75     return;
76   computeThresholds();
77 }
78 
getProfileCount(const CallBase & Call,BlockFrequencyInfo * BFI,bool AllowSynthetic) const79 std::optional<uint64_t> ProfileSummaryInfo::getProfileCount(
80     const CallBase &Call, BlockFrequencyInfo *BFI, bool AllowSynthetic) const {
81   assert((isa<CallInst>(Call) || isa<InvokeInst>(Call)) &&
82          "We can only get profile count for call/invoke instruction.");
83   if (hasSampleProfile()) {
84     // In sample PGO mode, check if there is a profile metadata on the
85     // instruction. If it is present, determine hotness solely based on that,
86     // since the sampled entry count may not be accurate. If there is no
87     // annotated on the instruction, return std::nullopt.
88     uint64_t TotalCount;
89     if (Call.extractProfTotalWeight(TotalCount))
90       return TotalCount;
91     return std::nullopt;
92   }
93   if (BFI)
94     return BFI->getBlockProfileCount(Call.getParent(), AllowSynthetic);
95   return std::nullopt;
96 }
97 
98 /// Returns true if the function's entry is hot. If it returns false, it
99 /// either means it is not hot or it is unknown whether it is hot or not (for
100 /// example, no profile data is available).
isFunctionEntryHot(const Function * F) const101 bool ProfileSummaryInfo::isFunctionEntryHot(const Function *F) const {
102   if (!F || !hasProfileSummary())
103     return false;
104   auto FunctionCount = F->getEntryCount();
105   // FIXME: The heuristic used below for determining hotness is based on
106   // preliminary SPEC tuning for inliner. This will eventually be a
107   // convenience method that calls isHotCount.
108   return FunctionCount && isHotCount(FunctionCount->getCount());
109 }
110 
111 /// Returns true if the function contains hot code. This can include a hot
112 /// function entry count, hot basic block, or (in the case of Sample PGO)
113 /// hot total call edge count.
114 /// If it returns false, it either means it is not hot or it is unknown
115 /// (for example, no profile data is available).
isFunctionHotInCallGraph(const Function * F,BlockFrequencyInfo & BFI) const116 bool ProfileSummaryInfo::isFunctionHotInCallGraph(
117     const Function *F, BlockFrequencyInfo &BFI) const {
118   if (!F || !hasProfileSummary())
119     return false;
120   if (auto FunctionCount = F->getEntryCount())
121     if (isHotCount(FunctionCount->getCount()))
122       return true;
123 
124   if (hasSampleProfile()) {
125     uint64_t TotalCallCount = 0;
126     for (const auto &BB : *F)
127       for (const auto &I : BB)
128         if (isa<CallInst>(I) || isa<InvokeInst>(I))
129           if (auto CallCount = getProfileCount(cast<CallBase>(I), nullptr))
130             TotalCallCount += *CallCount;
131     if (isHotCount(TotalCallCount))
132       return true;
133   }
134   for (const auto &BB : *F)
135     if (isHotBlock(&BB, &BFI))
136       return true;
137   return false;
138 }
139 
140 /// Returns true if the function only contains cold code. This means that
141 /// the function entry and blocks are all cold, and (in the case of Sample PGO)
142 /// the total call edge count is cold.
143 /// If it returns false, it either means it is not cold or it is unknown
144 /// (for example, no profile data is available).
isFunctionColdInCallGraph(const Function * F,BlockFrequencyInfo & BFI) const145 bool ProfileSummaryInfo::isFunctionColdInCallGraph(
146     const Function *F, BlockFrequencyInfo &BFI) const {
147   if (!F || !hasProfileSummary())
148     return false;
149   if (auto FunctionCount = F->getEntryCount())
150     if (!isColdCount(FunctionCount->getCount()))
151       return false;
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(cast<CallBase>(I), nullptr))
159             TotalCallCount += *CallCount;
160     if (!isColdCount(TotalCallCount))
161       return false;
162   }
163   for (const auto &BB : *F)
164     if (!isColdBlock(&BB, &BFI))
165       return false;
166   return true;
167 }
168 
isFunctionHotnessUnknown(const Function & F) const169 bool ProfileSummaryInfo::isFunctionHotnessUnknown(const Function &F) const {
170   assert(hasPartialSampleProfile() && "Expect partial sample profile");
171   return !F.getEntryCount();
172 }
173 
174 template <bool isHot>
isFunctionHotOrColdInCallGraphNthPercentile(int PercentileCutoff,const Function * F,BlockFrequencyInfo & BFI) const175 bool ProfileSummaryInfo::isFunctionHotOrColdInCallGraphNthPercentile(
176     int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) const {
177   if (!F || !hasProfileSummary())
178     return false;
179   if (auto FunctionCount = F->getEntryCount()) {
180     if (isHot &&
181         isHotCountNthPercentile(PercentileCutoff, FunctionCount->getCount()))
182       return true;
183     if (!isHot &&
184         !isColdCountNthPercentile(PercentileCutoff, 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;
194     if (isHot && isHotCountNthPercentile(PercentileCutoff, TotalCallCount))
195       return true;
196     if (!isHot && !isColdCountNthPercentile(PercentileCutoff, TotalCallCount))
197       return false;
198   }
199   for (const auto &BB : *F) {
200     if (isHot && isHotBlockNthPercentile(PercentileCutoff, &BB, &BFI))
201       return true;
202     if (!isHot && !isColdBlockNthPercentile(PercentileCutoff, &BB, &BFI))
203       return false;
204   }
205   return !isHot;
206 }
207 
208 // Like isFunctionHotInCallGraph but for a given cutoff.
isFunctionHotInCallGraphNthPercentile(int PercentileCutoff,const Function * F,BlockFrequencyInfo & BFI) const209 bool ProfileSummaryInfo::isFunctionHotInCallGraphNthPercentile(
210     int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) const {
211   return isFunctionHotOrColdInCallGraphNthPercentile<true>(
212       PercentileCutoff, F, BFI);
213 }
214 
isFunctionColdInCallGraphNthPercentile(int PercentileCutoff,const Function * F,BlockFrequencyInfo & BFI) const215 bool ProfileSummaryInfo::isFunctionColdInCallGraphNthPercentile(
216     int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) const {
217   return isFunctionHotOrColdInCallGraphNthPercentile<false>(
218       PercentileCutoff, F, BFI);
219 }
220 
221 /// Returns true if the function's entry is a cold. If it returns false, it
222 /// either means it is not cold or it is unknown whether it is cold or not (for
223 /// example, no profile data is available).
isFunctionEntryCold(const Function * F) const224 bool ProfileSummaryInfo::isFunctionEntryCold(const Function *F) const {
225   if (!F)
226     return false;
227   if (F->hasFnAttribute(Attribute::Cold))
228     return true;
229   if (!hasProfileSummary())
230     return false;
231   auto FunctionCount = F->getEntryCount();
232   // FIXME: The heuristic used below for determining coldness is based on
233   // preliminary SPEC tuning for inliner. This will eventually be a
234   // convenience method that calls isHotCount.
235   return FunctionCount && isColdCount(FunctionCount->getCount());
236 }
237 
238 /// Compute the hot and cold thresholds.
computeThresholds()239 void ProfileSummaryInfo::computeThresholds() {
240   auto &DetailedSummary = Summary->getDetailedSummary();
241   auto &HotEntry = ProfileSummaryBuilder::getEntryForPercentile(
242       DetailedSummary, ProfileSummaryCutoffHot);
243   HotCountThreshold =
244       ProfileSummaryBuilder::getHotCountThreshold(DetailedSummary);
245   ColdCountThreshold =
246       ProfileSummaryBuilder::getColdCountThreshold(DetailedSummary);
247   assert(ColdCountThreshold <= HotCountThreshold &&
248          "Cold count threshold cannot exceed hot count threshold!");
249   if (!hasPartialSampleProfile() || !ScalePartialSampleProfileWorkingSetSize) {
250     HasHugeWorkingSetSize =
251         HotEntry.NumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
252     HasLargeWorkingSetSize =
253         HotEntry.NumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
254   } else {
255     // Scale the working set size of the partial sample profile to reflect the
256     // size of the program being compiled.
257     double PartialProfileRatio = Summary->getPartialProfileRatio();
258     uint64_t ScaledHotEntryNumCounts =
259         static_cast<uint64_t>(HotEntry.NumCounts * PartialProfileRatio *
260                               PartialSampleProfileWorkingSetSizeScaleFactor);
261     HasHugeWorkingSetSize =
262         ScaledHotEntryNumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
263     HasLargeWorkingSetSize =
264         ScaledHotEntryNumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
265   }
266 }
267 
268 std::optional<uint64_t>
computeThreshold(int PercentileCutoff) const269 ProfileSummaryInfo::computeThreshold(int PercentileCutoff) const {
270   if (!hasProfileSummary())
271     return std::nullopt;
272   auto iter = ThresholdCache.find(PercentileCutoff);
273   if (iter != ThresholdCache.end()) {
274     return iter->second;
275   }
276   auto &DetailedSummary = Summary->getDetailedSummary();
277   auto &Entry = ProfileSummaryBuilder::getEntryForPercentile(DetailedSummary,
278                                                              PercentileCutoff);
279   uint64_t CountThreshold = Entry.MinCount;
280   ThresholdCache[PercentileCutoff] = CountThreshold;
281   return CountThreshold;
282 }
283 
hasHugeWorkingSetSize() const284 bool ProfileSummaryInfo::hasHugeWorkingSetSize() const {
285   return HasHugeWorkingSetSize && *HasHugeWorkingSetSize;
286 }
287 
hasLargeWorkingSetSize() const288 bool ProfileSummaryInfo::hasLargeWorkingSetSize() const {
289   return HasLargeWorkingSetSize && *HasLargeWorkingSetSize;
290 }
291 
isHotCount(uint64_t C) const292 bool ProfileSummaryInfo::isHotCount(uint64_t C) const {
293   return HotCountThreshold && C >= *HotCountThreshold;
294 }
295 
isColdCount(uint64_t C) const296 bool ProfileSummaryInfo::isColdCount(uint64_t C) const {
297   return ColdCountThreshold && C <= *ColdCountThreshold;
298 }
299 
300 template <bool isHot>
isHotOrColdCountNthPercentile(int PercentileCutoff,uint64_t C) const301 bool ProfileSummaryInfo::isHotOrColdCountNthPercentile(int PercentileCutoff,
302                                                        uint64_t C) const {
303   auto CountThreshold = computeThreshold(PercentileCutoff);
304   if (isHot)
305     return CountThreshold && C >= *CountThreshold;
306   else
307     return CountThreshold && C <= *CountThreshold;
308 }
309 
isHotCountNthPercentile(int PercentileCutoff,uint64_t C) const310 bool ProfileSummaryInfo::isHotCountNthPercentile(int PercentileCutoff,
311                                                  uint64_t C) const {
312   return isHotOrColdCountNthPercentile<true>(PercentileCutoff, C);
313 }
314 
isColdCountNthPercentile(int PercentileCutoff,uint64_t C) const315 bool ProfileSummaryInfo::isColdCountNthPercentile(int PercentileCutoff,
316                                                   uint64_t C) const {
317   return isHotOrColdCountNthPercentile<false>(PercentileCutoff, C);
318 }
319 
getOrCompHotCountThreshold() const320 uint64_t ProfileSummaryInfo::getOrCompHotCountThreshold() const {
321   return HotCountThreshold.value_or(UINT64_MAX);
322 }
323 
getOrCompColdCountThreshold() const324 uint64_t ProfileSummaryInfo::getOrCompColdCountThreshold() const {
325   return ColdCountThreshold.value_or(0);
326 }
327 
isHotBlock(const BasicBlock * BB,BlockFrequencyInfo * BFI) const328 bool ProfileSummaryInfo::isHotBlock(const BasicBlock *BB,
329                                     BlockFrequencyInfo *BFI) const {
330   auto Count = BFI->getBlockProfileCount(BB);
331   return Count && isHotCount(*Count);
332 }
333 
isColdBlock(const BasicBlock * BB,BlockFrequencyInfo * BFI) const334 bool ProfileSummaryInfo::isColdBlock(const BasicBlock *BB,
335                                      BlockFrequencyInfo *BFI) const {
336   auto Count = BFI->getBlockProfileCount(BB);
337   return Count && isColdCount(*Count);
338 }
339 
340 template <bool isHot>
isHotOrColdBlockNthPercentile(int PercentileCutoff,const BasicBlock * BB,BlockFrequencyInfo * BFI) const341 bool ProfileSummaryInfo::isHotOrColdBlockNthPercentile(
342     int PercentileCutoff, const BasicBlock *BB, BlockFrequencyInfo *BFI) const {
343   auto Count = BFI->getBlockProfileCount(BB);
344   if (isHot)
345     return Count && isHotCountNthPercentile(PercentileCutoff, *Count);
346   else
347     return Count && isColdCountNthPercentile(PercentileCutoff, *Count);
348 }
349 
isHotBlockNthPercentile(int PercentileCutoff,const BasicBlock * BB,BlockFrequencyInfo * BFI) const350 bool ProfileSummaryInfo::isHotBlockNthPercentile(
351     int PercentileCutoff, const BasicBlock *BB, BlockFrequencyInfo *BFI) const {
352   return isHotOrColdBlockNthPercentile<true>(PercentileCutoff, BB, BFI);
353 }
354 
isColdBlockNthPercentile(int PercentileCutoff,const BasicBlock * BB,BlockFrequencyInfo * BFI) const355 bool ProfileSummaryInfo::isColdBlockNthPercentile(
356     int PercentileCutoff, const BasicBlock *BB, BlockFrequencyInfo *BFI) const {
357   return isHotOrColdBlockNthPercentile<false>(PercentileCutoff, BB, BFI);
358 }
359 
isHotCallSite(const CallBase & CB,BlockFrequencyInfo * BFI) const360 bool ProfileSummaryInfo::isHotCallSite(const CallBase &CB,
361                                        BlockFrequencyInfo *BFI) const {
362   auto C = getProfileCount(CB, BFI);
363   return C && isHotCount(*C);
364 }
365 
isColdCallSite(const CallBase & CB,BlockFrequencyInfo * BFI) const366 bool ProfileSummaryInfo::isColdCallSite(const CallBase &CB,
367                                         BlockFrequencyInfo *BFI) const {
368   auto C = getProfileCount(CB, BFI);
369   if (C)
370     return isColdCount(*C);
371 
372   // In SamplePGO, if the caller has been sampled, and there is no profile
373   // annotated on the callsite, we consider the callsite as cold.
374   return hasSampleProfile() && CB.getCaller()->hasProfileData();
375 }
376 
hasPartialSampleProfile() const377 bool ProfileSummaryInfo::hasPartialSampleProfile() const {
378   return hasProfileSummary() &&
379          Summary->getKind() == ProfileSummary::PSK_Sample &&
380          (PartialProfile || Summary->isPartialProfile());
381 }
382 
383 INITIALIZE_PASS(ProfileSummaryInfoWrapperPass, "profile-summary-info",
384                 "Profile summary info", false, true)
385 
ProfileSummaryInfoWrapperPass()386 ProfileSummaryInfoWrapperPass::ProfileSummaryInfoWrapperPass()
387     : ImmutablePass(ID) {
388   initializeProfileSummaryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
389 }
390 
doInitialization(Module & M)391 bool ProfileSummaryInfoWrapperPass::doInitialization(Module &M) {
392   PSI.reset(new ProfileSummaryInfo(M));
393   return false;
394 }
395 
doFinalization(Module & M)396 bool ProfileSummaryInfoWrapperPass::doFinalization(Module &M) {
397   PSI.reset();
398   return false;
399 }
400 
401 AnalysisKey ProfileSummaryAnalysis::Key;
run(Module & M,ModuleAnalysisManager &)402 ProfileSummaryInfo ProfileSummaryAnalysis::run(Module &M,
403                                                ModuleAnalysisManager &) {
404   return ProfileSummaryInfo(M);
405 }
406 
run(Module & M,ModuleAnalysisManager & AM)407 PreservedAnalyses ProfileSummaryPrinterPass::run(Module &M,
408                                                  ModuleAnalysisManager &AM) {
409   ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
410 
411   OS << "Functions in " << M.getName() << " with hot/cold annotations: \n";
412   for (auto &F : M) {
413     OS << F.getName();
414     if (PSI.isFunctionEntryHot(&F))
415       OS << " :hot entry ";
416     else if (PSI.isFunctionEntryCold(&F))
417       OS << " :cold entry ";
418     OS << "\n";
419   }
420   return PreservedAnalyses::all();
421 }
422 
423 char ProfileSummaryInfoWrapperPass::ID = 0;
424