LLVM 22.0.0git
ProfileSummaryInfo.cpp
Go to the documentation of this file.
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
16#include "llvm/IR/BasicBlock.h"
18#include "llvm/IR/Module.h"
24#include <optional>
25using namespace llvm;
26
28 "partial-profile", cl::Hidden, cl::init(false),
29 cl::desc("Specify the current profile is used as a partial profile."));
30
32 "scale-partial-sample-profile-working-set-size", cl::Hidden, cl::init(true),
34 "If true, scale the working set size of the partial sample profile "
35 "by the partial profile ratio to reflect the size of the program "
36 "being compiled."));
37
39 "partial-sample-profile-working-set-size-scale-factor", cl::Hidden,
40 cl::init(0.008),
41 cl::desc("The scale factor used to scale the working set size of the "
42 "partial sample profile along with the partial profile ratio. "
43 "This includes the factor of the profile counter per block "
44 "and the factor to scale the working set size to use the same "
45 "shared thresholds as PGO."));
46
47// The profile summary metadata may be attached either by the frontend or by
48// any backend passes (IR level instrumentation, for example). This method
49// checks if the Summary is null and if so checks if the summary metadata is now
50// available in the module and parses it to get the Summary object.
51void ProfileSummaryInfo::refresh(std::unique_ptr<ProfileSummary> &&Other) {
52 if (Other) {
53 Summary.swap(Other);
54 return;
55 }
57 return;
58 // First try to get context sensitive ProfileSummary.
59 auto *SummaryMD = M->getProfileSummary(/* IsCS */ true);
60 if (SummaryMD)
61 Summary.reset(ProfileSummary::getFromMD(SummaryMD));
62
63 if (!hasProfileSummary()) {
64 // This will actually return PSK_Instr or PSK_Sample summary.
65 SummaryMD = M->getProfileSummary(/* IsCS */ false);
66 if (SummaryMD)
67 Summary.reset(ProfileSummary::getFromMD(SummaryMD));
68 }
69 if (!hasProfileSummary())
70 return;
71 computeThresholds();
72}
73
75 const CallBase &Call, BlockFrequencyInfo *BFI, bool AllowSynthetic) const {
76 assert((isa<CallInst>(Call) || isa<InvokeInst>(Call)) &&
77 "We can only get profile count for call/invoke instruction.");
78 if (hasSampleProfile()) {
79 // In sample PGO mode, check if there is a profile metadata on the
80 // instruction. If it is present, determine hotness solely based on that,
81 // since the sampled entry count may not be accurate. If there is no
82 // annotated on the instruction, return std::nullopt.
83 uint64_t TotalCount;
84 if (Call.extractProfTotalWeight(TotalCount))
85 return TotalCount;
86 return std::nullopt;
87 }
88 if (BFI)
89 return BFI->getBlockProfileCount(Call.getParent(), AllowSynthetic);
90 return std::nullopt;
91}
92
94 assert(hasPartialSampleProfile() && "Expect partial sample profile");
95 return !F.getEntryCount();
96}
97
98/// Returns true if the function's entry is a cold. If it returns false, it
99/// either means it is not cold or it is unknown whether it is cold or not (for
100/// example, no profile data is available).
102 if (!F)
103 return false;
104 if (F->hasFnAttribute(Attribute::Cold))
105 return true;
106 if (!hasProfileSummary())
107 return false;
108 auto FunctionCount = F->getEntryCount();
109 // FIXME: The heuristic used below for determining coldness is based on
110 // preliminary SPEC tuning for inliner. This will eventually be a
111 // convenience method that calls isHotCount.
112 return FunctionCount && isColdCount(FunctionCount->getCount());
113}
114
115/// Compute the hot and cold thresholds.
116void ProfileSummaryInfo::computeThresholds() {
117 auto &DetailedSummary = Summary->getDetailedSummary();
119 DetailedSummary, ProfileSummaryCutoffHot);
120 HotCountThreshold =
122 ColdCountThreshold =
124 // When the hot and cold thresholds are identical, we would classify
125 // a count value as both hot and cold since we are doing an inclusive check
126 // (see ::is{Hot|Cold}Count(). To avoid this undesirable overlap, ensure the
127 // thresholds are distinct.
128 if (HotCountThreshold == ColdCountThreshold) {
129 if (ColdCountThreshold > 0)
130 (*ColdCountThreshold)--;
131 else
132 (*HotCountThreshold)++;
133 }
134 assert(ColdCountThreshold < HotCountThreshold &&
135 "Cold count threshold should be less than hot count threshold!");
137 HasHugeWorkingSetSize =
139 HasLargeWorkingSetSize =
141 } else {
142 // Scale the working set size of the partial sample profile to reflect the
143 // size of the program being compiled.
144 double PartialProfileRatio = Summary->getPartialProfileRatio();
145 uint64_t ScaledHotEntryNumCounts =
146 static_cast<uint64_t>(HotEntry.NumCounts * PartialProfileRatio *
148 HasHugeWorkingSetSize =
149 ScaledHotEntryNumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
150 HasLargeWorkingSetSize =
151 ScaledHotEntryNumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
152 }
153}
154
155std::optional<uint64_t>
156ProfileSummaryInfo::computeThreshold(int PercentileCutoff) const {
157 if (!hasProfileSummary())
158 return std::nullopt;
159 auto [Iter, Inserted] = ThresholdCache.try_emplace(PercentileCutoff);
160 if (!Inserted)
161 return Iter->second;
162 auto &DetailedSummary = Summary->getDetailedSummary();
165 uint64_t CountThreshold = Entry.MinCount;
166 Iter->second = CountThreshold;
167 return CountThreshold;
168}
169
171 return HasHugeWorkingSetSize && *HasHugeWorkingSetSize;
172}
173
175 return HasLargeWorkingSetSize && *HasLargeWorkingSetSize;
176}
177
179 return HotCountThreshold && C >= *HotCountThreshold;
180}
181
183 return ColdCountThreshold && C <= *ColdCountThreshold;
184}
185
186template <bool isHot>
187bool ProfileSummaryInfo::isHotOrColdCountNthPercentile(int PercentileCutoff,
188 uint64_t C) const {
189 auto CountThreshold = computeThreshold(PercentileCutoff);
190 if (isHot)
191 return CountThreshold && C >= *CountThreshold;
192 else
193 return CountThreshold && C <= *CountThreshold;
194}
195
197 uint64_t C) const {
198 return isHotOrColdCountNthPercentile<true>(PercentileCutoff, C);
199}
200
202 uint64_t C) const {
203 return isHotOrColdCountNthPercentile<false>(PercentileCutoff, C);
204}
205
207 return HotCountThreshold.value_or(UINT64_MAX);
208}
209
211 return ColdCountThreshold.value_or(0);
212}
213
215 BlockFrequencyInfo *BFI) const {
216 auto C = getProfileCount(CB, BFI);
217 return C && isHotCount(*C);
218}
219
221 BlockFrequencyInfo *BFI) const {
222 auto C = getProfileCount(CB, BFI);
223 if (C)
224 return isColdCount(*C);
225
226 // In SamplePGO, if the caller has been sampled, and there is no profile
227 // annotated on the callsite, we consider the callsite as cold.
228 return hasSampleProfile() && CB.getCaller()->hasProfileData();
229}
230
232 return hasProfileSummary() &&
233 Summary->getKind() == ProfileSummary::PSK_Sample &&
234 (PartialProfile || Summary->isPartialProfile());
235}
236
238 "Profile summary info", false, true)
239
241 : ImmutablePass(ID) {}
242
244 PSI.reset(new ProfileSummaryInfo(M));
245 return false;
246}
247
249 PSI.reset();
250 return false;
251}
252
253AnalysisKey ProfileSummaryAnalysis::Key;
256 return ProfileSummaryInfo(M);
257}
258
262
263 OS << "Functions in " << M.getName() << " with hot/cold annotations: \n";
264 for (auto &F : M) {
265 OS << F.getName();
266 if (PSI.isFunctionEntryHot(&F))
267 OS << " :hot entry ";
268 else if (PSI.isFunctionEntryCold(&F))
269 OS << " :cold entry ";
270 OS << "\n";
271 }
272 return PreservedAnalyses::all();
273}
274
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition: Compiler.h:213
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1328
static cl::opt< unsigned > CountThreshold("hexagon-cext-threshold", cl::init(3), cl::Hidden, cl::desc("Minimum number of extenders to trigger replacement"))
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition: MD5.cpp:55
static cl::opt< unsigned > PercentileCutoff("mfs-psi-cutoff", cl::desc("Percentile profile summary cutoff used to " "determine cold blocks. Unused if set to zero."), cl::init(999950), cl::Hidden)
LLVM_ABI cl::opt< bool > ScalePartialSampleProfileWorkingSetSize
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:56
static cl::opt< bool > PartialProfile("partial-profile", cl::Hidden, cl::init(false), cl::desc("Specify the current profile is used as a partial profile."))
static cl::opt< double > PartialSampleProfileWorkingSetSizeScaleFactor("partial-sample-profile-working-set-size-scale-factor", cl::Hidden, cl::init(0.008), cl::desc("The scale factor used to scale the working set size of the " "partial sample profile along with the partial profile ratio. " "This includes the factor of the profile counter per block " "and the factor to scale the working set size to use the same " "shared thresholds as PGO."))
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:412
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1116
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition: DenseMap.h:245
bool hasProfileData(bool IncludeSynthetic=false) const
Return true if the function is annotated with profile data.
Definition: Function.h:334
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition: Pass.h:285
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
Metadata * getProfileSummary(bool IsCS) const
Returns profile summary metadata.
Definition: Module.cpp:687
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:118
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &)
static LLVM_ABI const ProfileSummaryEntry & getEntryForPercentile(const SummaryEntryVector &DS, uint64_t Percentile)
Find the summary entry for a desired percentile of counts.
static LLVM_ABI uint64_t getHotCountThreshold(const SummaryEntryVector &DS)
static LLVM_ABI uint64_t getColdCountThreshold(const SummaryEntryVector &DS)
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
bool doFinalization(Module &M) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
bool doInitialization(Module &M) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
Analysis providing profile information.
LLVM_ABI uint64_t getOrCompColdCountThreshold() const
Returns ColdCountThreshold if set.
bool hasProfileSummary() const
Returns true if profile summary is available.
LLVM_ABI bool isFunctionHotnessUnknown(const Function &F) const
Returns true if the hotness of F is unknown.
LLVM_ABI std::optional< uint64_t > getProfileCount(const CallBase &CallInst, BlockFrequencyInfo *BFI, bool AllowSynthetic=false) const
Returns the profile count for CallInst.
bool hasSampleProfile() const
Returns true if module M has sample profile.
bool isFunctionEntryHot(const FuncT *F) const
Returns true if F has hot function entry.
LLVM_ABI bool isColdCount(uint64_t C) const
Returns true if count C is considered cold.
LLVM_ABI bool isColdCountNthPercentile(int PercentileCutoff, uint64_t C) const
Returns true if count C is considered cold with regard to a given cold percentile cutoff value.
LLVM_ABI void refresh(std::unique_ptr< ProfileSummary > &&Other=nullptr)
If a summary is provided as argument, use that.
LLVM_ABI bool isHotCountNthPercentile(int PercentileCutoff, uint64_t C) const
Returns true if count C is considered hot with regard to a given hot percentile cutoff value.
LLVM_ABI bool hasPartialSampleProfile() const
Returns true if module M has partial-profile sample profile.
LLVM_ABI bool hasLargeWorkingSetSize() const
Returns true if the working set size of the code is considered large.
LLVM_ABI bool isColdCallSite(const CallBase &CB, BlockFrequencyInfo *BFI) const
Returns true if call site CB is considered cold.
LLVM_ABI bool isHotCallSite(const CallBase &CB, BlockFrequencyInfo *BFI) const
Returns true if the call site CB is considered hot.
LLVM_ABI bool isHotCount(uint64_t C) const
Returns true if count C is considered hot.
LLVM_ABI bool hasHugeWorkingSetSize() const
Returns true if the working set size of the code is considered huge.
LLVM_ABI uint64_t getOrCompHotCountThreshold() const
Returns HotCountThreshold if set.
LLVM_ABI bool isFunctionEntryCold(const Function *F) const
Returns true if F has cold function entry.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static LLVM_ABI ProfileSummary * getFromMD(Metadata *MD)
Construct profile summary from metdata.
#define UINT64_MAX
Definition: DataTypes.h:77
@ Entry
Definition: COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Other
Any other memory.
LLVM_ABI cl::opt< unsigned > ProfileSummaryLargeWorkingSetSizeThreshold
LLVM_ABI cl::opt< int > ProfileSummaryCutoffHot
LLVM_ABI cl::opt< unsigned > ProfileSummaryHugeWorkingSetSizeThreshold
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:29