1//=-- SampleProf.cpp - Sample profiling format support --------------------===// 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 7//===----------------------------------------------------------------------===// 9// This file contains common definitions used in the reading and writing of 10// sample profile data. 12//===----------------------------------------------------------------------===// 15#include "llvm/Config/llvm-config.h" 25#include <system_error> 28using namespacesampleprof;
32cl::desc(
"Cutoff value about how many symbols in profile symbol list " 33"will be used. This is very useful for performance debugging"));
36"generate-merged-base-profiles",
37cl::desc(
"When generating nested context-sensitive profiles, always " 38"generate extra base profile for function with all its context " 39"profiles merged into it."));
49}
// namespace sampleprof 54// FIXME: This class is only here to support the transition to llvm::Error. It 55// will be removed once this transition is complete. Clients should prefer to 56// deal with the Error value directly, rather than converting to error_code. 57classSampleProfErrorCategoryType :
public std::error_category {
58constchar *
name()
const noexcept
override{
return"llvm.sampleprof"; }
60 std::string message(
int IE)
const override{
63case sampleprof_error::success:
65case sampleprof_error::bad_magic:
66return"Invalid sample profile data (bad magic)";
67case sampleprof_error::unsupported_version:
68return"Unsupported sample profile format version";
69case sampleprof_error::too_large:
70return"Too much profile data";
71case sampleprof_error::truncated:
72return"Truncated profile data";
73case sampleprof_error::malformed:
74return"Malformed sample profile data";
75case sampleprof_error::unrecognized_format:
76return"Unrecognized sample profile encoding format";
77case sampleprof_error::unsupported_writing_format:
78return"Profile encoding format unsupported for writing operations";
79case sampleprof_error::truncated_name_table:
80return"Truncated function name table";
81case sampleprof_error::not_implemented:
82return"Unimplemented feature";
83case sampleprof_error::counter_overflow:
84return"Counter overflow";
85case sampleprof_error::ostream_seek_unsupported:
86return"Ostream does not support seek";
87case sampleprof_error::uncompress_failed:
88return"Uncompress failure";
89case sampleprof_error::zlib_unavailable:
90return"Zlib is unavailable";
91case sampleprof_error::hash_mismatch:
92return"Function hash mismatch";
98}
// end anonymous namespace 101static SampleProfErrorCategoryType ErrorCategory;
117/// Merge the samples in \p Other into this record. 118/// Optionally scale sample counts by \p Weight. 123for (
constauto &
I :
Other.getCallTargets()) {
129#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 133/// Print the sample record to the stream \p OS indented by \p Indent. 139OS <<
" " <<
I.first <<
":" <<
I.second;
144#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 154/// Print the samples collected for a function on stream \p OS. 159OS << TotalSamples <<
", " << TotalHeadSamples <<
", " << BodySamples.size()
160 <<
" sampled lines\n";
163if (!BodySamples.empty()) {
164OS <<
"Samples collected in the function's body {\n";
166for (
constauto &SI : SortedBodySamples.
get()) {
168OS << SI->first <<
": " << SI->second;
173OS <<
"No samples collected in the function's body\n";
177if (!CallsiteSamples.empty()) {
178OS <<
"Samples collected in inlined callsites {\n";
181for (
constauto &CS : SortedCallsiteSamples.
get()) {
182for (
constauto &FS : CS->second) {
184OS << CS->first <<
": inlined callee: " << FS.second.getFunction()
186 FS.second.print(
OS, Indent + 4);
192OS <<
"No inlined callsites in this function\n";
204 std::vector<NameFunctionSamples> &SortedProfiles) {
205for (
constauto &
I : ProfileMap) {
206 SortedProfiles.push_back(std::make_pair(
I.first, &
I.second));
210if (
A.second->getTotalSamples() ==
B.second->getTotalSamples())
211returnA.second->getContext() <
B.second->getContext();
212returnA.second->getTotalSamples() >
B.second->getTotalSamples();
217return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
224// In a pseudo-probe based profile, a callsite is simply represented by the 225// ID of the probe associated with the call instruction. The probe ID is 226// encoded in the Discriminator field of the call instruction's debug 229 DIL->getDiscriminator()),
232unsigned Discriminator =
241 *FuncNameToProfNameMap)
const{
246for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
247// Use C++ linkage name if possible. 248StringRefName = PrevDIL->getScope()->getSubprogram()->getLinkageName();
250Name = PrevDIL->getScope()->getSubprogram()->getName();
260for (
int i = S.
size() - 1; i >= 0 && FS !=
nullptr; i--) {
261 FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper,
262 FuncNameToProfNameMap);
269for (
constauto &BS : BodySamples)
270for (
constauto &TS : BS.second.getCallTargets())
273for (
constauto &CS : CallsiteSamples) {
274for (
constauto &NameFS : CS.second) {
275 NameSet.
insert(NameFS.first);
276 NameFS.second.findAllNames(NameSet);
285 *FuncNameToProfNameMap)
const{
289if (
I == CallsiteSamples.end())
292if (FS !=
I->second.end())
295if (FuncNameToProfNameMap && !FuncNameToProfNameMap->empty()) {
297if (R != FuncNameToProfNameMap->end()) {
298 CalleeName = R->second.stringRef();
300if (FS !=
I->second.end())
308if (FS !=
I->second.end())
312// If we cannot find exact match of the callee name, return the FS with 313// the max total count. Only do this when CalleeName is not provided, 314// i.e., only for indirect calls. 315if (!CalleeName.
empty())
319for (
constauto &NameFS :
I->second)
320if (NameFS.second.getTotalSamples() >= MaxTotalSamples) {
321 MaxTotalSamples = NameFS.second.getTotalSamples();
327#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 333constchar *ListStart =
reinterpret_cast<constchar *
>(
Data);
339Size += Str.size() + 1;
349uint32_t ColdContextFrameLength,
bool TrimBaseProfileOnly) {
350if (!TrimColdContext && !MergeColdContext)
353// Nothing to merge if sample threshold is zero 357// Trimming base profiles only is mainly to honor the preinliner decsion. When 358// MergeColdContext is true preinliner decsion is not honored anyway so turn 359// off TrimBaseProfileOnly. 361 TrimBaseProfileOnly =
false;
363// Filter the cold profiles from ProfileMap and move them into a tmp 365 std::vector<std::pair<hash_code, const FunctionSamples *>> ColdProfiles;
366for (
constauto &
I : ProfileMap) {
371 ColdProfiles.emplace_back(
I.first, &
I.second);
374// Remove the cold profile from ProfileMap and merge them into 375// MergedProfileMap by the last K frames of context 377for (
constauto &
I : ColdProfiles) {
378if (MergeColdContext) {
382// Need to set MergedProfile's context here otherwise it will be lost. 384 MergedProfile.
merge(*
I.second);
386 ProfileMap.erase(
I.first);
389// Move the merged profiles into ProfileMap; 390for (
constauto &
I : MergedProfileMap) {
391// Filter the cold merged profile 393 ProfileMap.find(
I.second.getContext()) == ProfileMap.end())
395// Merge the profile if the original profile exists, otherwise just insert 396// as a new profile. If inserted as a new profile from MergedProfileMap, it 397// already has the right context. 400 OrigProfile.
merge(
I.second);
405// Sort the symbols before output. If doing compression. 406// It will make the compression much more effective. 407 std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
410 std::string OutputString;
411for (
auto &
Sym : SortedList) {
412 OutputString.append(
Sym.str());
413 OutputString.append(1,
'\0');
421OS <<
"======== Dump profile symbol list ========\n";
422 std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
425for (
auto &
Sym : SortedList)
435assert(It->second.FuncName == CalleeName &&
436"Hash collision for child context node");
445 : ProfileMap(Profiles) {
446for (
auto &FuncSample : Profiles) {
448auto *NewNode = getOrCreateContextPath(FSamples->
getContext());
449assert(!NewNode->FuncSamples &&
"New node cannot have sample profile");
450 NewNode->FuncSamples = FSamples;
455ProfileConverter::getOrCreateContextPath(
constSampleContext &Context) {
456auto Node = &RootFrame;
459 Node = Node->getOrCreateChildFrame(CallSiteLoc, Callsite.Func);
460 CallSiteLoc = Callsite.Location;
466// Process each child profile. Add each child profile to callsite profile map 467// of the current node `Node` if `Node` comes with a profile. Otherwise 468// promote the child profile to a standalone profile. 469auto *NodeProfile =
Node.FuncSamples;
470for (
auto &It :
Node.AllChildFrames) {
471auto &ChildNode = It.second;
473auto *ChildProfile = ChildNode.FuncSamples;
478// Reset the child context to be contextless. 479 ChildProfile->getContext().setFunction(OrigChildContext.
getFunction());
481// Add child profile to the callsite profile map. 482auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
483 SamplesMap.emplace(OrigChildContext.
getFunction(), *ChildProfile);
484 NodeProfile->addTotalSamples(ChildProfile->getTotalSamples());
485// Remove the corresponding body sample for the callsite and update the 487auto Count = NodeProfile->removeCalledTargetAndBodySample(
488 ChildNode.CallSiteLoc.LineOffset, ChildNode.CallSiteLoc.Discriminator,
490 NodeProfile->removeTotalSamples(Count);
494// Separate child profile to be a standalone profile, if the current parent 495// profile doesn't exist. This is a duplicating operation when the child 496// profile is already incorporated into the parent which is still useful and 497// thus done optionally. It is seen that duplicating context profiles into 498// base profiles improves the code quality for thinlto build by allowing a 499// profile in the prelink phase for to-be-fully-inlined functions. 501 ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
502 NewChildProfileHash = ChildProfile->getContext().getHashCode();
504 ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
505 NewChildProfileHash = ChildProfile->getContext().getHashCode();
506auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
507 SamplesMap[ChildProfile->getFunction()].getContext().setAttribute(
511// Remove the original child profile. Check if MD5 of new child profile 512// collides with old profile, in this case the [] operator already 513// overwritten it without the need of erase. 514if (NewChildProfileHash != OrigChildContextHash)
515 ProfileMap.
erase(OrigChildContextHash);
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
static cl::opt< unsigned > ColdCountThreshold("mfs-count-threshold", cl::desc("Minimum number of times a block must be executed to be retained."), cl::init(1), cl::Hidden)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static cl::opt< bool > GenerateMergedBaseProfiles("generate-merged-base-profiles", cl::desc("When generating nested context-sensitive profiles, always " "generate extra base profile for function with all its context " "profiles merged into it."))
static cl::opt< uint64_t > ProfileSymbolListCutOff("profile-symbol-list-cutoff", cl::Hidden, cl::init(-1), cl::desc("Cutoff value about how many symbols in profile symbol list " "will be used. This is very useful for performance debugging"))
unsigned getBaseDiscriminator() const
Returns the base discriminator stored in the discriminator.
Implements a dense probed hash-table based set.
reference emplace_back(ArgTypes &&... Args)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
std::pair< iterator, bool > insert(const ValueT &V)
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
This class represents a function that is read from a sample profile.
Representation of the samples collected for a function.
static bool ProfileIsPreInlined
const FunctionSamples * findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName, SampleProfileReaderItaniumRemapper *Remapper, const HashKeyMap< std::unordered_map, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const
Returns a pointer to FunctionSamples at the given callsite location Loc with callee CalleeName.
static uint64_t getCallSiteHash(FunctionId Callee, const LineLocation &Callsite)
Returns a unique hash code for a combination of a callsite location and the callee function name.
const LineLocation & mapIRLocToProfileLoc(const LineLocation &IRLoc) const
FunctionId getFunction() const
Return the function name.
uint64_t getFunctionHash() const
const FunctionSamples * findFunctionSamples(const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper=nullptr, const HashKeyMap< std::unordered_map, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const
Get the FunctionSamples of the inline instance where DIL originates from.
static bool ProfileIsProbeBased
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
void findAllNames(DenseSet< FunctionId > &NameSet) const
static unsigned getOffset(const DILocation *DIL)
Returns the line offset to the start line of the subprogram.
static bool ProfileIsFS
If this profile uses flow sensitive discriminators.
SampleContext & getContext() const
static bool HasUniqSuffix
Whether the profile contains any ".__uniq." suffix in a name.
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
void print(raw_ostream &OS=dbgs(), unsigned Indent=0) const
Print the samples collected for a function on stream OS.
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
static LineLocation getCallSiteIdentifier(const DILocation *DIL, bool ProfileIsFS=false)
Returns a unique call site identifier for a given debug location of a call instruction.
static bool UseMD5
Whether the profile uses MD5 to represent string.
This class is a wrapper to associative container MapT<KeyT, ValueT> using the hash value of the origi...
iterator find(const original_key_type &Key)
ProfileConverter(SampleProfileMap &Profiles)
void add(StringRef Name, bool Copy=false)
copy indicates whether we need to copy the underlying memory for the input Name.
std::error_code write(raw_ostream &OS)
void dump(raw_ostream &OS=dbgs()) const
std::error_code read(const uint8_t *Data, uint64_t ListSize)
void trimAndMergeColdContextProfiles(uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext, uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly)
SampleContextFrames getContextFrames() const
bool isBaseContext() const
uint64_t getHashCode() const
FunctionId getFunction() const
This class provides operator overloads to the map container using MD5 as the key type,...
mapped_type & create(const SampleContext &Ctx)
size_t erase(const SampleContext &Ctx)
SampleProfileReaderItaniumRemapper remaps the profile data from a sample profile data reader,...
std::optional< StringRef > lookUpNameInProfile(StringRef FunctionName)
Return the equivalent name in the profile for FunctionName if it exists.
Representation of a single sample record.
bool hasCalls() const
Return true if this sample record contains function calls.
sampleprof_error merge(const SampleRecord &Other, uint64_t Weight=1)
Merge the samples in Other into this record.
sampleprof_error addSamples(uint64_t S, uint64_t Weight=1)
Increment the number of samples for this record by S.
const SortedCallTargetSet getSortedCallTargets() const
void print(raw_ostream &OS, unsigned Indent) const
Print the sample record to the stream OS indented by Indent.
sampleprof_error addCalledTarget(FunctionId F, uint64_t S, uint64_t Weight=1)
Add called function F with samples S.
Sort a LocationT->SampleT map by LocationT.
const SamplesWithLocList & get() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
static FunctionId getRepInFormat(StringRef Name)
Get the proper representation of a string according to whether the current Format uses MD5 to represe...
void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
std::pair< hash_code, const FunctionSamples * > NameFunctionSamples
@ ContextDuplicatedIntoBase
raw_ostream & operator<<(raw_ostream &OS, const FunctionId &Obj)
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
sampleprof_error mergeSampleProfErrors(sampleprof_error &Accumulator, sampleprof_error Result)
void sort(IteratorTy Start, IteratorTy End)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
const std::error_category & sampleprof_category()
static uint32_t extractProbeIndex(uint32_t Value)
Represents the relative location of an instruction.
void print(raw_ostream &OS) const
FrameNode * getOrCreateChildFrame(const LineLocation &CallSite, FunctionId CalleeName)
std::map< uint64_t, FrameNode > AllChildFrames