LLVM  9.0.0svn
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"
17 #include "llvm/IR/CallSite.h"
18 #include "llvm/IR/Metadata.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/ProfileSummary.h"
21 using namespace llvm;
22 
23 // The following two parameters determine the threshold for a count to be
24 // considered hot/cold. These two parameters are percentile values (multiplied
25 // by 10000). If the counts are sorted in descending order, the minimum count to
26 // reach ProfileSummaryCutoffHot gives the threshold to determine a hot count.
27 // Similarly, the minimum count to reach ProfileSummaryCutoffCold gives the
28 // threshold for determining cold count (everything <= this threshold is
29 // considered cold).
30 
32  "profile-summary-cutoff-hot", cl::Hidden, cl::init(990000), cl::ZeroOrMore,
33  cl::desc("A count is hot if it exceeds the minimum count to"
34  " reach this percentile of total counts."));
35 
37  "profile-summary-cutoff-cold", cl::Hidden, cl::init(999999), cl::ZeroOrMore,
38  cl::desc("A count is cold if it is below the minimum count"
39  " to reach this percentile of total counts."));
40 
42  "profile-summary-huge-working-set-size-threshold", cl::Hidden,
43  cl::init(15000), cl::ZeroOrMore,
44  cl::desc("The code working set size is considered huge if the number of"
45  " blocks required to reach the -profile-summary-cutoff-hot"
46  " percentile exceeds this count."));
47 
48 // The next two options override the counts derived from summary computation and
49 // are useful for debugging purposes.
51  "profile-summary-hot-count", cl::ReallyHidden, cl::ZeroOrMore,
52  cl::desc("A fixed hot count that overrides the count derived from"
53  " profile-summary-cutoff-hot"));
54 
56  "profile-summary-cold-count", cl::ReallyHidden, cl::ZeroOrMore,
57  cl::desc("A fixed cold count that overrides the count derived from"
58  " profile-summary-cutoff-cold"));
59 
60 // Find the summary entry for a desired percentile of counts.
62  uint64_t Percentile) {
63  auto Compare = [](const ProfileSummaryEntry &Entry, uint64_t Percentile) {
64  return Entry.Cutoff < Percentile;
65  };
66  auto It = std::lower_bound(DS.begin(), DS.end(), Percentile, Compare);
67  // The required percentile has to be <= one of the percentiles in the
68  // detailed summary.
69  if (It == DS.end())
70  report_fatal_error("Desired percentile exceeds the maximum cutoff");
71  return *It;
72 }
73 
74 // The profile summary metadata may be attached either by the frontend or by
75 // any backend passes (IR level instrumentation, for example). This method
76 // checks if the Summary is null and if so checks if the summary metadata is now
77 // available in the module and parses it to get the Summary object. Returns true
78 // if a valid Summary is available.
79 bool ProfileSummaryInfo::computeSummary() {
80  if (Summary)
81  return true;
82  auto *SummaryMD = M.getProfileSummary();
83  if (!SummaryMD)
84  return false;
85  Summary.reset(ProfileSummary::getFromMD(SummaryMD));
86  return true;
87 }
88 
92  if (!Inst)
93  return None;
94  assert((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) &&
95  "We can only get profile count for call/invoke instruction.");
96  if (hasSampleProfile()) {
97  // In sample PGO mode, check if there is a profile metadata on the
98  // instruction. If it is present, determine hotness solely based on that,
99  // since the sampled entry count may not be accurate. If there is no
100  // annotated on the instruction, return None.
101  uint64_t TotalCount;
102  if (Inst->extractProfTotalWeight(TotalCount))
103  return TotalCount;
104  return None;
105  }
106  if (BFI)
107  return BFI->getBlockProfileCount(Inst->getParent());
108  return None;
109 }
110 
111 /// Returns true if the function's entry is hot. If it returns false, it
112 /// either means it is not hot or it is unknown whether it is hot or not (for
113 /// example, no profile data is available).
115  if (!F || !computeSummary())
116  return false;
117  auto FunctionCount = F->getEntryCount();
118  // FIXME: The heuristic used below for determining hotness is based on
119  // preliminary SPEC tuning for inliner. This will eventually be a
120  // convenience method that calls isHotCount.
121  return FunctionCount && isHotCount(FunctionCount.getCount());
122 }
123 
124 /// Returns true if the function contains hot code. This can include a hot
125 /// function entry count, hot basic block, or (in the case of Sample PGO)
126 /// hot total call edge count.
127 /// If it returns false, it either means it is not hot or it is unknown
128 /// (for example, no profile data is available).
131  if (!F || !computeSummary())
132  return false;
133  if (auto FunctionCount = F->getEntryCount())
134  if (isHotCount(FunctionCount.getCount()))
135  return true;
136 
137  if (hasSampleProfile()) {
138  uint64_t TotalCallCount = 0;
139  for (const auto &BB : *F)
140  for (const auto &I : BB)
141  if (isa<CallInst>(I) || isa<InvokeInst>(I))
142  if (auto CallCount = getProfileCount(&I, nullptr))
143  TotalCallCount += CallCount.getValue();
144  if (isHotCount(TotalCallCount))
145  return true;
146  }
147  for (const auto &BB : *F)
148  if (isHotBlock(&BB, &BFI))
149  return true;
150  return false;
151 }
152 
153 /// Returns true if the function only contains cold code. This means that
154 /// the function entry and blocks are all cold, and (in the case of Sample PGO)
155 /// the total call edge count is cold.
156 /// If it returns false, it either means it is not cold or it is unknown
157 /// (for example, no profile data is available).
160  if (!F || !computeSummary())
161  return false;
162  if (auto FunctionCount = F->getEntryCount())
163  if (!isColdCount(FunctionCount.getCount()))
164  return false;
165 
166  if (hasSampleProfile()) {
167  uint64_t TotalCallCount = 0;
168  for (const auto &BB : *F)
169  for (const auto &I : BB)
170  if (isa<CallInst>(I) || isa<InvokeInst>(I))
171  if (auto CallCount = getProfileCount(&I, nullptr))
172  TotalCallCount += CallCount.getValue();
173  if (!isColdCount(TotalCallCount))
174  return false;
175  }
176  for (const auto &BB : *F)
177  if (!isColdBlock(&BB, &BFI))
178  return false;
179  return true;
180 }
181 
182 /// Returns true if the function's entry is a cold. If it returns false, it
183 /// either means it is not cold or it is unknown whether it is cold or not (for
184 /// example, no profile data is available).
186  if (!F)
187  return false;
189  return true;
190  if (!computeSummary())
191  return false;
192  auto FunctionCount = F->getEntryCount();
193  // FIXME: The heuristic used below for determining coldness is based on
194  // preliminary SPEC tuning for inliner. This will eventually be a
195  // convenience method that calls isHotCount.
196  return FunctionCount && isColdCount(FunctionCount.getCount());
197 }
198 
199 /// Compute the hot and cold thresholds.
200 void ProfileSummaryInfo::computeThresholds() {
201  if (!computeSummary())
202  return;
203  auto &DetailedSummary = Summary->getDetailedSummary();
204  auto &HotEntry =
206  HotCountThreshold = HotEntry.MinCount;
207  if (ProfileSummaryHotCount.getNumOccurrences() > 0)
208  HotCountThreshold = ProfileSummaryHotCount;
209  auto &ColdEntry =
211  ColdCountThreshold = ColdEntry.MinCount;
212  if (ProfileSummaryColdCount.getNumOccurrences() > 0)
213  ColdCountThreshold = ProfileSummaryColdCount;
214  assert(ColdCountThreshold <= HotCountThreshold &&
215  "Cold count threshold cannot exceed hot count threshold!");
216  HasHugeWorkingSetSize =
217  HotEntry.NumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
218 }
219 
221  if (!HasHugeWorkingSetSize)
222  computeThresholds();
223  return HasHugeWorkingSetSize && HasHugeWorkingSetSize.getValue();
224 }
225 
227  if (!HotCountThreshold)
228  computeThresholds();
229  return HotCountThreshold && C >= HotCountThreshold.getValue();
230 }
231 
233  if (!ColdCountThreshold)
234  computeThresholds();
235  return ColdCountThreshold && C <= ColdCountThreshold.getValue();
236 }
237 
239  if (!HotCountThreshold)
240  computeThresholds();
241  return HotCountThreshold ? HotCountThreshold.getValue() : UINT64_MAX;
242 }
243 
245  if (!ColdCountThreshold)
246  computeThresholds();
247  return ColdCountThreshold ? ColdCountThreshold.getValue() : 0;
248 }
249 
251  auto Count = BFI->getBlockProfileCount(BB);
252  return Count && isHotCount(*Count);
253 }
254 
257  auto Count = BFI->getBlockProfileCount(BB);
258  return Count && isColdCount(*Count);
259 }
260 
263  auto C = getProfileCount(CS.getInstruction(), BFI);
264  return C && isHotCount(*C);
265 }
266 
269  auto C = getProfileCount(CS.getInstruction(), BFI);
270  if (C)
271  return isColdCount(*C);
272 
273  // In SamplePGO, if the caller has been sampled, and there is no profile
274  // annotated on the callsite, we consider the callsite as cold.
275  return hasSampleProfile() && CS.getCaller()->hasProfileData();
276 }
277 
279  "Profile summary info", false, true)
280 
282  : ImmutablePass(ID) {
284 }
285 
287  PSI.reset(new ProfileSummaryInfo(M));
288  return false;
289 }
290 
292  PSI.reset();
293  return false;
294 }
295 
296 AnalysisKey ProfileSummaryAnalysis::Key;
299  return ProfileSummaryInfo(M);
300 }
301 
303  ModuleAnalysisManager &AM) {
305 
306  OS << "Functions in " << M.getName() << " with hot/cold annotations: \n";
307  for (auto &F : M) {
308  OS << F.getName();
309  if (PSI.isFunctionEntryHot(&F))
310  OS << " :hot entry ";
311  else if (PSI.isFunctionEntryCold(&F))
312  OS << " :cold entry ";
313  OS << "\n";
314  }
315  return PreservedAnalyses::all();
316 }
317 
uint64_t CallInst * C
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
uint32_t Cutoff
The required percentile of counts.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:769
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
bool isColdCount(uint64_t C)
Returns true if count C is considered cold.
Analysis providing profile information.
This file contains the declarations for metadata subclasses.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:320
Optional< uint64_t > getProfileCount(const Instruction *CallInst, BlockFrequencyInfo *BFI)
Returns the profile count for CallInst.
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:226
F(f)
uint64_t getOrCompHotCountThreshold()
Returns HotCountThreshold if set.
static cl::opt< unsigned > ProfileSummaryHugeWorkingSetSizeThreshold("profile-summary-huge-working-set-size-threshold", cl::Hidden, cl::init(15000), cl::ZeroOrMore, cl::desc("The code working set size is considered huge if the number of" " blocks required to reach the -profile-summary-cutoff-hot" " percentile exceeds this count."))
bool isHotCount(uint64_t C)
Returns true if count C is considered hot.
bool isFunctionEntryCold(const Function *F)
Returns true if F has cold function entry.
bool isHotCallSite(const CallSite &CS, BlockFrequencyInfo *BFI)
Returns true if CallSite CS is considered hot.
static cl::opt< int > ProfileSummaryHotCount("profile-summary-hot-count", cl::ReallyHidden, cl::ZeroOrMore, cl::desc("A fixed hot count that overrides the count derived from" " profile-summary-cutoff-hot"))
uint64_t getOrCompColdCountThreshold()
Returns ColdCountThreshold if set.
Result run(Module &M, ModuleAnalysisManager &)
bool isFunctionHotInCallGraph(const Function *F, BlockFrequencyInfo &BFI)
Returns true if F contains hot code.
ProfileCount getEntryCount() const
Get the entry count for this function.
Definition: Function.cpp:1384
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Metadata * getProfileSummary()
Returns profile summary metadata.
Definition: Module.cpp:538
InstrTy * getInstruction() const
Definition: CallSite.h:96
bool isColdBlock(const BasicBlock *BB, BlockFrequencyInfo *BFI)
Returns true if BasicBlock BB is considered cold.
#define UINT64_MAX
Definition: DataTypes.h:83
const T & getValue() const LLVM_LVALUE_FUNCTION
Definition: Optional.h:162
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1281
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
Definition: Metadata.cpp:1339
bool doInitialization(Module &M) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:422
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
bool hasSampleProfile()
Returns true if module M has sample profile.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
INITIALIZE_PASS(ProfileSummaryInfoWrapperPass, "profile-summary-info", "Profile summary info", false, true) ProfileSummaryInfoWrapperPass
bool doFinalization(Module &M) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
ImmutablePass class - This class is used to provide information that does not need to be run...
Definition: Pass.h:255
Module.h This file contains the declarations for the Module class.
void initializeProfileSummaryInfoWrapperPassPass(PassRegistry &)
bool isFunctionColdInCallGraph(const Function *F, BlockFrequencyInfo &BFI)
Returns true if F contains only cold code.
static ProfileSummary * getFromMD(Metadata *MD)
Construct profile summary from metdata.
static cl::opt< int > ProfileSummaryCutoffHot("profile-summary-cutoff-hot", cl::Hidden, cl::init(990000), cl::ZeroOrMore, cl::desc("A count is hot if it exceeds the minimum count to" " reach this percentile of total counts."))
bool isFunctionEntryHot(const Function *F)
Returns true if F has hot function entry.
#define I(x, y, z)
Definition: MD5.cpp:58
bool isHotBlock(const BasicBlock *BB, BlockFrequencyInfo *BFI)
Returns true if BasicBlock BB is considered hot.
bool isColdCallSite(const CallSite &CS, BlockFrequencyInfo *BFI)
Returns true if Callsite CS is considered cold.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasHugeWorkingSetSize()
Returns true if the working set size of the code is considered huge.
static cl::opt< int > ProfileSummaryCutoffCold("profile-summary-cutoff-cold", cl::Hidden, cl::init(999999), cl::ZeroOrMore, cl::desc("A count is cold if it is below the minimum count" " to reach this percentile of total counts."))
A container for analyses that lazily runs them and caches their results.
std::vector< ProfileSummaryEntry > SummaryEntryVector
static cl::opt< int > ProfileSummaryColdCount("profile-summary-cold-count", cl::ReallyHidden, cl::ZeroOrMore, cl::desc("A fixed cold count that overrides the count derived from" " profile-summary-cutoff-cold"))
bool hasProfileData() const
Return true if the function is annotated with profile data.
Definition: Function.h:307
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
Optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
static const ProfileSummaryEntry & getEntryForPercentile(SummaryEntryVector &DS, uint64_t Percentile)
const BasicBlock * getParent() const
Definition: Instruction.h:66
FunTy * getCaller() const
Return the caller function for this call site.
Definition: CallSite.h:275