1*0b57cec5SDimitry Andric //=-- SampleProf.cpp - Sample profiling format support --------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file contains common definitions used in the reading and writing of
10*0b57cec5SDimitry Andric // sample profile data.
11*0b57cec5SDimitry Andric //
12*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13*0b57cec5SDimitry Andric 
14*0b57cec5SDimitry Andric #include "llvm/ProfileData/SampleProf.h"
15*0b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
16*0b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
17e8d8bef9SDimitry Andric #include "llvm/IR/PseudoProbe.h"
18e8d8bef9SDimitry Andric #include "llvm/ProfileData/SampleProfReader.h"
19fe6060f1SDimitry Andric #include "llvm/Support/CommandLine.h"
20*0b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
21*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
228bcb0991SDimitry Andric #include "llvm/Support/Error.h"
23*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
248bcb0991SDimitry Andric #include "llvm/Support/LEB128.h"
25*0b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
26*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
27*0b57cec5SDimitry Andric #include <string>
28*0b57cec5SDimitry Andric #include <system_error>
29*0b57cec5SDimitry Andric 
30*0b57cec5SDimitry Andric using namespace llvm;
31*0b57cec5SDimitry Andric using namespace sampleprof;
32*0b57cec5SDimitry Andric 
33fe6060f1SDimitry Andric static cl::opt<uint64_t> ProfileSymbolListCutOff(
34fe6060f1SDimitry Andric     "profile-symbol-list-cutoff", cl::Hidden, cl::init(-1), cl::ZeroOrMore,
35fe6060f1SDimitry Andric     cl::desc("Cutoff value about how many symbols in profile symbol list "
36fe6060f1SDimitry Andric              "will be used. This is very useful for performance debugging"));
37fe6060f1SDimitry Andric 
380eae32dcSDimitry Andric cl::opt<bool> GenerateMergedBaseProfiles(
390eae32dcSDimitry Andric     "generate-merged-base-profiles", cl::init(true), cl::ZeroOrMore,
400eae32dcSDimitry Andric     cl::desc("When generating nested context-sensitive profiles, always "
410eae32dcSDimitry Andric              "generate extra base profile for function with all its context "
420eae32dcSDimitry Andric              "profiles merged into it."));
430eae32dcSDimitry Andric 
44*0b57cec5SDimitry Andric namespace llvm {
45*0b57cec5SDimitry Andric namespace sampleprof {
46*0b57cec5SDimitry Andric SampleProfileFormat FunctionSamples::Format;
47e8d8bef9SDimitry Andric bool FunctionSamples::ProfileIsProbeBased = false;
480eae32dcSDimitry Andric bool FunctionSamples::ProfileIsCSFlat = false;
490eae32dcSDimitry Andric bool FunctionSamples::ProfileIsCSNested = false;
50fe6060f1SDimitry Andric bool FunctionSamples::UseMD5 = false;
51fe6060f1SDimitry Andric bool FunctionSamples::HasUniqSuffix = true;
52fe6060f1SDimitry Andric bool FunctionSamples::ProfileIsFS = false;
53*0b57cec5SDimitry Andric } // namespace sampleprof
54*0b57cec5SDimitry Andric } // namespace llvm
55*0b57cec5SDimitry Andric 
56*0b57cec5SDimitry Andric namespace {
57*0b57cec5SDimitry Andric 
58*0b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
59*0b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
60*0b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
61*0b57cec5SDimitry Andric class SampleProfErrorCategoryType : public std::error_category {
62*0b57cec5SDimitry Andric   const char *name() const noexcept override { return "llvm.sampleprof"; }
63*0b57cec5SDimitry Andric 
64*0b57cec5SDimitry Andric   std::string message(int IE) const override {
65*0b57cec5SDimitry Andric     sampleprof_error E = static_cast<sampleprof_error>(IE);
66*0b57cec5SDimitry Andric     switch (E) {
67*0b57cec5SDimitry Andric     case sampleprof_error::success:
68*0b57cec5SDimitry Andric       return "Success";
69*0b57cec5SDimitry Andric     case sampleprof_error::bad_magic:
70*0b57cec5SDimitry Andric       return "Invalid sample profile data (bad magic)";
71*0b57cec5SDimitry Andric     case sampleprof_error::unsupported_version:
72*0b57cec5SDimitry Andric       return "Unsupported sample profile format version";
73*0b57cec5SDimitry Andric     case sampleprof_error::too_large:
74*0b57cec5SDimitry Andric       return "Too much profile data";
75*0b57cec5SDimitry Andric     case sampleprof_error::truncated:
76*0b57cec5SDimitry Andric       return "Truncated profile data";
77*0b57cec5SDimitry Andric     case sampleprof_error::malformed:
78*0b57cec5SDimitry Andric       return "Malformed sample profile data";
79*0b57cec5SDimitry Andric     case sampleprof_error::unrecognized_format:
80*0b57cec5SDimitry Andric       return "Unrecognized sample profile encoding format";
81*0b57cec5SDimitry Andric     case sampleprof_error::unsupported_writing_format:
82*0b57cec5SDimitry Andric       return "Profile encoding format unsupported for writing operations";
83*0b57cec5SDimitry Andric     case sampleprof_error::truncated_name_table:
84*0b57cec5SDimitry Andric       return "Truncated function name table";
85*0b57cec5SDimitry Andric     case sampleprof_error::not_implemented:
86*0b57cec5SDimitry Andric       return "Unimplemented feature";
87*0b57cec5SDimitry Andric     case sampleprof_error::counter_overflow:
88*0b57cec5SDimitry Andric       return "Counter overflow";
89*0b57cec5SDimitry Andric     case sampleprof_error::ostream_seek_unsupported:
90*0b57cec5SDimitry Andric       return "Ostream does not support seek";
918bcb0991SDimitry Andric     case sampleprof_error::compress_failed:
928bcb0991SDimitry Andric       return "Compress failure";
938bcb0991SDimitry Andric     case sampleprof_error::uncompress_failed:
948bcb0991SDimitry Andric       return "Uncompress failure";
958bcb0991SDimitry Andric     case sampleprof_error::zlib_unavailable:
968bcb0991SDimitry Andric       return "Zlib is unavailable";
97e8d8bef9SDimitry Andric     case sampleprof_error::hash_mismatch:
98e8d8bef9SDimitry Andric       return "Function hash mismatch";
99*0b57cec5SDimitry Andric     }
100*0b57cec5SDimitry Andric     llvm_unreachable("A value of sampleprof_error has no message.");
101*0b57cec5SDimitry Andric   }
102*0b57cec5SDimitry Andric };
103*0b57cec5SDimitry Andric 
104*0b57cec5SDimitry Andric } // end anonymous namespace
105*0b57cec5SDimitry Andric 
106*0b57cec5SDimitry Andric static ManagedStatic<SampleProfErrorCategoryType> ErrorCategory;
107*0b57cec5SDimitry Andric 
108*0b57cec5SDimitry Andric const std::error_category &llvm::sampleprof_category() {
109*0b57cec5SDimitry Andric   return *ErrorCategory;
110*0b57cec5SDimitry Andric }
111*0b57cec5SDimitry Andric 
112*0b57cec5SDimitry Andric void LineLocation::print(raw_ostream &OS) const {
113*0b57cec5SDimitry Andric   OS << LineOffset;
114*0b57cec5SDimitry Andric   if (Discriminator > 0)
115*0b57cec5SDimitry Andric     OS << "." << Discriminator;
116*0b57cec5SDimitry Andric }
117*0b57cec5SDimitry Andric 
118*0b57cec5SDimitry Andric raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
119*0b57cec5SDimitry Andric                                           const LineLocation &Loc) {
120*0b57cec5SDimitry Andric   Loc.print(OS);
121*0b57cec5SDimitry Andric   return OS;
122*0b57cec5SDimitry Andric }
123*0b57cec5SDimitry Andric 
124fe6060f1SDimitry Andric /// Merge the samples in \p Other into this record.
125fe6060f1SDimitry Andric /// Optionally scale sample counts by \p Weight.
126fe6060f1SDimitry Andric sampleprof_error SampleRecord::merge(const SampleRecord &Other,
127fe6060f1SDimitry Andric                                      uint64_t Weight) {
128fe6060f1SDimitry Andric   sampleprof_error Result;
129fe6060f1SDimitry Andric   Result = addSamples(Other.getSamples(), Weight);
130fe6060f1SDimitry Andric   for (const auto &I : Other.getCallTargets()) {
131fe6060f1SDimitry Andric     MergeResult(Result, addCalledTarget(I.first(), I.second, Weight));
132fe6060f1SDimitry Andric   }
133fe6060f1SDimitry Andric   return Result;
134fe6060f1SDimitry Andric }
135fe6060f1SDimitry Andric 
136*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
137*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void LineLocation::dump() const { print(dbgs()); }
138*0b57cec5SDimitry Andric #endif
139*0b57cec5SDimitry Andric 
140*0b57cec5SDimitry Andric /// Print the sample record to the stream \p OS indented by \p Indent.
141*0b57cec5SDimitry Andric void SampleRecord::print(raw_ostream &OS, unsigned Indent) const {
142*0b57cec5SDimitry Andric   OS << NumSamples;
143*0b57cec5SDimitry Andric   if (hasCalls()) {
144*0b57cec5SDimitry Andric     OS << ", calls:";
1458bcb0991SDimitry Andric     for (const auto &I : getSortedCallTargets())
1468bcb0991SDimitry Andric       OS << " " << I.first << ":" << I.second;
147*0b57cec5SDimitry Andric   }
148*0b57cec5SDimitry Andric   OS << "\n";
149*0b57cec5SDimitry Andric }
150*0b57cec5SDimitry Andric 
151*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
152*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void SampleRecord::dump() const { print(dbgs(), 0); }
153*0b57cec5SDimitry Andric #endif
154*0b57cec5SDimitry Andric 
155*0b57cec5SDimitry Andric raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
156*0b57cec5SDimitry Andric                                           const SampleRecord &Sample) {
157*0b57cec5SDimitry Andric   Sample.print(OS, 0);
158*0b57cec5SDimitry Andric   return OS;
159*0b57cec5SDimitry Andric }
160*0b57cec5SDimitry Andric 
161*0b57cec5SDimitry Andric /// Print the samples collected for a function on stream \p OS.
162*0b57cec5SDimitry Andric void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const {
163e8d8bef9SDimitry Andric   if (getFunctionHash())
164e8d8bef9SDimitry Andric     OS << "CFG checksum " << getFunctionHash() << "\n";
165e8d8bef9SDimitry Andric 
166*0b57cec5SDimitry Andric   OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
167*0b57cec5SDimitry Andric      << " sampled lines\n";
168*0b57cec5SDimitry Andric 
169*0b57cec5SDimitry Andric   OS.indent(Indent);
170*0b57cec5SDimitry Andric   if (!BodySamples.empty()) {
171*0b57cec5SDimitry Andric     OS << "Samples collected in the function's body {\n";
172*0b57cec5SDimitry Andric     SampleSorter<LineLocation, SampleRecord> SortedBodySamples(BodySamples);
173*0b57cec5SDimitry Andric     for (const auto &SI : SortedBodySamples.get()) {
174*0b57cec5SDimitry Andric       OS.indent(Indent + 2);
175*0b57cec5SDimitry Andric       OS << SI->first << ": " << SI->second;
176*0b57cec5SDimitry Andric     }
177*0b57cec5SDimitry Andric     OS.indent(Indent);
178*0b57cec5SDimitry Andric     OS << "}\n";
179*0b57cec5SDimitry Andric   } else {
180*0b57cec5SDimitry Andric     OS << "No samples collected in the function's body\n";
181*0b57cec5SDimitry Andric   }
182*0b57cec5SDimitry Andric 
183*0b57cec5SDimitry Andric   OS.indent(Indent);
184*0b57cec5SDimitry Andric   if (!CallsiteSamples.empty()) {
185*0b57cec5SDimitry Andric     OS << "Samples collected in inlined callsites {\n";
186*0b57cec5SDimitry Andric     SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples(
187*0b57cec5SDimitry Andric         CallsiteSamples);
188*0b57cec5SDimitry Andric     for (const auto &CS : SortedCallsiteSamples.get()) {
189*0b57cec5SDimitry Andric       for (const auto &FS : CS->second) {
190*0b57cec5SDimitry Andric         OS.indent(Indent + 2);
191*0b57cec5SDimitry Andric         OS << CS->first << ": inlined callee: " << FS.second.getName() << ": ";
192*0b57cec5SDimitry Andric         FS.second.print(OS, Indent + 4);
193*0b57cec5SDimitry Andric       }
194*0b57cec5SDimitry Andric     }
1958bcb0991SDimitry Andric     OS.indent(Indent);
196*0b57cec5SDimitry Andric     OS << "}\n";
197*0b57cec5SDimitry Andric   } else {
198*0b57cec5SDimitry Andric     OS << "No inlined callsites in this function\n";
199*0b57cec5SDimitry Andric   }
200*0b57cec5SDimitry Andric }
201*0b57cec5SDimitry Andric 
202*0b57cec5SDimitry Andric raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
203*0b57cec5SDimitry Andric                                           const FunctionSamples &FS) {
204*0b57cec5SDimitry Andric   FS.print(OS);
205*0b57cec5SDimitry Andric   return OS;
206*0b57cec5SDimitry Andric }
207*0b57cec5SDimitry Andric 
208349cc55cSDimitry Andric void sampleprof::sortFuncProfiles(
209349cc55cSDimitry Andric     const SampleProfileMap &ProfileMap,
210349cc55cSDimitry Andric     std::vector<NameFunctionSamples> &SortedProfiles) {
211349cc55cSDimitry Andric   for (const auto &I : ProfileMap) {
212349cc55cSDimitry Andric     assert(I.first == I.second.getContext() && "Inconsistent profile map");
213349cc55cSDimitry Andric     SortedProfiles.push_back(std::make_pair(I.second.getContext(), &I.second));
214349cc55cSDimitry Andric   }
215349cc55cSDimitry Andric   llvm::stable_sort(SortedProfiles, [](const NameFunctionSamples &A,
216349cc55cSDimitry Andric                                        const NameFunctionSamples &B) {
217349cc55cSDimitry Andric     if (A.second->getTotalSamples() == B.second->getTotalSamples())
218349cc55cSDimitry Andric       return A.first < B.first;
219349cc55cSDimitry Andric     return A.second->getTotalSamples() > B.second->getTotalSamples();
220349cc55cSDimitry Andric   });
221349cc55cSDimitry Andric }
222349cc55cSDimitry Andric 
223*0b57cec5SDimitry Andric unsigned FunctionSamples::getOffset(const DILocation *DIL) {
224*0b57cec5SDimitry Andric   return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
225*0b57cec5SDimitry Andric       0xffff;
226*0b57cec5SDimitry Andric }
227*0b57cec5SDimitry Andric 
2280eae32dcSDimitry Andric LineLocation FunctionSamples::getCallSiteIdentifier(const DILocation *DIL,
2290eae32dcSDimitry Andric                                                     bool ProfileIsFS) {
2300eae32dcSDimitry Andric   if (FunctionSamples::ProfileIsProbeBased) {
231e8d8bef9SDimitry Andric     // In a pseudo-probe based profile, a callsite is simply represented by the
232e8d8bef9SDimitry Andric     // ID of the probe associated with the call instruction. The probe ID is
233e8d8bef9SDimitry Andric     // encoded in the Discriminator field of the call instruction's debug
234e8d8bef9SDimitry Andric     // metadata.
235e8d8bef9SDimitry Andric     return LineLocation(PseudoProbeDwarfDiscriminator::extractProbeIndex(
236e8d8bef9SDimitry Andric                             DIL->getDiscriminator()),
237e8d8bef9SDimitry Andric                         0);
2380eae32dcSDimitry Andric   } else {
2390eae32dcSDimitry Andric     unsigned Discriminator =
2400eae32dcSDimitry Andric         ProfileIsFS ? DIL->getDiscriminator() : DIL->getBaseDiscriminator();
2410eae32dcSDimitry Andric     return LineLocation(FunctionSamples::getOffset(DIL), Discriminator);
2420eae32dcSDimitry Andric   }
2430eae32dcSDimitry Andric }
2440eae32dcSDimitry Andric 
2450eae32dcSDimitry Andric uint64_t FunctionSamples::getCallSiteHash(StringRef CalleeName,
2460eae32dcSDimitry Andric                                           const LineLocation &Callsite) {
2470eae32dcSDimitry Andric   uint64_t NameHash = std::hash<std::string>{}(CalleeName.str());
2480eae32dcSDimitry Andric   uint64_t LocId =
2490eae32dcSDimitry Andric       (((uint64_t)Callsite.LineOffset) << 32) | Callsite.Discriminator;
2500eae32dcSDimitry Andric   return NameHash + (LocId << 5) + LocId;
251e8d8bef9SDimitry Andric }
252e8d8bef9SDimitry Andric 
253e8d8bef9SDimitry Andric const FunctionSamples *FunctionSamples::findFunctionSamples(
254e8d8bef9SDimitry Andric     const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper) const {
255*0b57cec5SDimitry Andric   assert(DIL);
256*0b57cec5SDimitry Andric   SmallVector<std::pair<LineLocation, StringRef>, 10> S;
257*0b57cec5SDimitry Andric 
258*0b57cec5SDimitry Andric   const DILocation *PrevDIL = DIL;
259*0b57cec5SDimitry Andric   for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
260349cc55cSDimitry Andric     // Use C++ linkage name if possible.
261349cc55cSDimitry Andric     StringRef Name = PrevDIL->getScope()->getSubprogram()->getLinkageName();
262349cc55cSDimitry Andric     if (Name.empty())
263349cc55cSDimitry Andric       Name = PrevDIL->getScope()->getSubprogram()->getName();
2640eae32dcSDimitry Andric     S.emplace_back(FunctionSamples::getCallSiteIdentifier(
2650eae32dcSDimitry Andric                        DIL, FunctionSamples::ProfileIsFS),
2660eae32dcSDimitry Andric                    Name);
267*0b57cec5SDimitry Andric     PrevDIL = DIL;
268*0b57cec5SDimitry Andric   }
2690eae32dcSDimitry Andric 
270*0b57cec5SDimitry Andric   if (S.size() == 0)
271*0b57cec5SDimitry Andric     return this;
272*0b57cec5SDimitry Andric   const FunctionSamples *FS = this;
273*0b57cec5SDimitry Andric   for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
274e8d8bef9SDimitry Andric     FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper);
275*0b57cec5SDimitry Andric   }
276*0b57cec5SDimitry Andric   return FS;
277*0b57cec5SDimitry Andric }
278*0b57cec5SDimitry Andric 
279e8d8bef9SDimitry Andric void FunctionSamples::findAllNames(DenseSet<StringRef> &NameSet) const {
280349cc55cSDimitry Andric   NameSet.insert(getName());
281e8d8bef9SDimitry Andric   for (const auto &BS : BodySamples)
282e8d8bef9SDimitry Andric     for (const auto &TS : BS.second.getCallTargets())
283e8d8bef9SDimitry Andric       NameSet.insert(TS.getKey());
284e8d8bef9SDimitry Andric 
285e8d8bef9SDimitry Andric   for (const auto &CS : CallsiteSamples) {
286e8d8bef9SDimitry Andric     for (const auto &NameFS : CS.second) {
287e8d8bef9SDimitry Andric       NameSet.insert(NameFS.first);
288e8d8bef9SDimitry Andric       NameFS.second.findAllNames(NameSet);
289e8d8bef9SDimitry Andric     }
290e8d8bef9SDimitry Andric   }
291e8d8bef9SDimitry Andric }
292e8d8bef9SDimitry Andric 
293e8d8bef9SDimitry Andric const FunctionSamples *FunctionSamples::findFunctionSamplesAt(
294e8d8bef9SDimitry Andric     const LineLocation &Loc, StringRef CalleeName,
295e8d8bef9SDimitry Andric     SampleProfileReaderItaniumRemapper *Remapper) const {
296fe6060f1SDimitry Andric   CalleeName = getCanonicalFnName(CalleeName);
297fe6060f1SDimitry Andric 
298e8d8bef9SDimitry Andric   std::string CalleeGUID;
299e8d8bef9SDimitry Andric   CalleeName = getRepInFormat(CalleeName, UseMD5, CalleeGUID);
300e8d8bef9SDimitry Andric 
301e8d8bef9SDimitry Andric   auto iter = CallsiteSamples.find(Loc);
302e8d8bef9SDimitry Andric   if (iter == CallsiteSamples.end())
303e8d8bef9SDimitry Andric     return nullptr;
304e8d8bef9SDimitry Andric   auto FS = iter->second.find(CalleeName);
305e8d8bef9SDimitry Andric   if (FS != iter->second.end())
306e8d8bef9SDimitry Andric     return &FS->second;
307e8d8bef9SDimitry Andric   if (Remapper) {
308e8d8bef9SDimitry Andric     if (auto NameInProfile = Remapper->lookUpNameInProfile(CalleeName)) {
309e8d8bef9SDimitry Andric       auto FS = iter->second.find(*NameInProfile);
310e8d8bef9SDimitry Andric       if (FS != iter->second.end())
311e8d8bef9SDimitry Andric         return &FS->second;
312e8d8bef9SDimitry Andric     }
313e8d8bef9SDimitry Andric   }
314e8d8bef9SDimitry Andric   // If we cannot find exact match of the callee name, return the FS with
315e8d8bef9SDimitry Andric   // the max total count. Only do this when CalleeName is not provided,
316e8d8bef9SDimitry Andric   // i.e., only for indirect calls.
317e8d8bef9SDimitry Andric   if (!CalleeName.empty())
318e8d8bef9SDimitry Andric     return nullptr;
319e8d8bef9SDimitry Andric   uint64_t MaxTotalSamples = 0;
320e8d8bef9SDimitry Andric   const FunctionSamples *R = nullptr;
321e8d8bef9SDimitry Andric   for (const auto &NameFS : iter->second)
322e8d8bef9SDimitry Andric     if (NameFS.second.getTotalSamples() >= MaxTotalSamples) {
323e8d8bef9SDimitry Andric       MaxTotalSamples = NameFS.second.getTotalSamples();
324e8d8bef9SDimitry Andric       R = &NameFS.second;
325e8d8bef9SDimitry Andric     }
326e8d8bef9SDimitry Andric   return R;
327e8d8bef9SDimitry Andric }
328e8d8bef9SDimitry Andric 
329*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
330*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void FunctionSamples::dump() const { print(dbgs(), 0); }
331*0b57cec5SDimitry Andric #endif
3328bcb0991SDimitry Andric 
3338bcb0991SDimitry Andric std::error_code ProfileSymbolList::read(const uint8_t *Data,
3348bcb0991SDimitry Andric                                         uint64_t ListSize) {
3358bcb0991SDimitry Andric   const char *ListStart = reinterpret_cast<const char *>(Data);
3368bcb0991SDimitry Andric   uint64_t Size = 0;
337fe6060f1SDimitry Andric   uint64_t StrNum = 0;
338fe6060f1SDimitry Andric   while (Size < ListSize && StrNum < ProfileSymbolListCutOff) {
3398bcb0991SDimitry Andric     StringRef Str(ListStart + Size);
3408bcb0991SDimitry Andric     add(Str);
3418bcb0991SDimitry Andric     Size += Str.size() + 1;
342fe6060f1SDimitry Andric     StrNum++;
3438bcb0991SDimitry Andric   }
344fe6060f1SDimitry Andric   if (Size != ListSize && StrNum != ProfileSymbolListCutOff)
3458bcb0991SDimitry Andric     return sampleprof_error::malformed;
3468bcb0991SDimitry Andric   return sampleprof_error::success;
3478bcb0991SDimitry Andric }
3488bcb0991SDimitry Andric 
349fe6060f1SDimitry Andric void SampleContextTrimmer::trimAndMergeColdContextProfiles(
350fe6060f1SDimitry Andric     uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext,
351349cc55cSDimitry Andric     uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly) {
352fe6060f1SDimitry Andric   if (!TrimColdContext && !MergeColdContext)
353fe6060f1SDimitry Andric     return;
354fe6060f1SDimitry Andric 
355fe6060f1SDimitry Andric   // Nothing to merge if sample threshold is zero
356fe6060f1SDimitry Andric   if (ColdCountThreshold == 0)
357fe6060f1SDimitry Andric     return;
358fe6060f1SDimitry Andric 
359349cc55cSDimitry Andric   // Trimming base profiles only is mainly to honor the preinliner decsion. When
360349cc55cSDimitry Andric   // MergeColdContext is true preinliner decsion is not honored anyway so turn
361349cc55cSDimitry Andric   // off TrimBaseProfileOnly.
362349cc55cSDimitry Andric   if (MergeColdContext)
363349cc55cSDimitry Andric     TrimBaseProfileOnly = false;
364349cc55cSDimitry Andric 
365fe6060f1SDimitry Andric   // Filter the cold profiles from ProfileMap and move them into a tmp
366fe6060f1SDimitry Andric   // container
367349cc55cSDimitry Andric   std::vector<std::pair<SampleContext, const FunctionSamples *>> ColdProfiles;
368fe6060f1SDimitry Andric   for (const auto &I : ProfileMap) {
369349cc55cSDimitry Andric     const SampleContext &Context = I.first;
370fe6060f1SDimitry Andric     const FunctionSamples &FunctionProfile = I.second;
371349cc55cSDimitry Andric     if (FunctionProfile.getTotalSamples() < ColdCountThreshold &&
372349cc55cSDimitry Andric         (!TrimBaseProfileOnly || Context.isBaseContext()))
373349cc55cSDimitry Andric       ColdProfiles.emplace_back(Context, &I.second);
374fe6060f1SDimitry Andric   }
375fe6060f1SDimitry Andric 
376fe6060f1SDimitry Andric   // Remove the cold profile from ProfileMap and merge them into
377fe6060f1SDimitry Andric   // MergedProfileMap by the last K frames of context
378349cc55cSDimitry Andric   SampleProfileMap MergedProfileMap;
379fe6060f1SDimitry Andric   for (const auto &I : ColdProfiles) {
380fe6060f1SDimitry Andric     if (MergeColdContext) {
381349cc55cSDimitry Andric       auto MergedContext = I.second->getContext().getContextFrames();
382349cc55cSDimitry Andric       if (ColdContextFrameLength < MergedContext.size())
383349cc55cSDimitry Andric         MergedContext = MergedContext.take_back(ColdContextFrameLength);
384349cc55cSDimitry Andric       auto Ret = MergedProfileMap.emplace(MergedContext, FunctionSamples());
385fe6060f1SDimitry Andric       FunctionSamples &MergedProfile = Ret.first->second;
386fe6060f1SDimitry Andric       MergedProfile.merge(*I.second);
387fe6060f1SDimitry Andric     }
388fe6060f1SDimitry Andric     ProfileMap.erase(I.first);
389fe6060f1SDimitry Andric   }
390fe6060f1SDimitry Andric 
391fe6060f1SDimitry Andric   // Move the merged profiles into ProfileMap;
392fe6060f1SDimitry Andric   for (const auto &I : MergedProfileMap) {
393fe6060f1SDimitry Andric     // Filter the cold merged profile
394fe6060f1SDimitry Andric     if (TrimColdContext && I.second.getTotalSamples() < ColdCountThreshold &&
395349cc55cSDimitry Andric         ProfileMap.find(I.first) == ProfileMap.end())
396fe6060f1SDimitry Andric       continue;
397fe6060f1SDimitry Andric     // Merge the profile if the original profile exists, otherwise just insert
398fe6060f1SDimitry Andric     // as a new profile
399349cc55cSDimitry Andric     auto Ret = ProfileMap.emplace(I.first, FunctionSamples());
400fe6060f1SDimitry Andric     if (Ret.second) {
401349cc55cSDimitry Andric       SampleContext FContext(Ret.first->first, RawContext);
402fe6060f1SDimitry Andric       FunctionSamples &FProfile = Ret.first->second;
403fe6060f1SDimitry Andric       FProfile.setContext(FContext);
404fe6060f1SDimitry Andric     }
405fe6060f1SDimitry Andric     FunctionSamples &OrigProfile = Ret.first->second;
406fe6060f1SDimitry Andric     OrigProfile.merge(I.second);
407fe6060f1SDimitry Andric   }
408fe6060f1SDimitry Andric }
409fe6060f1SDimitry Andric 
410fe6060f1SDimitry Andric void SampleContextTrimmer::canonicalizeContextProfiles() {
411349cc55cSDimitry Andric   std::vector<SampleContext> ProfilesToBeRemoved;
412349cc55cSDimitry Andric   SampleProfileMap ProfilesToBeAdded;
413fe6060f1SDimitry Andric   for (auto &I : ProfileMap) {
414fe6060f1SDimitry Andric     FunctionSamples &FProfile = I.second;
415349cc55cSDimitry Andric     SampleContext &Context = FProfile.getContext();
416349cc55cSDimitry Andric     if (I.first == Context)
417fe6060f1SDimitry Andric       continue;
418fe6060f1SDimitry Andric 
419fe6060f1SDimitry Andric     // Use the context string from FunctionSamples to update the keys of
420fe6060f1SDimitry Andric     // ProfileMap. They can get out of sync after context profile promotion
421fe6060f1SDimitry Andric     // through pre-inliner.
422fe6060f1SDimitry Andric     // Duplicate the function profile for later insertion to avoid a conflict
423fe6060f1SDimitry Andric     // caused by a context both to be add and to be removed. This could happen
424fe6060f1SDimitry Andric     // when a context is promoted to another context which is also promoted to
425fe6060f1SDimitry Andric     // the third context. For example, given an original context A @ B @ C that
426fe6060f1SDimitry Andric     // is promoted to B @ C and the original context B @ C which is promoted to
427fe6060f1SDimitry Andric     // just C, adding B @ C to the profile map while removing same context (but
428fe6060f1SDimitry Andric     // with different profiles) from the map can cause a conflict if they are
429fe6060f1SDimitry Andric     // not handled in a right order. This can be solved by just caching the
430fe6060f1SDimitry Andric     // profiles to be added.
431349cc55cSDimitry Andric     auto Ret = ProfilesToBeAdded.emplace(Context, FProfile);
432fe6060f1SDimitry Andric     (void)Ret;
433fe6060f1SDimitry Andric     assert(Ret.second && "Context conflict during canonicalization");
434349cc55cSDimitry Andric     ProfilesToBeRemoved.push_back(I.first);
435fe6060f1SDimitry Andric   }
436fe6060f1SDimitry Andric 
437fe6060f1SDimitry Andric   for (auto &I : ProfilesToBeRemoved) {
438fe6060f1SDimitry Andric     ProfileMap.erase(I);
439fe6060f1SDimitry Andric   }
440fe6060f1SDimitry Andric 
441fe6060f1SDimitry Andric   for (auto &I : ProfilesToBeAdded) {
442349cc55cSDimitry Andric     ProfileMap.emplace(I.first, I.second);
443fe6060f1SDimitry Andric   }
444fe6060f1SDimitry Andric }
445fe6060f1SDimitry Andric 
4468bcb0991SDimitry Andric std::error_code ProfileSymbolList::write(raw_ostream &OS) {
4478bcb0991SDimitry Andric   // Sort the symbols before output. If doing compression.
4488bcb0991SDimitry Andric   // It will make the compression much more effective.
449e8d8bef9SDimitry Andric   std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
4508bcb0991SDimitry Andric   llvm::sort(SortedList);
4518bcb0991SDimitry Andric 
4528bcb0991SDimitry Andric   std::string OutputString;
4538bcb0991SDimitry Andric   for (auto &Sym : SortedList) {
4548bcb0991SDimitry Andric     OutputString.append(Sym.str());
4558bcb0991SDimitry Andric     OutputString.append(1, '\0');
4568bcb0991SDimitry Andric   }
4578bcb0991SDimitry Andric 
4588bcb0991SDimitry Andric   OS << OutputString;
4598bcb0991SDimitry Andric   return sampleprof_error::success;
4608bcb0991SDimitry Andric }
4618bcb0991SDimitry Andric 
4628bcb0991SDimitry Andric void ProfileSymbolList::dump(raw_ostream &OS) const {
4638bcb0991SDimitry Andric   OS << "======== Dump profile symbol list ========\n";
464e8d8bef9SDimitry Andric   std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
4658bcb0991SDimitry Andric   llvm::sort(SortedList);
4668bcb0991SDimitry Andric 
4678bcb0991SDimitry Andric   for (auto &Sym : SortedList)
4688bcb0991SDimitry Andric     OS << Sym << "\n";
4698bcb0991SDimitry Andric }
4700eae32dcSDimitry Andric 
4710eae32dcSDimitry Andric CSProfileConverter::FrameNode *
4720eae32dcSDimitry Andric CSProfileConverter::FrameNode::getOrCreateChildFrame(
4730eae32dcSDimitry Andric     const LineLocation &CallSite, StringRef CalleeName) {
4740eae32dcSDimitry Andric   uint64_t Hash = FunctionSamples::getCallSiteHash(CalleeName, CallSite);
4750eae32dcSDimitry Andric   auto It = AllChildFrames.find(Hash);
4760eae32dcSDimitry Andric   if (It != AllChildFrames.end()) {
4770eae32dcSDimitry Andric     assert(It->second.FuncName == CalleeName &&
4780eae32dcSDimitry Andric            "Hash collision for child context node");
4790eae32dcSDimitry Andric     return &It->second;
4800eae32dcSDimitry Andric   }
4810eae32dcSDimitry Andric 
4820eae32dcSDimitry Andric   AllChildFrames[Hash] = FrameNode(CalleeName, nullptr, CallSite);
4830eae32dcSDimitry Andric   return &AllChildFrames[Hash];
4840eae32dcSDimitry Andric }
4850eae32dcSDimitry Andric 
4860eae32dcSDimitry Andric CSProfileConverter::CSProfileConverter(SampleProfileMap &Profiles)
4870eae32dcSDimitry Andric     : ProfileMap(Profiles) {
4880eae32dcSDimitry Andric   for (auto &FuncSample : Profiles) {
4890eae32dcSDimitry Andric     FunctionSamples *FSamples = &FuncSample.second;
4900eae32dcSDimitry Andric     auto *NewNode = getOrCreateContextPath(FSamples->getContext());
4910eae32dcSDimitry Andric     assert(!NewNode->FuncSamples && "New node cannot have sample profile");
4920eae32dcSDimitry Andric     NewNode->FuncSamples = FSamples;
4930eae32dcSDimitry Andric   }
4940eae32dcSDimitry Andric }
4950eae32dcSDimitry Andric 
4960eae32dcSDimitry Andric CSProfileConverter::FrameNode *
4970eae32dcSDimitry Andric CSProfileConverter::getOrCreateContextPath(const SampleContext &Context) {
4980eae32dcSDimitry Andric   auto Node = &RootFrame;
4990eae32dcSDimitry Andric   LineLocation CallSiteLoc(0, 0);
5000eae32dcSDimitry Andric   for (auto &Callsite : Context.getContextFrames()) {
5010eae32dcSDimitry Andric     Node = Node->getOrCreateChildFrame(CallSiteLoc, Callsite.FuncName);
5020eae32dcSDimitry Andric     CallSiteLoc = Callsite.Location;
5030eae32dcSDimitry Andric   }
5040eae32dcSDimitry Andric   return Node;
5050eae32dcSDimitry Andric }
5060eae32dcSDimitry Andric 
5070eae32dcSDimitry Andric void CSProfileConverter::convertProfiles(CSProfileConverter::FrameNode &Node) {
5080eae32dcSDimitry Andric   // Process each child profile. Add each child profile to callsite profile map
5090eae32dcSDimitry Andric   // of the current node `Node` if `Node` comes with a profile. Otherwise
5100eae32dcSDimitry Andric   // promote the child profile to a standalone profile.
5110eae32dcSDimitry Andric   auto *NodeProfile = Node.FuncSamples;
5120eae32dcSDimitry Andric   for (auto &It : Node.AllChildFrames) {
5130eae32dcSDimitry Andric     auto &ChildNode = It.second;
5140eae32dcSDimitry Andric     convertProfiles(ChildNode);
5150eae32dcSDimitry Andric     auto *ChildProfile = ChildNode.FuncSamples;
5160eae32dcSDimitry Andric     if (!ChildProfile)
5170eae32dcSDimitry Andric       continue;
5180eae32dcSDimitry Andric     SampleContext OrigChildContext = ChildProfile->getContext();
5190eae32dcSDimitry Andric     // Reset the child context to be contextless.
5200eae32dcSDimitry Andric     ChildProfile->getContext().setName(OrigChildContext.getName());
5210eae32dcSDimitry Andric     if (NodeProfile) {
5220eae32dcSDimitry Andric       // Add child profile to the callsite profile map.
5230eae32dcSDimitry Andric       auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
5240eae32dcSDimitry Andric       SamplesMap.emplace(OrigChildContext.getName().str(), *ChildProfile);
5250eae32dcSDimitry Andric       NodeProfile->addTotalSamples(ChildProfile->getTotalSamples());
5260eae32dcSDimitry Andric     }
5270eae32dcSDimitry Andric 
5280eae32dcSDimitry Andric     // Separate child profile to be a standalone profile, if the current parent
5290eae32dcSDimitry Andric     // profile doesn't exist. This is a duplicating operation when the child
5300eae32dcSDimitry Andric     // profile is already incorporated into the parent which is still useful and
5310eae32dcSDimitry Andric     // thus done optionally. It is seen that duplicating context profiles into
5320eae32dcSDimitry Andric     // base profiles improves the code quality for thinlto build by allowing a
5330eae32dcSDimitry Andric     // profile in the prelink phase for to-be-fully-inlined functions.
5340eae32dcSDimitry Andric     if (!NodeProfile || GenerateMergedBaseProfiles)
5350eae32dcSDimitry Andric       ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
5360eae32dcSDimitry Andric 
5370eae32dcSDimitry Andric     // Contexts coming with a `ContextShouldBeInlined` attribute indicate this
5380eae32dcSDimitry Andric     // is a preinliner-computed profile.
5390eae32dcSDimitry Andric     if (OrigChildContext.hasAttribute(ContextShouldBeInlined))
5400eae32dcSDimitry Andric       FunctionSamples::ProfileIsCSNested = true;
5410eae32dcSDimitry Andric 
5420eae32dcSDimitry Andric     // Remove the original child profile.
5430eae32dcSDimitry Andric     ProfileMap.erase(OrigChildContext);
5440eae32dcSDimitry Andric   }
5450eae32dcSDimitry Andric }
5460eae32dcSDimitry Andric 
5470eae32dcSDimitry Andric void CSProfileConverter::convertProfiles() { convertProfiles(RootFrame); }
548