1c572e92cSDiego Novillo //=-- SampleProf.cpp - Sample profiling format support --------------------===//
2c572e92cSDiego Novillo //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c572e92cSDiego Novillo //
7c572e92cSDiego Novillo //===----------------------------------------------------------------------===//
8c572e92cSDiego Novillo //
9c572e92cSDiego Novillo // This file contains common definitions used in the reading and writing of
10c572e92cSDiego Novillo // sample profile data.
11c572e92cSDiego Novillo //
12c572e92cSDiego Novillo //===----------------------------------------------------------------------===//
13c572e92cSDiego Novillo 
14c572e92cSDiego Novillo #include "llvm/ProfileData/SampleProf.h"
15432a3883SNico Weber #include "llvm/Config/llvm-config.h"
16432a3883SNico Weber #include "llvm/IR/DebugInfoMetadata.h"
17ac068e01SHongtao Yu #include "llvm/IR/PseudoProbe.h"
18c67ccf5fSWei Mi #include "llvm/ProfileData/SampleProfReader.h"
197fb40011SWei Mi #include "llvm/Support/CommandLine.h"
20e78d131aSEugene Zelenko #include "llvm/Support/Compiler.h"
21e78d131aSEugene Zelenko #include "llvm/Support/Debug.h"
22c572e92cSDiego Novillo #include "llvm/Support/ErrorHandling.h"
23e78d131aSEugene Zelenko #include "llvm/Support/raw_ostream.h"
24e78d131aSEugene Zelenko #include <string>
25e78d131aSEugene Zelenko #include <system_error>
26c572e92cSDiego Novillo 
27c572e92cSDiego Novillo using namespace llvm;
28e78d131aSEugene Zelenko using namespace sampleprof;
29c572e92cSDiego Novillo 
307fb40011SWei Mi static cl::opt<uint64_t> ProfileSymbolListCutOff(
31557efc9aSFangrui Song     "profile-symbol-list-cutoff", cl::Hidden, cl::init(-1),
327fb40011SWei Mi     cl::desc("Cutoff value about how many symbols in profile symbol list "
337fb40011SWei Mi              "will be used. This is very useful for performance debugging"));
347fb40011SWei Mi 
355740bb80SHongtao Yu cl::opt<bool> GenerateMergedBaseProfiles(
36557efc9aSFangrui Song     "generate-merged-base-profiles",
375740bb80SHongtao Yu     cl::desc("When generating nested context-sensitive profiles, always "
385740bb80SHongtao Yu              "generate extra base profile for function with all its context "
395740bb80SHongtao Yu              "profiles merged into it."));
405740bb80SHongtao Yu 
4194d44c97SWei Mi namespace llvm {
4294d44c97SWei Mi namespace sampleprof {
43ac068e01SHongtao Yu bool FunctionSamples::ProfileIsProbeBased = false;
44e36786d1SHongtao Yu bool FunctionSamples::ProfileIsCS = false;
45e36786d1SHongtao Yu bool FunctionSamples::ProfileIsPreInlined = false;
46ee35784aSWei Mi bool FunctionSamples::UseMD5 = false;
47ee35784aSWei Mi bool FunctionSamples::HasUniqSuffix = true;
486745ffe4SRong Xu bool FunctionSamples::ProfileIsFS = false;
4994d44c97SWei Mi } // namespace sampleprof
5094d44c97SWei Mi } // namespace llvm
5194d44c97SWei Mi 
52c572e92cSDiego Novillo namespace {
53e78d131aSEugene Zelenko 
544718f8b5SPeter Collingbourne // FIXME: This class is only here to support the transition to llvm::Error. It
554718f8b5SPeter Collingbourne // will be removed once this transition is complete. Clients should prefer to
564718f8b5SPeter Collingbourne // deal with the Error value directly, rather than converting to error_code.
57c572e92cSDiego Novillo class SampleProfErrorCategoryType : public std::error_category {
name() const58990504e6SReid Kleckner   const char *name() const noexcept override { return "llvm.sampleprof"; }
59e78d131aSEugene Zelenko 
message(int IE) const60c572e92cSDiego Novillo   std::string message(int IE) const override {
61c572e92cSDiego Novillo     sampleprof_error E = static_cast<sampleprof_error>(IE);
62c572e92cSDiego Novillo     switch (E) {
63c572e92cSDiego Novillo     case sampleprof_error::success:
64c572e92cSDiego Novillo       return "Success";
65c572e92cSDiego Novillo     case sampleprof_error::bad_magic:
664f823667SNathan Slingerland       return "Invalid sample profile data (bad magic)";
67c572e92cSDiego Novillo     case sampleprof_error::unsupported_version:
684f823667SNathan Slingerland       return "Unsupported sample profile format version";
69c572e92cSDiego Novillo     case sampleprof_error::too_large:
70c572e92cSDiego Novillo       return "Too much profile data";
71c572e92cSDiego Novillo     case sampleprof_error::truncated:
72c572e92cSDiego Novillo       return "Truncated profile data";
73c572e92cSDiego Novillo     case sampleprof_error::malformed:
744f823667SNathan Slingerland       return "Malformed sample profile data";
75d5336ae2SDiego Novillo     case sampleprof_error::unrecognized_format:
764f823667SNathan Slingerland       return "Unrecognized sample profile encoding format";
77760c5a8fSDiego Novillo     case sampleprof_error::unsupported_writing_format:
78760c5a8fSDiego Novillo       return "Profile encoding format unsupported for writing operations";
79760c5a8fSDiego Novillo     case sampleprof_error::truncated_name_table:
80760c5a8fSDiego Novillo       return "Truncated function name table";
813376a787SDiego Novillo     case sampleprof_error::not_implemented:
823376a787SDiego Novillo       return "Unimplemented feature";
8348dd080cSNathan Slingerland     case sampleprof_error::counter_overflow:
8448dd080cSNathan Slingerland       return "Counter overflow";
856a14325dSWei Mi     case sampleprof_error::ostream_seek_unsupported:
866a14325dSWei Mi       return "Ostream does not support seek";
87798e59b8SWei Mi     case sampleprof_error::uncompress_failed:
88798e59b8SWei Mi       return "Uncompress failure";
89798e59b8SWei Mi     case sampleprof_error::zlib_unavailable:
90798e59b8SWei Mi       return "Zlib is unavailable";
91ac068e01SHongtao Yu     case sampleprof_error::hash_mismatch:
92ac068e01SHongtao Yu       return "Function hash mismatch";
93c572e92cSDiego Novillo     }
94c572e92cSDiego Novillo     llvm_unreachable("A value of sampleprof_error has no message.");
95c572e92cSDiego Novillo   }
96c572e92cSDiego Novillo };
97e78d131aSEugene Zelenko 
98e78d131aSEugene Zelenko } // end anonymous namespace
99c572e92cSDiego Novillo 
sampleprof_category()100c572e92cSDiego Novillo const std::error_category &llvm::sampleprof_category() {
101*ede60037SNicolai Hähnle   static SampleProfErrorCategoryType ErrorCategory;
102*ede60037SNicolai Hähnle   return ErrorCategory;
103c572e92cSDiego Novillo }
1044b6bdb53SDiego Novillo 
print(raw_ostream & OS) const105ba920be4SDiego Novillo void LineLocation::print(raw_ostream &OS) const {
106ba920be4SDiego Novillo   OS << LineOffset;
107ba920be4SDiego Novillo   if (Discriminator > 0)
108ba920be4SDiego Novillo     OS << "." << Discriminator;
109ba920be4SDiego Novillo }
110ba920be4SDiego Novillo 
operator <<(raw_ostream & OS,const LineLocation & Loc)111ba920be4SDiego Novillo raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
112ba920be4SDiego Novillo                                           const LineLocation &Loc) {
113ba920be4SDiego Novillo   Loc.print(OS);
114ba920be4SDiego Novillo   return OS;
115ba920be4SDiego Novillo }
116ba920be4SDiego Novillo 
117ad2a59f5SHongtao Yu /// Merge the samples in \p Other into this record.
118ad2a59f5SHongtao Yu /// Optionally scale sample counts by \p Weight.
merge(const SampleRecord & Other,uint64_t Weight)119ad2a59f5SHongtao Yu sampleprof_error SampleRecord::merge(const SampleRecord &Other,
120ad2a59f5SHongtao Yu                                      uint64_t Weight) {
121ad2a59f5SHongtao Yu   sampleprof_error Result;
122ad2a59f5SHongtao Yu   Result = addSamples(Other.getSamples(), Weight);
123ad2a59f5SHongtao Yu   for (const auto &I : Other.getCallTargets()) {
124ad2a59f5SHongtao Yu     MergeResult(Result, addCalledTarget(I.first(), I.second, Weight));
125ad2a59f5SHongtao Yu   }
126ad2a59f5SHongtao Yu   return Result;
127ad2a59f5SHongtao Yu }
128ad2a59f5SHongtao Yu 
129615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const130eb2a2546SYaron Keren LLVM_DUMP_METHOD void LineLocation::dump() const { print(dbgs()); }
1318c209aa8SMatthias Braun #endif
132ba920be4SDiego Novillo 
1335f8f34e4SAdrian Prantl /// Print the sample record to the stream \p OS indented by \p Indent.
print(raw_ostream & OS,unsigned Indent) const1348e415a82SDiego Novillo void SampleRecord::print(raw_ostream &OS, unsigned Indent) const {
1358e415a82SDiego Novillo   OS << NumSamples;
1368e415a82SDiego Novillo   if (hasCalls()) {
1374b6bdb53SDiego Novillo     OS << ", calls:";
1385adace35SWenlei He     for (const auto &I : getSortedCallTargets())
1395adace35SWenlei He       OS << " " << I.first << ":" << I.second;
1404b6bdb53SDiego Novillo   }
1414b6bdb53SDiego Novillo   OS << "\n";
1424b6bdb53SDiego Novillo }
1438e415a82SDiego Novillo 
144615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const145eb2a2546SYaron Keren LLVM_DUMP_METHOD void SampleRecord::dump() const { print(dbgs(), 0); }
1468c209aa8SMatthias Braun #endif
147ba920be4SDiego Novillo 
operator <<(raw_ostream & OS,const SampleRecord & Sample)148ba920be4SDiego Novillo raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
149ba920be4SDiego Novillo                                           const SampleRecord &Sample) {
150ba920be4SDiego Novillo   Sample.print(OS, 0);
151ba920be4SDiego Novillo   return OS;
152ba920be4SDiego Novillo }
153ba920be4SDiego Novillo 
1545f8f34e4SAdrian Prantl /// Print the samples collected for a function on stream \p OS.
print(raw_ostream & OS,unsigned Indent) const1558e415a82SDiego Novillo void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const {
156ac068e01SHongtao Yu   if (getFunctionHash())
157ac068e01SHongtao Yu     OS << "CFG checksum " << getFunctionHash() << "\n";
158ac068e01SHongtao Yu 
1598e415a82SDiego Novillo   OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
1608e415a82SDiego Novillo      << " sampled lines\n";
1618e415a82SDiego Novillo 
162379cc5e7SDiego Novillo   OS.indent(Indent);
163e78d131aSEugene Zelenko   if (!BodySamples.empty()) {
164379cc5e7SDiego Novillo     OS << "Samples collected in the function's body {\n";
165ef548d29SDiego Novillo     SampleSorter<LineLocation, SampleRecord> SortedBodySamples(BodySamples);
166ef548d29SDiego Novillo     for (const auto &SI : SortedBodySamples.get()) {
167379cc5e7SDiego Novillo       OS.indent(Indent + 2);
168ef548d29SDiego Novillo       OS << SI->first << ": " << SI->second;
1698e415a82SDiego Novillo     }
170379cc5e7SDiego Novillo     OS.indent(Indent);
171379cc5e7SDiego Novillo     OS << "}\n";
172379cc5e7SDiego Novillo   } else {
173379cc5e7SDiego Novillo     OS << "No samples collected in the function's body\n";
174379cc5e7SDiego Novillo   }
1758e415a82SDiego Novillo 
176379cc5e7SDiego Novillo   OS.indent(Indent);
177e78d131aSEugene Zelenko   if (!CallsiteSamples.empty()) {
178379cc5e7SDiego Novillo     OS << "Samples collected in inlined callsites {\n";
1792c7ca9b5SDehao Chen     SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples(
180ef548d29SDiego Novillo         CallsiteSamples);
181ef548d29SDiego Novillo     for (const auto &CS : SortedCallsiteSamples.get()) {
1822c7ca9b5SDehao Chen       for (const auto &FS : CS->second) {
183379cc5e7SDiego Novillo         OS.indent(Indent + 2);
1842c7ca9b5SDehao Chen         OS << CS->first << ": inlined callee: " << FS.second.getName() << ": ";
1852c7ca9b5SDehao Chen         FS.second.print(OS, Indent + 4);
1862c7ca9b5SDehao Chen       }
187379cc5e7SDiego Novillo     }
188b3342e18SWenlei He     OS.indent(Indent);
189379cc5e7SDiego Novillo     OS << "}\n";
190379cc5e7SDiego Novillo   } else {
191379cc5e7SDiego Novillo     OS << "No inlined callsites in this function\n";
1924b6bdb53SDiego Novillo   }
1934b6bdb53SDiego Novillo }
194ba920be4SDiego Novillo 
operator <<(raw_ostream & OS,const FunctionSamples & FS)195ba920be4SDiego Novillo raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
196ba920be4SDiego Novillo                                           const FunctionSamples &FS) {
197ba920be4SDiego Novillo   FS.print(OS);
198ba920be4SDiego Novillo   return OS;
199ba920be4SDiego Novillo }
200ba920be4SDiego Novillo 
sortFuncProfiles(const SampleProfileMap & ProfileMap,std::vector<NameFunctionSamples> & SortedProfiles)201f27fee62SHongtao Yu void sampleprof::sortFuncProfiles(
202b9db7036SHongtao Yu     const SampleProfileMap &ProfileMap,
203f27fee62SHongtao Yu     std::vector<NameFunctionSamples> &SortedProfiles) {
204f27fee62SHongtao Yu   for (const auto &I : ProfileMap) {
205b9db7036SHongtao Yu     assert(I.first == I.second.getContext() && "Inconsistent profile map");
206b9db7036SHongtao Yu     SortedProfiles.push_back(std::make_pair(I.second.getContext(), &I.second));
207f27fee62SHongtao Yu   }
208f27fee62SHongtao Yu   llvm::stable_sort(SortedProfiles, [](const NameFunctionSamples &A,
209f27fee62SHongtao Yu                                        const NameFunctionSamples &B) {
210f27fee62SHongtao Yu     if (A.second->getTotalSamples() == B.second->getTotalSamples())
211b9db7036SHongtao Yu       return A.first < B.first;
212f27fee62SHongtao Yu     return A.second->getTotalSamples() > B.second->getTotalSamples();
213f27fee62SHongtao Yu   });
214f27fee62SHongtao Yu }
215f27fee62SHongtao Yu 
getOffset(const DILocation * DIL)21656950974SMircea Trofin unsigned FunctionSamples::getOffset(const DILocation *DIL) {
21756950974SMircea Trofin   return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
21856950974SMircea Trofin       0xffff;
21956950974SMircea Trofin }
22056950974SMircea Trofin 
getCallSiteIdentifier(const DILocation * DIL,bool ProfileIsFS)2215740bb80SHongtao Yu LineLocation FunctionSamples::getCallSiteIdentifier(const DILocation *DIL,
2225740bb80SHongtao Yu                                                     bool ProfileIsFS) {
2235740bb80SHongtao Yu   if (FunctionSamples::ProfileIsProbeBased) {
224ac068e01SHongtao Yu     // In a pseudo-probe based profile, a callsite is simply represented by the
225ac068e01SHongtao Yu     // ID of the probe associated with the call instruction. The probe ID is
226ac068e01SHongtao Yu     // encoded in the Discriminator field of the call instruction's debug
227ac068e01SHongtao Yu     // metadata.
228ac068e01SHongtao Yu     return LineLocation(PseudoProbeDwarfDiscriminator::extractProbeIndex(
229ac068e01SHongtao Yu                             DIL->getDiscriminator()),
230ac068e01SHongtao Yu                         0);
2315740bb80SHongtao Yu   } else {
2325740bb80SHongtao Yu     unsigned Discriminator =
2335740bb80SHongtao Yu         ProfileIsFS ? DIL->getDiscriminator() : DIL->getBaseDiscriminator();
2345740bb80SHongtao Yu     return LineLocation(FunctionSamples::getOffset(DIL), Discriminator);
2355740bb80SHongtao Yu   }
2365740bb80SHongtao Yu }
2375740bb80SHongtao Yu 
getCallSiteHash(StringRef CalleeName,const LineLocation & Callsite)2385740bb80SHongtao Yu uint64_t FunctionSamples::getCallSiteHash(StringRef CalleeName,
2395740bb80SHongtao Yu                                           const LineLocation &Callsite) {
2405740bb80SHongtao Yu   uint64_t NameHash = std::hash<std::string>{}(CalleeName.str());
2415740bb80SHongtao Yu   uint64_t LocId =
2425740bb80SHongtao Yu       (((uint64_t)Callsite.LineOffset) << 32) | Callsite.Discriminator;
2435740bb80SHongtao Yu   return NameHash + (LocId << 5) + LocId;
244ac068e01SHongtao Yu }
245ac068e01SHongtao Yu 
findFunctionSamples(const DILocation * DIL,SampleProfileReaderItaniumRemapper * Remapper) const246c67ccf5fSWei Mi const FunctionSamples *FunctionSamples::findFunctionSamples(
247c67ccf5fSWei Mi     const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper) const {
24856950974SMircea Trofin   assert(DIL);
24956950974SMircea Trofin   SmallVector<std::pair<LineLocation, StringRef>, 10> S;
25056950974SMircea Trofin 
25156950974SMircea Trofin   const DILocation *PrevDIL = DIL;
25256950974SMircea Trofin   for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
253d1378544SHongtao Yu     // Use C++ linkage name if possible.
254d1378544SHongtao Yu     StringRef Name = PrevDIL->getScope()->getSubprogram()->getLinkageName();
255d1378544SHongtao Yu     if (Name.empty())
256d1378544SHongtao Yu       Name = PrevDIL->getScope()->getSubprogram()->getName();
2575740bb80SHongtao Yu     S.emplace_back(FunctionSamples::getCallSiteIdentifier(
2585740bb80SHongtao Yu                        DIL, FunctionSamples::ProfileIsFS),
2595740bb80SHongtao Yu                    Name);
26056950974SMircea Trofin     PrevDIL = DIL;
26156950974SMircea Trofin   }
2625740bb80SHongtao Yu 
26356950974SMircea Trofin   if (S.size() == 0)
26456950974SMircea Trofin     return this;
26556950974SMircea Trofin   const FunctionSamples *FS = this;
26656950974SMircea Trofin   for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
267c67ccf5fSWei Mi     FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper);
26856950974SMircea Trofin   }
26956950974SMircea Trofin   return FS;
27056950974SMircea Trofin }
27156950974SMircea Trofin 
findAllNames(DenseSet<StringRef> & NameSet) const272c67ccf5fSWei Mi void FunctionSamples::findAllNames(DenseSet<StringRef> &NameSet) const {
273b9db7036SHongtao Yu   NameSet.insert(getName());
274c67ccf5fSWei Mi   for (const auto &BS : BodySamples)
275c67ccf5fSWei Mi     for (const auto &TS : BS.second.getCallTargets())
276c67ccf5fSWei Mi       NameSet.insert(TS.getKey());
277c67ccf5fSWei Mi 
278c67ccf5fSWei Mi   for (const auto &CS : CallsiteSamples) {
279c67ccf5fSWei Mi     for (const auto &NameFS : CS.second) {
280c67ccf5fSWei Mi       NameSet.insert(NameFS.first);
281c67ccf5fSWei Mi       NameFS.second.findAllNames(NameSet);
282c67ccf5fSWei Mi     }
283c67ccf5fSWei Mi   }
284c67ccf5fSWei Mi }
285c67ccf5fSWei Mi 
findFunctionSamplesAt(const LineLocation & Loc,StringRef CalleeName,SampleProfileReaderItaniumRemapper * Remapper) const286c67ccf5fSWei Mi const FunctionSamples *FunctionSamples::findFunctionSamplesAt(
287c67ccf5fSWei Mi     const LineLocation &Loc, StringRef CalleeName,
288c67ccf5fSWei Mi     SampleProfileReaderItaniumRemapper *Remapper) const {
289ee35784aSWei Mi   CalleeName = getCanonicalFnName(CalleeName);
290ee35784aSWei Mi 
291c67ccf5fSWei Mi   std::string CalleeGUID;
292c67ccf5fSWei Mi   CalleeName = getRepInFormat(CalleeName, UseMD5, CalleeGUID);
293c67ccf5fSWei Mi 
294c67ccf5fSWei Mi   auto iter = CallsiteSamples.find(Loc);
295c67ccf5fSWei Mi   if (iter == CallsiteSamples.end())
296c67ccf5fSWei Mi     return nullptr;
297c67ccf5fSWei Mi   auto FS = iter->second.find(CalleeName);
298c67ccf5fSWei Mi   if (FS != iter->second.end())
299c67ccf5fSWei Mi     return &FS->second;
300c67ccf5fSWei Mi   if (Remapper) {
301c67ccf5fSWei Mi     if (auto NameInProfile = Remapper->lookUpNameInProfile(CalleeName)) {
302c67ccf5fSWei Mi       auto FS = iter->second.find(*NameInProfile);
303c67ccf5fSWei Mi       if (FS != iter->second.end())
304c67ccf5fSWei Mi         return &FS->second;
305c67ccf5fSWei Mi     }
306c67ccf5fSWei Mi   }
307c67ccf5fSWei Mi   // If we cannot find exact match of the callee name, return the FS with
308c67ccf5fSWei Mi   // the max total count. Only do this when CalleeName is not provided,
309c67ccf5fSWei Mi   // i.e., only for indirect calls.
310c67ccf5fSWei Mi   if (!CalleeName.empty())
311c67ccf5fSWei Mi     return nullptr;
312c67ccf5fSWei Mi   uint64_t MaxTotalSamples = 0;
313c67ccf5fSWei Mi   const FunctionSamples *R = nullptr;
314c67ccf5fSWei Mi   for (const auto &NameFS : iter->second)
315c67ccf5fSWei Mi     if (NameFS.second.getTotalSamples() >= MaxTotalSamples) {
316c67ccf5fSWei Mi       MaxTotalSamples = NameFS.second.getTotalSamples();
317c67ccf5fSWei Mi       R = &NameFS.second;
318c67ccf5fSWei Mi     }
319c67ccf5fSWei Mi   return R;
320c67ccf5fSWei Mi }
321c67ccf5fSWei Mi 
322615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const323e78d131aSEugene Zelenko LLVM_DUMP_METHOD void FunctionSamples::dump() const { print(dbgs(), 0); }
3248c209aa8SMatthias Braun #endif
325798e59b8SWei Mi 
read(const uint8_t * Data,uint64_t ListSize)326b523790aSWei Mi std::error_code ProfileSymbolList::read(const uint8_t *Data,
327b523790aSWei Mi                                         uint64_t ListSize) {
328798e59b8SWei Mi   const char *ListStart = reinterpret_cast<const char *>(Data);
329798e59b8SWei Mi   uint64_t Size = 0;
3307fb40011SWei Mi   uint64_t StrNum = 0;
3317fb40011SWei Mi   while (Size < ListSize && StrNum < ProfileSymbolListCutOff) {
332798e59b8SWei Mi     StringRef Str(ListStart + Size);
333798e59b8SWei Mi     add(Str);
334798e59b8SWei Mi     Size += Str.size() + 1;
3357fb40011SWei Mi     StrNum++;
336798e59b8SWei Mi   }
3377fb40011SWei Mi   if (Size != ListSize && StrNum != ProfileSymbolListCutOff)
338b523790aSWei Mi     return sampleprof_error::malformed;
339798e59b8SWei Mi   return sampleprof_error::success;
340798e59b8SWei Mi }
341798e59b8SWei Mi 
trimAndMergeColdContextProfiles(uint64_t ColdCountThreshold,bool TrimColdContext,bool MergeColdContext,uint32_t ColdContextFrameLength,bool TrimBaseProfileOnly)34200ef28efSWenlei He void SampleContextTrimmer::trimAndMergeColdContextProfiles(
343863184ddSwlei     uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext,
344259e4c56SHongtao Yu     uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly) {
34500ef28efSWenlei He   if (!TrimColdContext && !MergeColdContext)
34600ef28efSWenlei He     return;
34700ef28efSWenlei He 
34800ef28efSWenlei He   // Nothing to merge if sample threshold is zero
34900ef28efSWenlei He   if (ColdCountThreshold == 0)
35000ef28efSWenlei He     return;
35100ef28efSWenlei He 
352259e4c56SHongtao Yu   // Trimming base profiles only is mainly to honor the preinliner decsion. When
353259e4c56SHongtao Yu   // MergeColdContext is true preinliner decsion is not honored anyway so turn
354259e4c56SHongtao Yu   // off TrimBaseProfileOnly.
355259e4c56SHongtao Yu   if (MergeColdContext)
356259e4c56SHongtao Yu     TrimBaseProfileOnly = false;
357259e4c56SHongtao Yu 
35800ef28efSWenlei He   // Filter the cold profiles from ProfileMap and move them into a tmp
35900ef28efSWenlei He   // container
360b9db7036SHongtao Yu   std::vector<std::pair<SampleContext, const FunctionSamples *>> ColdProfiles;
36100ef28efSWenlei He   for (const auto &I : ProfileMap) {
362259e4c56SHongtao Yu     const SampleContext &Context = I.first;
36300ef28efSWenlei He     const FunctionSamples &FunctionProfile = I.second;
364259e4c56SHongtao Yu     if (FunctionProfile.getTotalSamples() < ColdCountThreshold &&
365259e4c56SHongtao Yu         (!TrimBaseProfileOnly || Context.isBaseContext()))
366259e4c56SHongtao Yu       ColdProfiles.emplace_back(Context, &I.second);
36700ef28efSWenlei He   }
36800ef28efSWenlei He 
369863184ddSwlei   // Remove the cold profile from ProfileMap and merge them into
370863184ddSwlei   // MergedProfileMap by the last K frames of context
371b9db7036SHongtao Yu   SampleProfileMap MergedProfileMap;
37200ef28efSWenlei He   for (const auto &I : ColdProfiles) {
37300ef28efSWenlei He     if (MergeColdContext) {
374b9db7036SHongtao Yu       auto MergedContext = I.second->getContext().getContextFrames();
375b9db7036SHongtao Yu       if (ColdContextFrameLength < MergedContext.size())
376b9db7036SHongtao Yu         MergedContext = MergedContext.take_back(ColdContextFrameLength);
377b9db7036SHongtao Yu       auto Ret = MergedProfileMap.emplace(MergedContext, FunctionSamples());
378863184ddSwlei       FunctionSamples &MergedProfile = Ret.first->second;
379863184ddSwlei       MergedProfile.merge(*I.second);
38000ef28efSWenlei He     }
38100ef28efSWenlei He     ProfileMap.erase(I.first);
38200ef28efSWenlei He   }
38300ef28efSWenlei He 
384863184ddSwlei   // Move the merged profiles into ProfileMap;
385863184ddSwlei   for (const auto &I : MergedProfileMap) {
386863184ddSwlei     // Filter the cold merged profile
38700ef28efSWenlei He     if (TrimColdContext && I.second.getTotalSamples() < ColdCountThreshold &&
388b9db7036SHongtao Yu         ProfileMap.find(I.first) == ProfileMap.end())
38900ef28efSWenlei He       continue;
39000ef28efSWenlei He     // Merge the profile if the original profile exists, otherwise just insert
39100ef28efSWenlei He     // as a new profile
392b9db7036SHongtao Yu     auto Ret = ProfileMap.emplace(I.first, FunctionSamples());
39300ef28efSWenlei He     if (Ret.second) {
394b9db7036SHongtao Yu       SampleContext FContext(Ret.first->first, RawContext);
39500ef28efSWenlei He       FunctionSamples &FProfile = Ret.first->second;
39600ef28efSWenlei He       FProfile.setContext(FContext);
39700ef28efSWenlei He     }
39800ef28efSWenlei He     FunctionSamples &OrigProfile = Ret.first->second;
39900ef28efSWenlei He     OrigProfile.merge(I.second);
40000ef28efSWenlei He   }
40100ef28efSWenlei He }
40200ef28efSWenlei He 
canonicalizeContextProfiles()40300ef28efSWenlei He void SampleContextTrimmer::canonicalizeContextProfiles() {
404b9db7036SHongtao Yu   std::vector<SampleContext> ProfilesToBeRemoved;
405b9db7036SHongtao Yu   SampleProfileMap ProfilesToBeAdded;
40600ef28efSWenlei He   for (auto &I : ProfileMap) {
40700ef28efSWenlei He     FunctionSamples &FProfile = I.second;
408b9db7036SHongtao Yu     SampleContext &Context = FProfile.getContext();
409b9db7036SHongtao Yu     if (I.first == Context)
41000ef28efSWenlei He       continue;
41100ef28efSWenlei He 
41200ef28efSWenlei He     // Use the context string from FunctionSamples to update the keys of
41300ef28efSWenlei He     // ProfileMap. They can get out of sync after context profile promotion
41400ef28efSWenlei He     // through pre-inliner.
415c60f1d5dSHongtao Yu     // Duplicate the function profile for later insertion to avoid a conflict
416c60f1d5dSHongtao Yu     // caused by a context both to be add and to be removed. This could happen
417c60f1d5dSHongtao Yu     // when a context is promoted to another context which is also promoted to
418c60f1d5dSHongtao Yu     // the third context. For example, given an original context A @ B @ C that
419c60f1d5dSHongtao Yu     // is promoted to B @ C and the original context B @ C which is promoted to
420c60f1d5dSHongtao Yu     // just C, adding B @ C to the profile map while removing same context (but
421c60f1d5dSHongtao Yu     // with different profiles) from the map can cause a conflict if they are
422c60f1d5dSHongtao Yu     // not handled in a right order. This can be solved by just caching the
423c60f1d5dSHongtao Yu     // profiles to be added.
424b9db7036SHongtao Yu     auto Ret = ProfilesToBeAdded.emplace(Context, FProfile);
425c60f1d5dSHongtao Yu     (void)Ret;
426c60f1d5dSHongtao Yu     assert(Ret.second && "Context conflict during canonicalization");
427b9db7036SHongtao Yu     ProfilesToBeRemoved.push_back(I.first);
42800ef28efSWenlei He   }
42900ef28efSWenlei He 
43000ef28efSWenlei He   for (auto &I : ProfilesToBeRemoved) {
431c60f1d5dSHongtao Yu     ProfileMap.erase(I);
432c60f1d5dSHongtao Yu   }
433c60f1d5dSHongtao Yu 
434c60f1d5dSHongtao Yu   for (auto &I : ProfilesToBeAdded) {
435b9db7036SHongtao Yu     ProfileMap.emplace(I.first, I.second);
43600ef28efSWenlei He   }
43700ef28efSWenlei He }
43800ef28efSWenlei He 
write(raw_ostream & OS)439798e59b8SWei Mi std::error_code ProfileSymbolList::write(raw_ostream &OS) {
440b523790aSWei Mi   // Sort the symbols before output. If doing compression.
441b523790aSWei Mi   // It will make the compression much more effective.
44228ea50f5SKazu Hirata   std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
443798e59b8SWei Mi   llvm::sort(SortedList);
444798e59b8SWei Mi 
445b523790aSWei Mi   std::string OutputString;
446798e59b8SWei Mi   for (auto &Sym : SortedList) {
447b523790aSWei Mi     OutputString.append(Sym.str());
448b523790aSWei Mi     OutputString.append(1, '\0');
449798e59b8SWei Mi   }
450798e59b8SWei Mi 
451b523790aSWei Mi   OS << OutputString;
452798e59b8SWei Mi   return sampleprof_error::success;
453798e59b8SWei Mi }
454798e59b8SWei Mi 
dump(raw_ostream & OS) const455798e59b8SWei Mi void ProfileSymbolList::dump(raw_ostream &OS) const {
456798e59b8SWei Mi   OS << "======== Dump profile symbol list ========\n";
45728ea50f5SKazu Hirata   std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
458798e59b8SWei Mi   llvm::sort(SortedList);
459798e59b8SWei Mi 
460798e59b8SWei Mi   for (auto &Sym : SortedList)
461798e59b8SWei Mi     OS << Sym << "\n";
462798e59b8SWei Mi }
4635740bb80SHongtao Yu 
4645740bb80SHongtao Yu CSProfileConverter::FrameNode *
getOrCreateChildFrame(const LineLocation & CallSite,StringRef CalleeName)4655740bb80SHongtao Yu CSProfileConverter::FrameNode::getOrCreateChildFrame(
4665740bb80SHongtao Yu     const LineLocation &CallSite, StringRef CalleeName) {
4675740bb80SHongtao Yu   uint64_t Hash = FunctionSamples::getCallSiteHash(CalleeName, CallSite);
4685740bb80SHongtao Yu   auto It = AllChildFrames.find(Hash);
4695740bb80SHongtao Yu   if (It != AllChildFrames.end()) {
4705740bb80SHongtao Yu     assert(It->second.FuncName == CalleeName &&
4715740bb80SHongtao Yu            "Hash collision for child context node");
4725740bb80SHongtao Yu     return &It->second;
4735740bb80SHongtao Yu   }
4745740bb80SHongtao Yu 
4755740bb80SHongtao Yu   AllChildFrames[Hash] = FrameNode(CalleeName, nullptr, CallSite);
4765740bb80SHongtao Yu   return &AllChildFrames[Hash];
4775740bb80SHongtao Yu }
4785740bb80SHongtao Yu 
CSProfileConverter(SampleProfileMap & Profiles)4795740bb80SHongtao Yu CSProfileConverter::CSProfileConverter(SampleProfileMap &Profiles)
4805740bb80SHongtao Yu     : ProfileMap(Profiles) {
4815740bb80SHongtao Yu   for (auto &FuncSample : Profiles) {
4825740bb80SHongtao Yu     FunctionSamples *FSamples = &FuncSample.second;
4835740bb80SHongtao Yu     auto *NewNode = getOrCreateContextPath(FSamples->getContext());
4845740bb80SHongtao Yu     assert(!NewNode->FuncSamples && "New node cannot have sample profile");
4855740bb80SHongtao Yu     NewNode->FuncSamples = FSamples;
4865740bb80SHongtao Yu   }
4875740bb80SHongtao Yu }
4885740bb80SHongtao Yu 
4895740bb80SHongtao Yu CSProfileConverter::FrameNode *
getOrCreateContextPath(const SampleContext & Context)4905740bb80SHongtao Yu CSProfileConverter::getOrCreateContextPath(const SampleContext &Context) {
4915740bb80SHongtao Yu   auto Node = &RootFrame;
4925740bb80SHongtao Yu   LineLocation CallSiteLoc(0, 0);
4935740bb80SHongtao Yu   for (auto &Callsite : Context.getContextFrames()) {
4945740bb80SHongtao Yu     Node = Node->getOrCreateChildFrame(CallSiteLoc, Callsite.FuncName);
4955740bb80SHongtao Yu     CallSiteLoc = Callsite.Location;
4965740bb80SHongtao Yu   }
4975740bb80SHongtao Yu   return Node;
4985740bb80SHongtao Yu }
4995740bb80SHongtao Yu 
convertProfiles(CSProfileConverter::FrameNode & Node)5005740bb80SHongtao Yu void CSProfileConverter::convertProfiles(CSProfileConverter::FrameNode &Node) {
5015740bb80SHongtao Yu   // Process each child profile. Add each child profile to callsite profile map
5025740bb80SHongtao Yu   // of the current node `Node` if `Node` comes with a profile. Otherwise
5035740bb80SHongtao Yu   // promote the child profile to a standalone profile.
5045740bb80SHongtao Yu   auto *NodeProfile = Node.FuncSamples;
5055740bb80SHongtao Yu   for (auto &It : Node.AllChildFrames) {
5065740bb80SHongtao Yu     auto &ChildNode = It.second;
5075740bb80SHongtao Yu     convertProfiles(ChildNode);
5085740bb80SHongtao Yu     auto *ChildProfile = ChildNode.FuncSamples;
5095740bb80SHongtao Yu     if (!ChildProfile)
5105740bb80SHongtao Yu       continue;
5115740bb80SHongtao Yu     SampleContext OrigChildContext = ChildProfile->getContext();
5125740bb80SHongtao Yu     // Reset the child context to be contextless.
5135740bb80SHongtao Yu     ChildProfile->getContext().setName(OrigChildContext.getName());
5145740bb80SHongtao Yu     if (NodeProfile) {
5155740bb80SHongtao Yu       // Add child profile to the callsite profile map.
5165740bb80SHongtao Yu       auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
517156b1e6bSDmitri Gribenko       SamplesMap.emplace(OrigChildContext.getName().str(), *ChildProfile);
5185740bb80SHongtao Yu       NodeProfile->addTotalSamples(ChildProfile->getTotalSamples());
5191662cfa4SHongtao Yu       // Remove the corresponding body sample for the callsite and update the
5201662cfa4SHongtao Yu       // total weight.
5211662cfa4SHongtao Yu       auto Count = NodeProfile->removeCalledTargetAndBodySample(
5221662cfa4SHongtao Yu           ChildNode.CallSiteLoc.LineOffset, ChildNode.CallSiteLoc.Discriminator,
5231662cfa4SHongtao Yu           OrigChildContext.getName());
5241662cfa4SHongtao Yu       NodeProfile->removeTotalSamples(Count);
5255740bb80SHongtao Yu     }
5265740bb80SHongtao Yu 
5275740bb80SHongtao Yu     // Separate child profile to be a standalone profile, if the current parent
5285740bb80SHongtao Yu     // profile doesn't exist. This is a duplicating operation when the child
5295740bb80SHongtao Yu     // profile is already incorporated into the parent which is still useful and
5305740bb80SHongtao Yu     // thus done optionally. It is seen that duplicating context profiles into
5315740bb80SHongtao Yu     // base profiles improves the code quality for thinlto build by allowing a
5325740bb80SHongtao Yu     // profile in the prelink phase for to-be-fully-inlined functions.
533f0f70ae6SHongtao Yu     if (!NodeProfile) {
5345740bb80SHongtao Yu       ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
535f0f70ae6SHongtao Yu     } else if (GenerateMergedBaseProfiles) {
536f0f70ae6SHongtao Yu       ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
537f0f70ae6SHongtao Yu       auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
538f0f70ae6SHongtao Yu       SamplesMap[ChildProfile->getName().str()].getContext().setAttribute(
539f0f70ae6SHongtao Yu           ContextDuplicatedIntoBase);
540f0f70ae6SHongtao Yu     }
5415740bb80SHongtao Yu 
5425740bb80SHongtao Yu     // Remove the original child profile.
5435740bb80SHongtao Yu     ProfileMap.erase(OrigChildContext);
5445740bb80SHongtao Yu   }
5455740bb80SHongtao Yu }
5465740bb80SHongtao Yu 
convertProfiles()5475740bb80SHongtao Yu void CSProfileConverter::convertProfiles() { convertProfiles(RootFrame); }
548