LLVM  6.0.0svn
ProfileSummaryInfo.cpp
Go to the documentation of this file.
1 //===- ProfileSummaryInfo.cpp - Global profile summary information --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a pass that provides access to the global profile summary
11 // information.
12 //
13 //===----------------------------------------------------------------------===//
14 
17 #include "llvm/IR/BasicBlock.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/Metadata.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/ProfileSummary.h"
22 using namespace llvm;
23 
24 // The following two parameters determine the threshold for a count to be
25 // considered hot/cold. These two parameters are percentile values (multiplied
26 // by 10000). If the counts are sorted in descending order, the minimum count to
27 // reach ProfileSummaryCutoffHot gives the threshold to determine a hot count.
28 // Similarly, the minimum count to reach ProfileSummaryCutoffCold gives the
29 // threshold for determining cold count (everything <= this threshold is
30 // considered cold).
31 
33  "profile-summary-cutoff-hot", cl::Hidden, cl::init(990000), cl::ZeroOrMore,
34  cl::desc("A count is hot if it exceeds the minimum count to"
35  " reach this percentile of total counts."));
36 
38  "profile-summary-cutoff-cold", cl::Hidden, cl::init(999999), cl::ZeroOrMore,
39  cl::desc("A count is cold if it is below the minimum count"
40  " to reach this percentile of total counts."));
41 
43  "profile-sample-accurate", cl::Hidden, cl::init(false),
44  cl::desc("If the sample profile is accurate, we will mark all un-sampled "
45  "callsite as cold. Otherwise, treat un-sampled callsites as if "
46  "we have no profile."));
48  "profile-summary-huge-working-set-size-threshold", cl::Hidden,
49  cl::init(15000), cl::ZeroOrMore,
50  cl::desc("The code working set size is considered huge if the number of"
51  " blocks required to reach the -profile-summary-cutoff-hot"
52  " percentile exceeds this count."));
53 
54 // Find the summary entry for a desired percentile of counts.
56  uint64_t Percentile) {
57  auto Compare = [](const ProfileSummaryEntry &Entry, uint64_t Percentile) {
58  return Entry.Cutoff < Percentile;
59  };
60  auto It = std::lower_bound(DS.begin(), DS.end(), Percentile, Compare);
61  // The required percentile has to be <= one of the percentiles in the
62  // detailed summary.
63  if (It == DS.end())
64  report_fatal_error("Desired percentile exceeds the maximum cutoff");
65  return *It;
66 }
67 
68 // The profile summary metadata may be attached either by the frontend or by
69 // any backend passes (IR level instrumentation, for example). This method
70 // checks if the Summary is null and if so checks if the summary metadata is now
71 // available in the module and parses it to get the Summary object. Returns true
72 // if a valid Summary is available.
73 bool ProfileSummaryInfo::computeSummary() {
74  if (Summary)
75  return true;
76  auto *SummaryMD = M.getProfileSummary();
77  if (!SummaryMD)
78  return false;
79  Summary.reset(ProfileSummary::getFromMD(SummaryMD));
80  return true;
81 }
82 
86  if (!Inst)
87  return None;
88  assert((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) &&
89  "We can only get profile count for call/invoke instruction.");
90  if (hasSampleProfile()) {
91  // In sample PGO mode, check if there is a profile metadata on the
92  // instruction. If it is present, determine hotness solely based on that,
93  // since the sampled entry count may not be accurate. If there is no
94  // annotated on the instruction, return None.
95  uint64_t TotalCount;
96  if (Inst->extractProfTotalWeight(TotalCount))
97  return TotalCount;
98  return None;
99  }
100  if (BFI)
101  return BFI->getBlockProfileCount(Inst->getParent());
102  return None;
103 }
104 
105 /// Returns true if the function's entry is hot. If it returns false, it
106 /// either means it is not hot or it is unknown whether it is hot or not (for
107 /// example, no profile data is available).
109  if (!F || !computeSummary())
110  return false;
111  auto FunctionCount = F->getEntryCount();
112  // FIXME: The heuristic used below for determining hotness is based on
113  // preliminary SPEC tuning for inliner. This will eventually be a
114  // convenience method that calls isHotCount.
115  return FunctionCount && isHotCount(FunctionCount.getValue());
116 }
117 
118 /// Returns true if the function's entry or total call edge count is hot.
119 /// If it returns false, it either means it is not hot or it is unknown
120 /// whether it is hot or not (for example, no profile data is available).
122  if (!F || !computeSummary())
123  return false;
124  if (auto FunctionCount = F->getEntryCount())
125  if (isHotCount(FunctionCount.getValue()))
126  return true;
127 
128  uint64_t TotalCallCount = 0;
129  for (const auto &BB : *F)
130  for (const auto &I : BB)
131  if (isa<CallInst>(I) || isa<InvokeInst>(I))
132  if (auto CallCount = getProfileCount(&I, nullptr))
133  TotalCallCount += CallCount.getValue();
134  return isHotCount(TotalCallCount);
135 }
136 
137 /// Returns true if the function's entry and total call edge count is cold.
138 /// If it returns false, it either means it is not cold or it is unknown
139 /// whether it is cold or not (for example, no profile data is available).
141  if (!F || !computeSummary())
142  return false;
143  if (auto FunctionCount = F->getEntryCount())
144  if (!isColdCount(FunctionCount.getValue()))
145  return false;
146 
147  uint64_t TotalCallCount = 0;
148  for (const auto &BB : *F)
149  for (const auto &I : BB)
150  if (isa<CallInst>(I) || isa<InvokeInst>(I))
151  if (auto CallCount = getProfileCount(&I, nullptr))
152  TotalCallCount += CallCount.getValue();
153  return isColdCount(TotalCallCount);
154 }
155 
156 /// Returns true if the function's entry is a cold. If it returns false, it
157 /// either means it is not cold or it is unknown whether it is cold or not (for
158 /// example, no profile data is available).
160  if (!F)
161  return false;
163  return true;
164  if (!computeSummary())
165  return false;
166  auto FunctionCount = F->getEntryCount();
167  // FIXME: The heuristic used below for determining coldness is based on
168  // preliminary SPEC tuning for inliner. This will eventually be a
169  // convenience method that calls isHotCount.
170  return FunctionCount && isColdCount(FunctionCount.getValue());
171 }
172 
173 /// Compute the hot and cold thresholds.
174 void ProfileSummaryInfo::computeThresholds() {
175  if (!computeSummary())
176  return;
177  auto &DetailedSummary = Summary->getDetailedSummary();
178  auto &HotEntry =
180  HotCountThreshold = HotEntry.MinCount;
181  auto &ColdEntry =
183  ColdCountThreshold = ColdEntry.MinCount;
184  HasHugeWorkingSetSize =
185  HotEntry.NumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
186 }
187 
189  if (!HasHugeWorkingSetSize)
190  computeThresholds();
191  return HasHugeWorkingSetSize && HasHugeWorkingSetSize.getValue();
192 }
193 
195  if (!HotCountThreshold)
196  computeThresholds();
197  return HotCountThreshold && C >= HotCountThreshold.getValue();
198 }
199 
201  if (!ColdCountThreshold)
202  computeThresholds();
203  return ColdCountThreshold && C <= ColdCountThreshold.getValue();
204 }
205 
207  auto Count = BFI->getBlockProfileCount(B);
208  return Count && isHotCount(*Count);
209 }
210 
213  auto Count = BFI->getBlockProfileCount(B);
214  return Count && isColdCount(*Count);
215 }
216 
219  auto C = getProfileCount(CS.getInstruction(), BFI);
220  return C && isHotCount(*C);
221 }
222 
225  auto C = getProfileCount(CS.getInstruction(), BFI);
226  if (C)
227  return isColdCount(*C);
228 
229  // In SamplePGO, if the caller has been sampled, and there is no profile
230  // annotatedon the callsite, we consider the callsite as cold.
231  // If there is no profile for the caller, and we know the profile is
232  // accurate, we consider the callsite as cold.
233  return (hasSampleProfile() &&
235  CS.getCaller()->hasFnAttribute("profile-sample-accurate")));
236 }
237 
239  "Profile summary info", false, true)
240 
242  : ImmutablePass(ID) {
244 }
245 
247  PSI.reset(new ProfileSummaryInfo(M));
248  return false;
249 }
250 
252  PSI.reset();
253  return false;
254 }
255 
256 AnalysisKey ProfileSummaryAnalysis::Key;
259  return ProfileSummaryInfo(M);
260 }
261 
263  ModuleAnalysisManager &AM) {
265 
266  OS << "Functions in " << M.getName() << " with hot/cold annotations: \n";
267  for (auto &F : M) {
268  OS << F.getName();
269  if (PSI.isFunctionEntryHot(&F))
270  OS << " :hot entry ";
271  else if (PSI.isFunctionEntryCold(&F))
272  OS << " :cold entry ";
273  OS << "\n";
274  }
275  return PreservedAnalyses::all();
276 }
277 
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:687
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:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
bool isColdBB(const BasicBlock *B, BlockFrequencyInfo *BFI)
Returns true if BasicBlock B is considered cold.
bool isFunctionHotInCallGraph(const Function *F)
Returns true if F has hot function entry or hot call edge.
bool isColdCount(uint64_t C)
Returns true if count C is considered cold.
static cl::opt< bool > ProfileSampleAccurate("profile-sample-accurate", cl::Hidden, cl::init(false), cl::desc("If the sample profile is accurate, we will mark all un-sampled " "callsite as cold. Otherwise, treat un-sampled callsites as if " "we have no profile."))
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:262
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:220
F(f)
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 F is a hot function.
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.
Result run(Module &M, ModuleAnalysisManager &)
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
bool isHotBB(const BasicBlock *B, BlockFrequencyInfo *BFI)
Returns true if BasicBlock B is considered hot.
InstrTy * getInstruction() const
Definition: CallSite.h:92
Metadata * getProfileSummary()
Returns profile summary metadata.
Definition: Module.cpp:505
const T & getValue() const LLVM_LVALUE_FUNCTION
Definition: Optional.h:127
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:904
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
Definition: Metadata.cpp:1328
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:406
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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:59
bool isFunctionColdInCallGraph(const Function *F)
Returns true if F has cold function entry or cold call edge.
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
Optional< uint64_t > getEntryCount() const
Get the entry count for this function.
Definition: Function.cpp:1330
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:256
Module.h This file contains the declarations for the Module class.
void initializeProfileSummaryInfoWrapperPassPass(PassRegistry &)
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."))
FunTy * getCaller() const
Return the caller function for this call site.
Definition: CallSite.h:267
bool isFunctionEntryHot(const Function *F)
Returns true if F has hot function entry.
#define I(x, y, z)
Definition: MD5.cpp:58
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
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