]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/lib/Analysis/ProfileSummaryInfo.cpp
MFC r355940:
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / lib / Analysis / ProfileSummaryInfo.cpp
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/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
31 static cl::opt<int> ProfileSummaryCutoffHot(
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
36 static cl::opt<int> ProfileSummaryCutoffCold(
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
41 static cl::opt<unsigned> ProfileSummaryHugeWorkingSetSizeThreshold(
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.
50 static cl::opt<int> ProfileSummaryHotCount(
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
55 static cl::opt<int> ProfileSummaryColdCount(
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.
61 static const ProfileSummaryEntry &getEntryForPercentile(SummaryEntryVector &DS,
62                                                         uint64_t Percentile) {
63   auto It = partition_point(DS, [=](const ProfileSummaryEntry &Entry) {
64     return Entry.Cutoff < Percentile;
65   });
66   // The required percentile has to be <= one of the percentiles in the
67   // detailed summary.
68   if (It == DS.end())
69     report_fatal_error("Desired percentile exceeds the maximum cutoff");
70   return *It;
71 }
72
73 // The profile summary metadata may be attached either by the frontend or by
74 // any backend passes (IR level instrumentation, for example). This method
75 // checks if the Summary is null and if so checks if the summary metadata is now
76 // available in the module and parses it to get the Summary object. Returns true
77 // if a valid Summary is available.
78 bool ProfileSummaryInfo::computeSummary() {
79   if (Summary)
80     return true;
81   // First try to get context sensitive ProfileSummary.
82   auto *SummaryMD = M.getProfileSummary(/* IsCS */ true);
83   if (SummaryMD) {
84     Summary.reset(ProfileSummary::getFromMD(SummaryMD));
85     return true;
86   }
87   // This will actually return PSK_Instr or PSK_Sample summary.
88   SummaryMD = M.getProfileSummary(/* IsCS */ false);
89   if (!SummaryMD)
90     return false;
91   Summary.reset(ProfileSummary::getFromMD(SummaryMD));
92   return true;
93 }
94
95 Optional<uint64_t>
96 ProfileSummaryInfo::getProfileCount(const Instruction *Inst,
97                                     BlockFrequencyInfo *BFI,
98                                     bool AllowSynthetic) {
99   if (!Inst)
100     return None;
101   assert((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) &&
102          "We can only get profile count for call/invoke instruction.");
103   if (hasSampleProfile()) {
104     // In sample PGO mode, check if there is a profile metadata on the
105     // instruction. If it is present, determine hotness solely based on that,
106     // since the sampled entry count may not be accurate. If there is no
107     // annotated on the instruction, return None.
108     uint64_t TotalCount;
109     if (Inst->extractProfTotalWeight(TotalCount))
110       return TotalCount;
111     return None;
112   }
113   if (BFI)
114     return BFI->getBlockProfileCount(Inst->getParent(), AllowSynthetic);
115   return None;
116 }
117
118 /// Returns true if the function's entry is hot. If it returns false, it
119 /// either means it is not hot or it is unknown whether it is hot or not (for
120 /// example, no profile data is available).
121 bool ProfileSummaryInfo::isFunctionEntryHot(const Function *F) {
122   if (!F || !computeSummary())
123     return false;
124   auto FunctionCount = F->getEntryCount();
125   // FIXME: The heuristic used below for determining hotness is based on
126   // preliminary SPEC tuning for inliner. This will eventually be a
127   // convenience method that calls isHotCount.
128   return FunctionCount && isHotCount(FunctionCount.getCount());
129 }
130
131 /// Returns true if the function contains hot code. This can include a hot
132 /// function entry count, hot basic block, or (in the case of Sample PGO)
133 /// hot total call edge count.
134 /// If it returns false, it either means it is not hot or it is unknown
135 /// (for example, no profile data is available).
136 bool ProfileSummaryInfo::isFunctionHotInCallGraph(const Function *F,
137                                                   BlockFrequencyInfo &BFI) {
138   if (!F || !computeSummary())
139     return false;
140   if (auto FunctionCount = F->getEntryCount())
141     if (isHotCount(FunctionCount.getCount()))
142       return true;
143
144   if (hasSampleProfile()) {
145     uint64_t TotalCallCount = 0;
146     for (const auto &BB : *F)
147       for (const auto &I : BB)
148         if (isa<CallInst>(I) || isa<InvokeInst>(I))
149           if (auto CallCount = getProfileCount(&I, nullptr))
150             TotalCallCount += CallCount.getValue();
151     if (isHotCount(TotalCallCount))
152       return true;
153   }
154   for (const auto &BB : *F)
155     if (isHotBlock(&BB, &BFI))
156       return true;
157   return false;
158 }
159
160 /// Returns true if the function only contains cold code. This means that
161 /// the function entry and blocks are all cold, and (in the case of Sample PGO)
162 /// the total call edge count is cold.
163 /// If it returns false, it either means it is not cold or it is unknown
164 /// (for example, no profile data is available).
165 bool ProfileSummaryInfo::isFunctionColdInCallGraph(const Function *F,
166                                                    BlockFrequencyInfo &BFI) {
167   if (!F || !computeSummary())
168     return false;
169   if (auto FunctionCount = F->getEntryCount())
170     if (!isColdCount(FunctionCount.getCount()))
171       return false;
172
173   if (hasSampleProfile()) {
174     uint64_t TotalCallCount = 0;
175     for (const auto &BB : *F)
176       for (const auto &I : BB)
177         if (isa<CallInst>(I) || isa<InvokeInst>(I))
178           if (auto CallCount = getProfileCount(&I, nullptr))
179             TotalCallCount += CallCount.getValue();
180     if (!isColdCount(TotalCallCount))
181       return false;
182   }
183   for (const auto &BB : *F)
184     if (!isColdBlock(&BB, &BFI))
185       return false;
186   return true;
187 }
188
189 /// Returns true if the function's entry is a cold. If it returns false, it
190 /// either means it is not cold or it is unknown whether it is cold or not (for
191 /// example, no profile data is available).
192 bool ProfileSummaryInfo::isFunctionEntryCold(const Function *F) {
193   if (!F)
194     return false;
195   if (F->hasFnAttribute(Attribute::Cold))
196     return true;
197   if (!computeSummary())
198     return false;
199   auto FunctionCount = F->getEntryCount();
200   // FIXME: The heuristic used below for determining coldness is based on
201   // preliminary SPEC tuning for inliner. This will eventually be a
202   // convenience method that calls isHotCount.
203   return FunctionCount && isColdCount(FunctionCount.getCount());
204 }
205
206 /// Compute the hot and cold thresholds.
207 void ProfileSummaryInfo::computeThresholds() {
208   if (!computeSummary())
209     return;
210   auto &DetailedSummary = Summary->getDetailedSummary();
211   auto &HotEntry =
212       getEntryForPercentile(DetailedSummary, ProfileSummaryCutoffHot);
213   HotCountThreshold = HotEntry.MinCount;
214   if (ProfileSummaryHotCount.getNumOccurrences() > 0)
215     HotCountThreshold = ProfileSummaryHotCount;
216   auto &ColdEntry =
217       getEntryForPercentile(DetailedSummary, ProfileSummaryCutoffCold);
218   ColdCountThreshold = ColdEntry.MinCount;
219   if (ProfileSummaryColdCount.getNumOccurrences() > 0)
220     ColdCountThreshold = ProfileSummaryColdCount;
221   assert(ColdCountThreshold <= HotCountThreshold &&
222          "Cold count threshold cannot exceed hot count threshold!");
223   HasHugeWorkingSetSize =
224       HotEntry.NumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
225 }
226
227 bool ProfileSummaryInfo::hasHugeWorkingSetSize() {
228   if (!HasHugeWorkingSetSize)
229     computeThresholds();
230   return HasHugeWorkingSetSize && HasHugeWorkingSetSize.getValue();
231 }
232
233 bool ProfileSummaryInfo::isHotCount(uint64_t C) {
234   if (!HotCountThreshold)
235     computeThresholds();
236   return HotCountThreshold && C >= HotCountThreshold.getValue();
237 }
238
239 bool ProfileSummaryInfo::isColdCount(uint64_t C) {
240   if (!ColdCountThreshold)
241     computeThresholds();
242   return ColdCountThreshold && C <= ColdCountThreshold.getValue();
243 }
244
245 uint64_t ProfileSummaryInfo::getOrCompHotCountThreshold() {
246   if (!HotCountThreshold)
247     computeThresholds();
248   return HotCountThreshold ? HotCountThreshold.getValue() : UINT64_MAX;
249 }
250
251 uint64_t ProfileSummaryInfo::getOrCompColdCountThreshold() {
252   if (!ColdCountThreshold)
253     computeThresholds();
254   return ColdCountThreshold ? ColdCountThreshold.getValue() : 0;
255 }
256
257 bool ProfileSummaryInfo::isHotBlock(const BasicBlock *BB, BlockFrequencyInfo *BFI) {
258   auto Count = BFI->getBlockProfileCount(BB);
259   return Count && isHotCount(*Count);
260 }
261
262 bool ProfileSummaryInfo::isColdBlock(const BasicBlock *BB,
263                                   BlockFrequencyInfo *BFI) {
264   auto Count = BFI->getBlockProfileCount(BB);
265   return Count && isColdCount(*Count);
266 }
267
268 bool ProfileSummaryInfo::isHotCallSite(const CallSite &CS,
269                                        BlockFrequencyInfo *BFI) {
270   auto C = getProfileCount(CS.getInstruction(), BFI);
271   return C && isHotCount(*C);
272 }
273
274 bool ProfileSummaryInfo::isColdCallSite(const CallSite &CS,
275                                         BlockFrequencyInfo *BFI) {
276   auto C = getProfileCount(CS.getInstruction(), BFI);
277   if (C)
278     return isColdCount(*C);
279
280   // In SamplePGO, if the caller has been sampled, and there is no profile
281   // annotated on the callsite, we consider the callsite as cold.
282   return hasSampleProfile() && CS.getCaller()->hasProfileData();
283 }
284
285 INITIALIZE_PASS(ProfileSummaryInfoWrapperPass, "profile-summary-info",
286                 "Profile summary info", false, true)
287
288 ProfileSummaryInfoWrapperPass::ProfileSummaryInfoWrapperPass()
289     : ImmutablePass(ID) {
290   initializeProfileSummaryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
291 }
292
293 bool ProfileSummaryInfoWrapperPass::doInitialization(Module &M) {
294   PSI.reset(new ProfileSummaryInfo(M));
295   return false;
296 }
297
298 bool ProfileSummaryInfoWrapperPass::doFinalization(Module &M) {
299   PSI.reset();
300   return false;
301 }
302
303 AnalysisKey ProfileSummaryAnalysis::Key;
304 ProfileSummaryInfo ProfileSummaryAnalysis::run(Module &M,
305                                                ModuleAnalysisManager &) {
306   return ProfileSummaryInfo(M);
307 }
308
309 PreservedAnalyses ProfileSummaryPrinterPass::run(Module &M,
310                                                  ModuleAnalysisManager &AM) {
311   ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
312
313   OS << "Functions in " << M.getName() << " with hot/cold annotations: \n";
314   for (auto &F : M) {
315     OS << F.getName();
316     if (PSI.isFunctionEntryHot(&F))
317       OS << " :hot entry ";
318     else if (PSI.isFunctionEntryCold(&F))
319       OS << " :cold entry ";
320     OS << "\n";
321   }
322   return PreservedAnalyses::all();
323 }
324
325 char ProfileSummaryInfoWrapperPass::ID = 0;