llvm-project
503 строки · 18.6 Кб
1//=-- SampleProf.cpp - Sample profiling format support --------------------===//
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 common definitions used in the reading and writing of
10// sample profile data.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ProfileData/SampleProf.h"
15#include "llvm/Config/llvm-config.h"
16#include "llvm/IR/DebugInfoMetadata.h"
17#include "llvm/IR/PseudoProbe.h"
18#include "llvm/ProfileData/SampleProfReader.h"
19#include "llvm/Support/CommandLine.h"
20#include "llvm/Support/Compiler.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/Support/ErrorHandling.h"
23#include "llvm/Support/raw_ostream.h"
24#include <string>
25#include <system_error>
26
27using namespace llvm;
28using namespace sampleprof;
29
30static cl::opt<uint64_t> ProfileSymbolListCutOff(
31"profile-symbol-list-cutoff", cl::Hidden, cl::init(-1),
32cl::desc("Cutoff value about how many symbols in profile symbol list "
33"will be used. This is very useful for performance debugging"));
34
35static cl::opt<bool> GenerateMergedBaseProfiles(
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."));
40
41namespace llvm {
42namespace sampleprof {
43bool FunctionSamples::ProfileIsProbeBased = false;
44bool FunctionSamples::ProfileIsCS = false;
45bool FunctionSamples::ProfileIsPreInlined = false;
46bool FunctionSamples::UseMD5 = false;
47bool FunctionSamples::HasUniqSuffix = true;
48bool FunctionSamples::ProfileIsFS = false;
49} // namespace sampleprof
50} // namespace llvm
51
52namespace {
53
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.
57class SampleProfErrorCategoryType : public std::error_category {
58const char *name() const noexcept override { return "llvm.sampleprof"; }
59
60std::string message(int IE) const override {
61sampleprof_error E = static_cast<sampleprof_error>(IE);
62switch (E) {
63case sampleprof_error::success:
64return "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";
93}
94llvm_unreachable("A value of sampleprof_error has no message.");
95}
96};
97
98} // end anonymous namespace
99
100const std::error_category &llvm::sampleprof_category() {
101static SampleProfErrorCategoryType ErrorCategory;
102return ErrorCategory;
103}
104
105void LineLocation::print(raw_ostream &OS) const {
106OS << LineOffset;
107if (Discriminator > 0)
108OS << "." << Discriminator;
109}
110
111raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
112const LineLocation &Loc) {
113Loc.print(OS);
114return OS;
115}
116
117/// Merge the samples in \p Other into this record.
118/// Optionally scale sample counts by \p Weight.
119sampleprof_error SampleRecord::merge(const SampleRecord &Other,
120uint64_t Weight) {
121sampleprof_error Result;
122Result = addSamples(Other.getSamples(), Weight);
123for (const auto &I : Other.getCallTargets()) {
124mergeSampleProfErrors(Result, addCalledTarget(I.first, I.second, Weight));
125}
126return Result;
127}
128
129#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
130LLVM_DUMP_METHOD void LineLocation::dump() const { print(dbgs()); }
131#endif
132
133/// Print the sample record to the stream \p OS indented by \p Indent.
134void SampleRecord::print(raw_ostream &OS, unsigned Indent) const {
135OS << NumSamples;
136if (hasCalls()) {
137OS << ", calls:";
138for (const auto &I : getSortedCallTargets())
139OS << " " << I.first << ":" << I.second;
140}
141OS << "\n";
142}
143
144#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
145LLVM_DUMP_METHOD void SampleRecord::dump() const { print(dbgs(), 0); }
146#endif
147
148raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
149const SampleRecord &Sample) {
150Sample.print(OS, 0);
151return OS;
152}
153
154/// Print the samples collected for a function on stream \p OS.
155void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const {
156if (getFunctionHash())
157OS << "CFG checksum " << getFunctionHash() << "\n";
158
159OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
160<< " sampled lines\n";
161
162OS.indent(Indent);
163if (!BodySamples.empty()) {
164OS << "Samples collected in the function's body {\n";
165SampleSorter<LineLocation, SampleRecord> SortedBodySamples(BodySamples);
166for (const auto &SI : SortedBodySamples.get()) {
167OS.indent(Indent + 2);
168OS << SI->first << ": " << SI->second;
169}
170OS.indent(Indent);
171OS << "}\n";
172} else {
173OS << "No samples collected in the function's body\n";
174}
175
176OS.indent(Indent);
177if (!CallsiteSamples.empty()) {
178OS << "Samples collected in inlined callsites {\n";
179SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples(
180CallsiteSamples);
181for (const auto &CS : SortedCallsiteSamples.get()) {
182for (const auto &FS : CS->second) {
183OS.indent(Indent + 2);
184OS << CS->first << ": inlined callee: " << FS.second.getFunction()
185<< ": ";
186FS.second.print(OS, Indent + 4);
187}
188}
189OS.indent(Indent);
190OS << "}\n";
191} else {
192OS << "No inlined callsites in this function\n";
193}
194}
195
196raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
197const FunctionSamples &FS) {
198FS.print(OS);
199return OS;
200}
201
202void sampleprof::sortFuncProfiles(
203const SampleProfileMap &ProfileMap,
204std::vector<NameFunctionSamples> &SortedProfiles) {
205for (const auto &I : ProfileMap) {
206SortedProfiles.push_back(std::make_pair(I.first, &I.second));
207}
208llvm::stable_sort(SortedProfiles, [](const NameFunctionSamples &A,
209const NameFunctionSamples &B) {
210if (A.second->getTotalSamples() == B.second->getTotalSamples())
211return A.second->getContext() < B.second->getContext();
212return A.second->getTotalSamples() > B.second->getTotalSamples();
213});
214}
215
216unsigned FunctionSamples::getOffset(const DILocation *DIL) {
217return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
2180xffff;
219}
220
221LineLocation FunctionSamples::getCallSiteIdentifier(const DILocation *DIL,
222bool ProfileIsFS) {
223if (FunctionSamples::ProfileIsProbeBased) {
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
227// metadata.
228return LineLocation(PseudoProbeDwarfDiscriminator::extractProbeIndex(
229DIL->getDiscriminator()),
2300);
231} else {
232unsigned Discriminator =
233ProfileIsFS ? DIL->getDiscriminator() : DIL->getBaseDiscriminator();
234return LineLocation(FunctionSamples::getOffset(DIL), Discriminator);
235}
236}
237
238const FunctionSamples *FunctionSamples::findFunctionSamples(
239const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper) const {
240assert(DIL);
241SmallVector<std::pair<LineLocation, StringRef>, 10> S;
242
243const DILocation *PrevDIL = DIL;
244for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
245// Use C++ linkage name if possible.
246StringRef Name = PrevDIL->getScope()->getSubprogram()->getLinkageName();
247if (Name.empty())
248Name = PrevDIL->getScope()->getSubprogram()->getName();
249S.emplace_back(FunctionSamples::getCallSiteIdentifier(
250DIL, FunctionSamples::ProfileIsFS),
251Name);
252PrevDIL = DIL;
253}
254
255if (S.size() == 0)
256return this;
257const FunctionSamples *FS = this;
258for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
259FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper);
260}
261return FS;
262}
263
264void FunctionSamples::findAllNames(DenseSet<FunctionId> &NameSet) const {
265NameSet.insert(getFunction());
266for (const auto &BS : BodySamples)
267for (const auto &TS : BS.second.getCallTargets())
268NameSet.insert(TS.first);
269
270for (const auto &CS : CallsiteSamples) {
271for (const auto &NameFS : CS.second) {
272NameSet.insert(NameFS.first);
273NameFS.second.findAllNames(NameSet);
274}
275}
276}
277
278const FunctionSamples *FunctionSamples::findFunctionSamplesAt(
279const LineLocation &Loc, StringRef CalleeName,
280SampleProfileReaderItaniumRemapper *Remapper) const {
281CalleeName = getCanonicalFnName(CalleeName);
282
283auto iter = CallsiteSamples.find(mapIRLocToProfileLoc(Loc));
284if (iter == CallsiteSamples.end())
285return nullptr;
286auto FS = iter->second.find(getRepInFormat(CalleeName));
287if (FS != iter->second.end())
288return &FS->second;
289if (Remapper) {
290if (auto NameInProfile = Remapper->lookUpNameInProfile(CalleeName)) {
291auto FS = iter->second.find(getRepInFormat(*NameInProfile));
292if (FS != iter->second.end())
293return &FS->second;
294}
295}
296// If we cannot find exact match of the callee name, return the FS with
297// the max total count. Only do this when CalleeName is not provided,
298// i.e., only for indirect calls.
299if (!CalleeName.empty())
300return nullptr;
301uint64_t MaxTotalSamples = 0;
302const FunctionSamples *R = nullptr;
303for (const auto &NameFS : iter->second)
304if (NameFS.second.getTotalSamples() >= MaxTotalSamples) {
305MaxTotalSamples = NameFS.second.getTotalSamples();
306R = &NameFS.second;
307}
308return R;
309}
310
311#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
312LLVM_DUMP_METHOD void FunctionSamples::dump() const { print(dbgs(), 0); }
313#endif
314
315std::error_code ProfileSymbolList::read(const uint8_t *Data,
316uint64_t ListSize) {
317const char *ListStart = reinterpret_cast<const char *>(Data);
318uint64_t Size = 0;
319uint64_t StrNum = 0;
320while (Size < ListSize && StrNum < ProfileSymbolListCutOff) {
321StringRef Str(ListStart + Size);
322add(Str);
323Size += Str.size() + 1;
324StrNum++;
325}
326if (Size != ListSize && StrNum != ProfileSymbolListCutOff)
327return sampleprof_error::malformed;
328return sampleprof_error::success;
329}
330
331void SampleContextTrimmer::trimAndMergeColdContextProfiles(
332uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext,
333uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly) {
334if (!TrimColdContext && !MergeColdContext)
335return;
336
337// Nothing to merge if sample threshold is zero
338if (ColdCountThreshold == 0)
339return;
340
341// Trimming base profiles only is mainly to honor the preinliner decsion. When
342// MergeColdContext is true preinliner decsion is not honored anyway so turn
343// off TrimBaseProfileOnly.
344if (MergeColdContext)
345TrimBaseProfileOnly = false;
346
347// Filter the cold profiles from ProfileMap and move them into a tmp
348// container
349std::vector<std::pair<hash_code, const FunctionSamples *>> ColdProfiles;
350for (const auto &I : ProfileMap) {
351const SampleContext &Context = I.second.getContext();
352const FunctionSamples &FunctionProfile = I.second;
353if (FunctionProfile.getTotalSamples() < ColdCountThreshold &&
354(!TrimBaseProfileOnly || Context.isBaseContext()))
355ColdProfiles.emplace_back(I.first, &I.second);
356}
357
358// Remove the cold profile from ProfileMap and merge them into
359// MergedProfileMap by the last K frames of context
360SampleProfileMap MergedProfileMap;
361for (const auto &I : ColdProfiles) {
362if (MergeColdContext) {
363auto MergedContext = I.second->getContext().getContextFrames();
364if (ColdContextFrameLength < MergedContext.size())
365MergedContext = MergedContext.take_back(ColdContextFrameLength);
366// Need to set MergedProfile's context here otherwise it will be lost.
367FunctionSamples &MergedProfile = MergedProfileMap.create(MergedContext);
368MergedProfile.merge(*I.second);
369}
370ProfileMap.erase(I.first);
371}
372
373// Move the merged profiles into ProfileMap;
374for (const auto &I : MergedProfileMap) {
375// Filter the cold merged profile
376if (TrimColdContext && I.second.getTotalSamples() < ColdCountThreshold &&
377ProfileMap.find(I.second.getContext()) == ProfileMap.end())
378continue;
379// Merge the profile if the original profile exists, otherwise just insert
380// as a new profile. If inserted as a new profile from MergedProfileMap, it
381// already has the right context.
382auto Ret = ProfileMap.emplace(I.second.getContext(), FunctionSamples());
383FunctionSamples &OrigProfile = Ret.first->second;
384OrigProfile.merge(I.second);
385}
386}
387
388std::error_code ProfileSymbolList::write(raw_ostream &OS) {
389// Sort the symbols before output. If doing compression.
390// It will make the compression much more effective.
391std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
392llvm::sort(SortedList);
393
394std::string OutputString;
395for (auto &Sym : SortedList) {
396OutputString.append(Sym.str());
397OutputString.append(1, '\0');
398}
399
400OS << OutputString;
401return sampleprof_error::success;
402}
403
404void ProfileSymbolList::dump(raw_ostream &OS) const {
405OS << "======== Dump profile symbol list ========\n";
406std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
407llvm::sort(SortedList);
408
409for (auto &Sym : SortedList)
410OS << Sym << "\n";
411}
412
413ProfileConverter::FrameNode *
414ProfileConverter::FrameNode::getOrCreateChildFrame(const LineLocation &CallSite,
415FunctionId CalleeName) {
416uint64_t Hash = FunctionSamples::getCallSiteHash(CalleeName, CallSite);
417auto It = AllChildFrames.find(Hash);
418if (It != AllChildFrames.end()) {
419assert(It->second.FuncName == CalleeName &&
420"Hash collision for child context node");
421return &It->second;
422}
423
424AllChildFrames[Hash] = FrameNode(CalleeName, nullptr, CallSite);
425return &AllChildFrames[Hash];
426}
427
428ProfileConverter::ProfileConverter(SampleProfileMap &Profiles)
429: ProfileMap(Profiles) {
430for (auto &FuncSample : Profiles) {
431FunctionSamples *FSamples = &FuncSample.second;
432auto *NewNode = getOrCreateContextPath(FSamples->getContext());
433assert(!NewNode->FuncSamples && "New node cannot have sample profile");
434NewNode->FuncSamples = FSamples;
435}
436}
437
438ProfileConverter::FrameNode *
439ProfileConverter::getOrCreateContextPath(const SampleContext &Context) {
440auto Node = &RootFrame;
441LineLocation CallSiteLoc(0, 0);
442for (auto &Callsite : Context.getContextFrames()) {
443Node = Node->getOrCreateChildFrame(CallSiteLoc, Callsite.Func);
444CallSiteLoc = Callsite.Location;
445}
446return Node;
447}
448
449void ProfileConverter::convertCSProfiles(ProfileConverter::FrameNode &Node) {
450// Process each child profile. Add each child profile to callsite profile map
451// of the current node `Node` if `Node` comes with a profile. Otherwise
452// promote the child profile to a standalone profile.
453auto *NodeProfile = Node.FuncSamples;
454for (auto &It : Node.AllChildFrames) {
455auto &ChildNode = It.second;
456convertCSProfiles(ChildNode);
457auto *ChildProfile = ChildNode.FuncSamples;
458if (!ChildProfile)
459continue;
460SampleContext OrigChildContext = ChildProfile->getContext();
461uint64_t OrigChildContextHash = OrigChildContext.getHashCode();
462// Reset the child context to be contextless.
463ChildProfile->getContext().setFunction(OrigChildContext.getFunction());
464if (NodeProfile) {
465// Add child profile to the callsite profile map.
466auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
467SamplesMap.emplace(OrigChildContext.getFunction(), *ChildProfile);
468NodeProfile->addTotalSamples(ChildProfile->getTotalSamples());
469// Remove the corresponding body sample for the callsite and update the
470// total weight.
471auto Count = NodeProfile->removeCalledTargetAndBodySample(
472ChildNode.CallSiteLoc.LineOffset, ChildNode.CallSiteLoc.Discriminator,
473OrigChildContext.getFunction());
474NodeProfile->removeTotalSamples(Count);
475}
476
477uint64_t NewChildProfileHash = 0;
478// Separate child profile to be a standalone profile, if the current parent
479// profile doesn't exist. This is a duplicating operation when the child
480// profile is already incorporated into the parent which is still useful and
481// thus done optionally. It is seen that duplicating context profiles into
482// base profiles improves the code quality for thinlto build by allowing a
483// profile in the prelink phase for to-be-fully-inlined functions.
484if (!NodeProfile) {
485ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
486NewChildProfileHash = ChildProfile->getContext().getHashCode();
487} else if (GenerateMergedBaseProfiles) {
488ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
489NewChildProfileHash = ChildProfile->getContext().getHashCode();
490auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
491SamplesMap[ChildProfile->getFunction()].getContext().setAttribute(
492ContextDuplicatedIntoBase);
493}
494
495// Remove the original child profile. Check if MD5 of new child profile
496// collides with old profile, in this case the [] operator already
497// overwritten it without the need of erase.
498if (NewChildProfileHash != OrigChildContextHash)
499ProfileMap.erase(OrigChildContextHash);
500}
501}
502
503void ProfileConverter::convertCSProfiles() { convertCSProfiles(RootFrame); }
504