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 //===----------------------------------------------------------------------===//
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/Compiler.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Error.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/LEB128.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/raw_ostream.h"
27 #include <system_error>
30 using namespace sampleprof;
33 namespace sampleprof {
34 SampleProfileFormat FunctionSamples::Format;
35 bool FunctionSamples::ProfileIsProbeBased = false;
36 bool FunctionSamples::ProfileIsCS = false;
37 bool FunctionSamples::UseMD5;
38 } // namespace sampleprof
43 // FIXME: This class is only here to support the transition to llvm::Error. It
44 // will be removed once this transition is complete. Clients should prefer to
45 // deal with the Error value directly, rather than converting to error_code.
46 class SampleProfErrorCategoryType : public std::error_category {
47 const char *name() const noexcept override { return "llvm.sampleprof"; }
49 std::string message(int IE) const override {
50 sampleprof_error E = static_cast<sampleprof_error>(IE);
52 case sampleprof_error::success:
54 case sampleprof_error::bad_magic:
55 return "Invalid sample profile data (bad magic)";
56 case sampleprof_error::unsupported_version:
57 return "Unsupported sample profile format version";
58 case sampleprof_error::too_large:
59 return "Too much profile data";
60 case sampleprof_error::truncated:
61 return "Truncated profile data";
62 case sampleprof_error::malformed:
63 return "Malformed sample profile data";
64 case sampleprof_error::unrecognized_format:
65 return "Unrecognized sample profile encoding format";
66 case sampleprof_error::unsupported_writing_format:
67 return "Profile encoding format unsupported for writing operations";
68 case sampleprof_error::truncated_name_table:
69 return "Truncated function name table";
70 case sampleprof_error::not_implemented:
71 return "Unimplemented feature";
72 case sampleprof_error::counter_overflow:
73 return "Counter overflow";
74 case sampleprof_error::ostream_seek_unsupported:
75 return "Ostream does not support seek";
76 case sampleprof_error::compress_failed:
77 return "Compress failure";
78 case sampleprof_error::uncompress_failed:
79 return "Uncompress failure";
80 case sampleprof_error::zlib_unavailable:
81 return "Zlib is unavailable";
82 case sampleprof_error::hash_mismatch:
83 return "Function hash mismatch";
85 llvm_unreachable("A value of sampleprof_error has no message.");
89 } // end anonymous namespace
91 static ManagedStatic<SampleProfErrorCategoryType> ErrorCategory;
93 const std::error_category &llvm::sampleprof_category() {
94 return *ErrorCategory;
97 void LineLocation::print(raw_ostream &OS) const {
99 if (Discriminator > 0)
100 OS << "." << Discriminator;
103 raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
104 const LineLocation &Loc) {
109 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
110 LLVM_DUMP_METHOD void LineLocation::dump() const { print(dbgs()); }
113 /// Print the sample record to the stream \p OS indented by \p Indent.
114 void SampleRecord::print(raw_ostream &OS, unsigned Indent) const {
118 for (const auto &I : getSortedCallTargets())
119 OS << " " << I.first << ":" << I.second;
124 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
125 LLVM_DUMP_METHOD void SampleRecord::dump() const { print(dbgs(), 0); }
128 raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
129 const SampleRecord &Sample) {
134 /// Print the samples collected for a function on stream \p OS.
135 void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const {
136 if (getFunctionHash())
137 OS << "CFG checksum " << getFunctionHash() << "\n";
139 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
140 << " sampled lines\n";
143 if (!BodySamples.empty()) {
144 OS << "Samples collected in the function's body {\n";
145 SampleSorter<LineLocation, SampleRecord> SortedBodySamples(BodySamples);
146 for (const auto &SI : SortedBodySamples.get()) {
147 OS.indent(Indent + 2);
148 OS << SI->first << ": " << SI->second;
153 OS << "No samples collected in the function's body\n";
157 if (!CallsiteSamples.empty()) {
158 OS << "Samples collected in inlined callsites {\n";
159 SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples(
161 for (const auto &CS : SortedCallsiteSamples.get()) {
162 for (const auto &FS : CS->second) {
163 OS.indent(Indent + 2);
164 OS << CS->first << ": inlined callee: " << FS.second.getName() << ": ";
165 FS.second.print(OS, Indent + 4);
171 OS << "No inlined callsites in this function\n";
175 raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
176 const FunctionSamples &FS) {
181 unsigned FunctionSamples::getOffset(const DILocation *DIL) {
182 return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
186 LineLocation FunctionSamples::getCallSiteIdentifier(const DILocation *DIL) {
187 if (FunctionSamples::ProfileIsProbeBased)
188 // In a pseudo-probe based profile, a callsite is simply represented by the
189 // ID of the probe associated with the call instruction. The probe ID is
190 // encoded in the Discriminator field of the call instruction's debug
192 return LineLocation(PseudoProbeDwarfDiscriminator::extractProbeIndex(
193 DIL->getDiscriminator()),
196 return LineLocation(FunctionSamples::getOffset(DIL),
197 DIL->getBaseDiscriminator());
200 const FunctionSamples *FunctionSamples::findFunctionSamples(
201 const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper) const {
203 SmallVector<std::pair<LineLocation, StringRef>, 10> S;
205 const DILocation *PrevDIL = DIL;
206 for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
207 S.push_back(std::make_pair(
208 LineLocation(getOffset(DIL), DIL->getBaseDiscriminator()),
209 PrevDIL->getScope()->getSubprogram()->getLinkageName()));
214 const FunctionSamples *FS = this;
215 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
216 FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper);
221 void FunctionSamples::findAllNames(DenseSet<StringRef> &NameSet) const {
222 NameSet.insert(Name);
223 for (const auto &BS : BodySamples)
224 for (const auto &TS : BS.second.getCallTargets())
225 NameSet.insert(TS.getKey());
227 for (const auto &CS : CallsiteSamples) {
228 for (const auto &NameFS : CS.second) {
229 NameSet.insert(NameFS.first);
230 NameFS.second.findAllNames(NameSet);
235 const FunctionSamples *FunctionSamples::findFunctionSamplesAt(
236 const LineLocation &Loc, StringRef CalleeName,
237 SampleProfileReaderItaniumRemapper *Remapper) const {
238 std::string CalleeGUID;
239 CalleeName = getRepInFormat(CalleeName, UseMD5, CalleeGUID);
241 auto iter = CallsiteSamples.find(Loc);
242 if (iter == CallsiteSamples.end())
244 auto FS = iter->second.find(CalleeName);
245 if (FS != iter->second.end())
248 if (auto NameInProfile = Remapper->lookUpNameInProfile(CalleeName)) {
249 auto FS = iter->second.find(*NameInProfile);
250 if (FS != iter->second.end())
254 // If we cannot find exact match of the callee name, return the FS with
255 // the max total count. Only do this when CalleeName is not provided,
256 // i.e., only for indirect calls.
257 if (!CalleeName.empty())
259 uint64_t MaxTotalSamples = 0;
260 const FunctionSamples *R = nullptr;
261 for (const auto &NameFS : iter->second)
262 if (NameFS.second.getTotalSamples() >= MaxTotalSamples) {
263 MaxTotalSamples = NameFS.second.getTotalSamples();
269 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
270 LLVM_DUMP_METHOD void FunctionSamples::dump() const { print(dbgs(), 0); }
273 std::error_code ProfileSymbolList::read(const uint8_t *Data,
275 const char *ListStart = reinterpret_cast<const char *>(Data);
277 while (Size < ListSize) {
278 StringRef Str(ListStart + Size);
280 Size += Str.size() + 1;
282 if (Size != ListSize)
283 return sampleprof_error::malformed;
284 return sampleprof_error::success;
287 std::error_code ProfileSymbolList::write(raw_ostream &OS) {
288 // Sort the symbols before output. If doing compression.
289 // It will make the compression much more effective.
290 std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
291 llvm::sort(SortedList);
293 std::string OutputString;
294 for (auto &Sym : SortedList) {
295 OutputString.append(Sym.str());
296 OutputString.append(1, '\0');
300 return sampleprof_error::success;
303 void ProfileSymbolList::dump(raw_ostream &OS) const {
304 OS << "======== Dump profile symbol list ========\n";
305 std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
306 llvm::sort(SortedList);
308 for (auto &Sym : SortedList)