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 "llvm/Support/Compiler.h"
24#include <optional>
25using namespace llvm;
26
27namespace llvm {
28
29static cl::opt<bool> PartialProfile(
30 "partial-profile", cl::Hidden, cl::init(Val: false),
31 cl::desc("Specify the current profile is used as a partial profile."));
32
33LLVM_ABI cl::opt<bool> ScalePartialSampleProfileWorkingSetSize(
34 "scale-partial-sample-profile-working-set-size", cl::Hidden, cl::init(Val: true),
35 cl::desc(
36 "If true, scale the working set size of the partial sample profile "
37 "by the partial profile ratio to reflect the size of the program "
38 "being compiled."));
39
40static cl::opt<double> PartialSampleProfileWorkingSetSizeScaleFactor(
41 "partial-sample-profile-working-set-size-scale-factor", cl::Hidden,
42 cl::init(Val: 0.008),
43 cl::desc("The scale factor used to scale the working set size of the "
44 "partial sample profile along with the partial profile ratio. "
45 "This includes the factor of the profile counter per block "
46 "and the factor to scale the working set size to use the same "
47 "shared thresholds as PGO."));
48
49} // end namespace llvm
50
51// The profile summary metadata may be attached either by the frontend or by
52// any backend passes (IR level instrumentation, for example). This method
53// checks if the Summary is null and if so checks if the summary metadata is now
54// available in the module and parses it to get the Summary object.
55void ProfileSummaryInfo::refresh(std::unique_ptr<ProfileSummary> &&Other) {
56 if (Other) {
57 Summary.swap(u&: Other);
58 return;
59 }
60 if (hasProfileSummary())
61 return;
62 // First try to get context sensitive ProfileSummary.
63 auto *SummaryMD = M->getProfileSummary(/* IsCS */ true);
64 if (SummaryMD)
65 Summary.reset(p: ProfileSummary::getFromMD(MD: SummaryMD));
66
67 if (!hasProfileSummary()) {
68 // This will actually return PSK_Instr or PSK_Sample summary.
69 SummaryMD = M->getProfileSummary(/* IsCS */ false);
70 if (SummaryMD)
71 Summary.reset(p: ProfileSummary::getFromMD(MD: SummaryMD));
72 }
73 if (!hasProfileSummary())
74 return;
75 computeThresholds();
76}
77
78std::optional<uint64_t>
79ProfileSummaryInfo::getProfileCount(const CallBase &Call,
80 BlockFrequencyInfo *BFI) 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(TotalVal&: TotalCount))
90 return TotalCount;
91 return std::nullopt;
92 }
93 if (BFI)
94 return BFI->getBlockProfileCount(BB: Call.getParent());
95 return std::nullopt;
96}
97
98bool ProfileSummaryInfo::isFunctionHotnessUnknown(const Function &F) const {
99 assert(hasPartialSampleProfile() && "Expect partial sample profile");
100 return !F.getEntryCount();
101}
102
103/// Returns true if the function's entry is a cold. If it returns false, it
104/// either means it is not cold or it is unknown whether it is cold or not (for
105/// example, no profile data is available).
106bool ProfileSummaryInfo::isFunctionEntryCold(const Function *F) const {
107 if (!F)
108 return false;
109 // The hot attribute is a manual alternative to profile data, and takes
110 // precedence over it.
111 if (hasHotAttr(F))
112 return false;
113 if (F->hasFnAttribute(Kind: Attribute::Cold))
114 return true;
115 if (!hasProfileSummary())
116 return false;
117 auto FunctionCount = F->getEntryCount();
118 // FIXME: The heuristic used below for determining coldness is based on
119 // preliminary SPEC tuning for inliner. This will eventually be a
120 // convenience method that calls isHotCount.
121 return FunctionCount && isColdCount(C: *FunctionCount);
122}
123
124/// Compute the hot and cold thresholds.
125void ProfileSummaryInfo::computeThresholds() {
126 auto &DetailedSummary = Summary->getDetailedSummary();
127 auto &HotEntry = ProfileSummaryBuilder::getEntryForPercentile(
128 DS: DetailedSummary, Percentile: ProfileSummaryCutoffHot);
129 HotCountThreshold =
130 ProfileSummaryBuilder::getHotCountThreshold(DS: DetailedSummary);
131 ColdCountThreshold =
132 ProfileSummaryBuilder::getColdCountThreshold(DS: DetailedSummary);
133 // When the hot and cold thresholds are identical, we would classify
134 // a count value as both hot and cold since we are doing an inclusive check
135 // (see ::is{Hot|Cold}Count(). To avoid this undesirable overlap, ensure the
136 // thresholds are distinct.
137 if (HotCountThreshold == ColdCountThreshold) {
138 if (ColdCountThreshold > 0)
139 (*ColdCountThreshold)--;
140 else
141 (*HotCountThreshold)++;
142 }
143 assert(ColdCountThreshold < HotCountThreshold &&
144 "Cold count threshold should be less than hot count threshold!");
145 if (!hasPartialSampleProfile() || !ScalePartialSampleProfileWorkingSetSize) {
146 HasHugeWorkingSetSize =
147 HotEntry.NumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
148 HasLargeWorkingSetSize =
149 HotEntry.NumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
150 } else {
151 // Scale the working set size of the partial sample profile to reflect the
152 // size of the program being compiled.
153 double PartialProfileRatio = Summary->getPartialProfileRatio();
154 uint64_t ScaledHotEntryNumCounts =
155 static_cast<uint64_t>(HotEntry.NumCounts * PartialProfileRatio *
156 PartialSampleProfileWorkingSetSizeScaleFactor);
157 HasHugeWorkingSetSize =
158 ScaledHotEntryNumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
159 HasLargeWorkingSetSize =
160 ScaledHotEntryNumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
161 }
162}
163
164std::optional<uint64_t>
165ProfileSummaryInfo::computeThreshold(int PercentileCutoff) const {
166 if (!hasProfileSummary())
167 return std::nullopt;
168 auto [Iter, Inserted] = ThresholdCache.try_emplace(Key: PercentileCutoff);
169 if (!Inserted)
170 return Iter->second;
171 auto &DetailedSummary = Summary->getDetailedSummary();
172 auto &Entry = ProfileSummaryBuilder::getEntryForPercentile(DS: DetailedSummary,
173 Percentile: PercentileCutoff);
174 uint64_t CountThreshold = Entry.MinCount;
175 Iter->second = CountThreshold;
176 return CountThreshold;
177}
178
179bool ProfileSummaryInfo::hasHugeWorkingSetSize() const {
180 return HasHugeWorkingSetSize && *HasHugeWorkingSetSize;
181}
182
183bool ProfileSummaryInfo::hasLargeWorkingSetSize() const {
184 return HasLargeWorkingSetSize && *HasLargeWorkingSetSize;
185}
186
187bool ProfileSummaryInfo::isHotCount(uint64_t C) const {
188 return HotCountThreshold && C >= *HotCountThreshold;
189}
190
191bool ProfileSummaryInfo::isColdCount(uint64_t C) const {
192 return ColdCountThreshold && C <= *ColdCountThreshold;
193}
194
195template <bool isHot>
196bool ProfileSummaryInfo::isHotOrColdCountNthPercentile(int PercentileCutoff,
197 uint64_t C) const {
198 auto CountThreshold = computeThreshold(PercentileCutoff);
199 if (isHot)
200 return CountThreshold && C >= *CountThreshold;
201 else
202 return CountThreshold && C <= *CountThreshold;
203}
204
205bool ProfileSummaryInfo::isHotCountNthPercentile(int PercentileCutoff,
206 uint64_t C) const {
207 return isHotOrColdCountNthPercentile<true>(PercentileCutoff, C);
208}
209
210bool ProfileSummaryInfo::isColdCountNthPercentile(int PercentileCutoff,
211 uint64_t C) const {
212 return isHotOrColdCountNthPercentile<false>(PercentileCutoff, C);
213}
214
215uint64_t ProfileSummaryInfo::getOrCompHotCountThreshold() const {
216 return HotCountThreshold.value_or(UINT64_MAX);
217}
218
219uint64_t ProfileSummaryInfo::getOrCompColdCountThreshold() const {
220 return ColdCountThreshold.value_or(u: 0);
221}
222
223bool ProfileSummaryInfo::isHotCallSite(const CallBase &CB,
224 BlockFrequencyInfo *BFI) const {
225 auto C = getProfileCount(Call: CB, BFI);
226 return C && isHotCount(C: *C);
227}
228
229bool ProfileSummaryInfo::isColdCallSite(const CallBase &CB,
230 BlockFrequencyInfo *BFI) const {
231 auto C = getProfileCount(Call: CB, BFI);
232 if (C)
233 return isColdCount(C: *C);
234
235 // In SamplePGO, if the caller has been sampled, and there is no profile
236 // annotated on the callsite, we consider the callsite as cold.
237 return hasSampleProfile() && CB.getCaller()->hasProfileData();
238}
239
240bool ProfileSummaryInfo::hasPartialSampleProfile() const {
241 return hasProfileSummary() &&
242 Summary->getKind() == ProfileSummary::PSK_Sample &&
243 (PartialProfile || Summary->isPartialProfile());
244}
245
246INITIALIZE_PASS(ProfileSummaryInfoWrapperPass, "profile-summary-info",
247 "Profile summary info", false, true)
248
249ProfileSummaryInfoWrapperPass::ProfileSummaryInfoWrapperPass()
250 : ImmutablePass(ID) {}
251
252bool ProfileSummaryInfoWrapperPass::doInitialization(Module &M) {
253 PSI.reset(p: new ProfileSummaryInfo(M));
254 return false;
255}
256
257bool ProfileSummaryInfoWrapperPass::doFinalization(Module &M) {
258 PSI.reset();
259 return false;
260}
261
262AnalysisKey ProfileSummaryAnalysis::Key;
263ProfileSummaryInfo ProfileSummaryAnalysis::run(Module &M,
264 ModuleAnalysisManager &) {
265 return ProfileSummaryInfo(M);
266}
267
268PreservedAnalyses ProfileSummaryPrinterPass::run(Module &M,
269 ModuleAnalysisManager &AM) {
270 ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(IR&: M);
271
272 OS << "Functions in " << M.getName() << " with hot/cold annotations: \n";
273 for (auto &F : M) {
274 OS << F.getName();
275 if (PSI.isFunctionEntryHot(F: &F))
276 OS << " :hot entry ";
277 else if (PSI.isFunctionEntryCold(F: &F))
278 OS << " :cold entry ";
279 OS << "\n";
280 }
281 return PreservedAnalyses::all();
282}
283
284char ProfileSummaryInfoWrapperPass::ID = 0;
285