xref: /freebsd-src/contrib/llvm-project/llvm/lib/ProfileData/SampleProf.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
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/ManagedStatic.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <string>
26 #include <system_error>
27 
28 using namespace llvm;
29 using namespace sampleprof;
30 
31 static cl::opt<uint64_t> ProfileSymbolListCutOff(
32     "profile-symbol-list-cutoff", cl::Hidden, cl::init(-1),
33     cl::desc("Cutoff value about how many symbols in profile symbol list "
34              "will be used. This is very useful for performance debugging"));
35 
36 cl::opt<bool> GenerateMergedBaseProfiles(
37     "generate-merged-base-profiles",
38     cl::desc("When generating nested context-sensitive profiles, always "
39              "generate extra base profile for function with all its context "
40              "profiles merged into it."));
41 
42 namespace llvm {
43 namespace sampleprof {
44 bool FunctionSamples::ProfileIsProbeBased = false;
45 bool FunctionSamples::ProfileIsCS = false;
46 bool FunctionSamples::ProfileIsPreInlined = false;
47 bool FunctionSamples::UseMD5 = false;
48 bool FunctionSamples::HasUniqSuffix = true;
49 bool FunctionSamples::ProfileIsFS = false;
50 } // namespace sampleprof
51 } // namespace llvm
52 
53 namespace {
54 
55 // FIXME: This class is only here to support the transition to llvm::Error. It
56 // will be removed once this transition is complete. Clients should prefer to
57 // deal with the Error value directly, rather than converting to error_code.
58 class SampleProfErrorCategoryType : public std::error_category {
59   const char *name() const noexcept override { return "llvm.sampleprof"; }
60 
61   std::string message(int IE) const override {
62     sampleprof_error E = static_cast<sampleprof_error>(IE);
63     switch (E) {
64     case sampleprof_error::success:
65       return "Success";
66     case sampleprof_error::bad_magic:
67       return "Invalid sample profile data (bad magic)";
68     case sampleprof_error::unsupported_version:
69       return "Unsupported sample profile format version";
70     case sampleprof_error::too_large:
71       return "Too much profile data";
72     case sampleprof_error::truncated:
73       return "Truncated profile data";
74     case sampleprof_error::malformed:
75       return "Malformed sample profile data";
76     case sampleprof_error::unrecognized_format:
77       return "Unrecognized sample profile encoding format";
78     case sampleprof_error::unsupported_writing_format:
79       return "Profile encoding format unsupported for writing operations";
80     case sampleprof_error::truncated_name_table:
81       return "Truncated function name table";
82     case sampleprof_error::not_implemented:
83       return "Unimplemented feature";
84     case sampleprof_error::counter_overflow:
85       return "Counter overflow";
86     case sampleprof_error::ostream_seek_unsupported:
87       return "Ostream does not support seek";
88     case sampleprof_error::uncompress_failed:
89       return "Uncompress failure";
90     case sampleprof_error::zlib_unavailable:
91       return "Zlib is unavailable";
92     case sampleprof_error::hash_mismatch:
93       return "Function hash mismatch";
94     }
95     llvm_unreachable("A value of sampleprof_error has no message.");
96   }
97 };
98 
99 } // end anonymous namespace
100 
101 static ManagedStatic<SampleProfErrorCategoryType> ErrorCategory;
102 
103 const std::error_category &llvm::sampleprof_category() {
104   return *ErrorCategory;
105 }
106 
107 void LineLocation::print(raw_ostream &OS) const {
108   OS << LineOffset;
109   if (Discriminator > 0)
110     OS << "." << Discriminator;
111 }
112 
113 raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
114                                           const LineLocation &Loc) {
115   Loc.print(OS);
116   return OS;
117 }
118 
119 /// Merge the samples in \p Other into this record.
120 /// Optionally scale sample counts by \p Weight.
121 sampleprof_error SampleRecord::merge(const SampleRecord &Other,
122                                      uint64_t Weight) {
123   sampleprof_error Result;
124   Result = addSamples(Other.getSamples(), Weight);
125   for (const auto &I : Other.getCallTargets()) {
126     MergeResult(Result, addCalledTarget(I.first(), I.second, Weight));
127   }
128   return Result;
129 }
130 
131 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
132 LLVM_DUMP_METHOD void LineLocation::dump() const { print(dbgs()); }
133 #endif
134 
135 /// Print the sample record to the stream \p OS indented by \p Indent.
136 void SampleRecord::print(raw_ostream &OS, unsigned Indent) const {
137   OS << NumSamples;
138   if (hasCalls()) {
139     OS << ", calls:";
140     for (const auto &I : getSortedCallTargets())
141       OS << " " << I.first << ":" << I.second;
142   }
143   OS << "\n";
144 }
145 
146 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
147 LLVM_DUMP_METHOD void SampleRecord::dump() const { print(dbgs(), 0); }
148 #endif
149 
150 raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
151                                           const SampleRecord &Sample) {
152   Sample.print(OS, 0);
153   return OS;
154 }
155 
156 /// Print the samples collected for a function on stream \p OS.
157 void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const {
158   if (getFunctionHash())
159     OS << "CFG checksum " << getFunctionHash() << "\n";
160 
161   OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
162      << " sampled lines\n";
163 
164   OS.indent(Indent);
165   if (!BodySamples.empty()) {
166     OS << "Samples collected in the function's body {\n";
167     SampleSorter<LineLocation, SampleRecord> SortedBodySamples(BodySamples);
168     for (const auto &SI : SortedBodySamples.get()) {
169       OS.indent(Indent + 2);
170       OS << SI->first << ": " << SI->second;
171     }
172     OS.indent(Indent);
173     OS << "}\n";
174   } else {
175     OS << "No samples collected in the function's body\n";
176   }
177 
178   OS.indent(Indent);
179   if (!CallsiteSamples.empty()) {
180     OS << "Samples collected in inlined callsites {\n";
181     SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples(
182         CallsiteSamples);
183     for (const auto &CS : SortedCallsiteSamples.get()) {
184       for (const auto &FS : CS->second) {
185         OS.indent(Indent + 2);
186         OS << CS->first << ": inlined callee: " << FS.second.getName() << ": ";
187         FS.second.print(OS, Indent + 4);
188       }
189     }
190     OS.indent(Indent);
191     OS << "}\n";
192   } else {
193     OS << "No inlined callsites in this function\n";
194   }
195 }
196 
197 raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS,
198                                           const FunctionSamples &FS) {
199   FS.print(OS);
200   return OS;
201 }
202 
203 void sampleprof::sortFuncProfiles(
204     const SampleProfileMap &ProfileMap,
205     std::vector<NameFunctionSamples> &SortedProfiles) {
206   for (const auto &I : ProfileMap) {
207     assert(I.first == I.second.getContext() && "Inconsistent profile map");
208     SortedProfiles.push_back(std::make_pair(I.second.getContext(), &I.second));
209   }
210   llvm::stable_sort(SortedProfiles, [](const NameFunctionSamples &A,
211                                        const NameFunctionSamples &B) {
212     if (A.second->getTotalSamples() == B.second->getTotalSamples())
213       return A.first < B.first;
214     return A.second->getTotalSamples() > B.second->getTotalSamples();
215   });
216 }
217 
218 unsigned FunctionSamples::getOffset(const DILocation *DIL) {
219   return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
220       0xffff;
221 }
222 
223 LineLocation FunctionSamples::getCallSiteIdentifier(const DILocation *DIL,
224                                                     bool ProfileIsFS) {
225   if (FunctionSamples::ProfileIsProbeBased) {
226     // In a pseudo-probe based profile, a callsite is simply represented by the
227     // ID of the probe associated with the call instruction. The probe ID is
228     // encoded in the Discriminator field of the call instruction's debug
229     // metadata.
230     return LineLocation(PseudoProbeDwarfDiscriminator::extractProbeIndex(
231                             DIL->getDiscriminator()),
232                         0);
233   } else {
234     unsigned Discriminator =
235         ProfileIsFS ? DIL->getDiscriminator() : DIL->getBaseDiscriminator();
236     return LineLocation(FunctionSamples::getOffset(DIL), Discriminator);
237   }
238 }
239 
240 uint64_t FunctionSamples::getCallSiteHash(StringRef CalleeName,
241                                           const LineLocation &Callsite) {
242   uint64_t NameHash = std::hash<std::string>{}(CalleeName.str());
243   uint64_t LocId =
244       (((uint64_t)Callsite.LineOffset) << 32) | Callsite.Discriminator;
245   return NameHash + (LocId << 5) + LocId;
246 }
247 
248 const FunctionSamples *FunctionSamples::findFunctionSamples(
249     const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper) const {
250   assert(DIL);
251   SmallVector<std::pair<LineLocation, StringRef>, 10> S;
252 
253   const DILocation *PrevDIL = DIL;
254   for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
255     // Use C++ linkage name if possible.
256     StringRef Name = PrevDIL->getScope()->getSubprogram()->getLinkageName();
257     if (Name.empty())
258       Name = PrevDIL->getScope()->getSubprogram()->getName();
259     S.emplace_back(FunctionSamples::getCallSiteIdentifier(
260                        DIL, FunctionSamples::ProfileIsFS),
261                    Name);
262     PrevDIL = DIL;
263   }
264 
265   if (S.size() == 0)
266     return this;
267   const FunctionSamples *FS = this;
268   for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
269     FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper);
270   }
271   return FS;
272 }
273 
274 void FunctionSamples::findAllNames(DenseSet<StringRef> &NameSet) const {
275   NameSet.insert(getName());
276   for (const auto &BS : BodySamples)
277     for (const auto &TS : BS.second.getCallTargets())
278       NameSet.insert(TS.getKey());
279 
280   for (const auto &CS : CallsiteSamples) {
281     for (const auto &NameFS : CS.second) {
282       NameSet.insert(NameFS.first);
283       NameFS.second.findAllNames(NameSet);
284     }
285   }
286 }
287 
288 const FunctionSamples *FunctionSamples::findFunctionSamplesAt(
289     const LineLocation &Loc, StringRef CalleeName,
290     SampleProfileReaderItaniumRemapper *Remapper) const {
291   CalleeName = getCanonicalFnName(CalleeName);
292 
293   std::string CalleeGUID;
294   CalleeName = getRepInFormat(CalleeName, UseMD5, CalleeGUID);
295 
296   auto iter = CallsiteSamples.find(Loc);
297   if (iter == CallsiteSamples.end())
298     return nullptr;
299   auto FS = iter->second.find(CalleeName);
300   if (FS != iter->second.end())
301     return &FS->second;
302   if (Remapper) {
303     if (auto NameInProfile = Remapper->lookUpNameInProfile(CalleeName)) {
304       auto FS = iter->second.find(*NameInProfile);
305       if (FS != iter->second.end())
306         return &FS->second;
307     }
308   }
309   // If we cannot find exact match of the callee name, return the FS with
310   // the max total count. Only do this when CalleeName is not provided,
311   // i.e., only for indirect calls.
312   if (!CalleeName.empty())
313     return nullptr;
314   uint64_t MaxTotalSamples = 0;
315   const FunctionSamples *R = nullptr;
316   for (const auto &NameFS : iter->second)
317     if (NameFS.second.getTotalSamples() >= MaxTotalSamples) {
318       MaxTotalSamples = NameFS.second.getTotalSamples();
319       R = &NameFS.second;
320     }
321   return R;
322 }
323 
324 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
325 LLVM_DUMP_METHOD void FunctionSamples::dump() const { print(dbgs(), 0); }
326 #endif
327 
328 std::error_code ProfileSymbolList::read(const uint8_t *Data,
329                                         uint64_t ListSize) {
330   const char *ListStart = reinterpret_cast<const char *>(Data);
331   uint64_t Size = 0;
332   uint64_t StrNum = 0;
333   while (Size < ListSize && StrNum < ProfileSymbolListCutOff) {
334     StringRef Str(ListStart + Size);
335     add(Str);
336     Size += Str.size() + 1;
337     StrNum++;
338   }
339   if (Size != ListSize && StrNum != ProfileSymbolListCutOff)
340     return sampleprof_error::malformed;
341   return sampleprof_error::success;
342 }
343 
344 void SampleContextTrimmer::trimAndMergeColdContextProfiles(
345     uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext,
346     uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly) {
347   if (!TrimColdContext && !MergeColdContext)
348     return;
349 
350   // Nothing to merge if sample threshold is zero
351   if (ColdCountThreshold == 0)
352     return;
353 
354   // Trimming base profiles only is mainly to honor the preinliner decsion. When
355   // MergeColdContext is true preinliner decsion is not honored anyway so turn
356   // off TrimBaseProfileOnly.
357   if (MergeColdContext)
358     TrimBaseProfileOnly = false;
359 
360   // Filter the cold profiles from ProfileMap and move them into a tmp
361   // container
362   std::vector<std::pair<SampleContext, const FunctionSamples *>> ColdProfiles;
363   for (const auto &I : ProfileMap) {
364     const SampleContext &Context = I.first;
365     const FunctionSamples &FunctionProfile = I.second;
366     if (FunctionProfile.getTotalSamples() < ColdCountThreshold &&
367         (!TrimBaseProfileOnly || Context.isBaseContext()))
368       ColdProfiles.emplace_back(Context, &I.second);
369   }
370 
371   // Remove the cold profile from ProfileMap and merge them into
372   // MergedProfileMap by the last K frames of context
373   SampleProfileMap MergedProfileMap;
374   for (const auto &I : ColdProfiles) {
375     if (MergeColdContext) {
376       auto MergedContext = I.second->getContext().getContextFrames();
377       if (ColdContextFrameLength < MergedContext.size())
378         MergedContext = MergedContext.take_back(ColdContextFrameLength);
379       auto Ret = MergedProfileMap.emplace(MergedContext, FunctionSamples());
380       FunctionSamples &MergedProfile = Ret.first->second;
381       MergedProfile.merge(*I.second);
382     }
383     ProfileMap.erase(I.first);
384   }
385 
386   // Move the merged profiles into ProfileMap;
387   for (const auto &I : MergedProfileMap) {
388     // Filter the cold merged profile
389     if (TrimColdContext && I.second.getTotalSamples() < ColdCountThreshold &&
390         ProfileMap.find(I.first) == ProfileMap.end())
391       continue;
392     // Merge the profile if the original profile exists, otherwise just insert
393     // as a new profile
394     auto Ret = ProfileMap.emplace(I.first, FunctionSamples());
395     if (Ret.second) {
396       SampleContext FContext(Ret.first->first, RawContext);
397       FunctionSamples &FProfile = Ret.first->second;
398       FProfile.setContext(FContext);
399     }
400     FunctionSamples &OrigProfile = Ret.first->second;
401     OrigProfile.merge(I.second);
402   }
403 }
404 
405 void SampleContextTrimmer::canonicalizeContextProfiles() {
406   std::vector<SampleContext> ProfilesToBeRemoved;
407   SampleProfileMap ProfilesToBeAdded;
408   for (auto &I : ProfileMap) {
409     FunctionSamples &FProfile = I.second;
410     SampleContext &Context = FProfile.getContext();
411     if (I.first == Context)
412       continue;
413 
414     // Use the context string from FunctionSamples to update the keys of
415     // ProfileMap. They can get out of sync after context profile promotion
416     // through pre-inliner.
417     // Duplicate the function profile for later insertion to avoid a conflict
418     // caused by a context both to be add and to be removed. This could happen
419     // when a context is promoted to another context which is also promoted to
420     // the third context. For example, given an original context A @ B @ C that
421     // is promoted to B @ C and the original context B @ C which is promoted to
422     // just C, adding B @ C to the profile map while removing same context (but
423     // with different profiles) from the map can cause a conflict if they are
424     // not handled in a right order. This can be solved by just caching the
425     // profiles to be added.
426     auto Ret = ProfilesToBeAdded.emplace(Context, FProfile);
427     (void)Ret;
428     assert(Ret.second && "Context conflict during canonicalization");
429     ProfilesToBeRemoved.push_back(I.first);
430   }
431 
432   for (auto &I : ProfilesToBeRemoved) {
433     ProfileMap.erase(I);
434   }
435 
436   for (auto &I : ProfilesToBeAdded) {
437     ProfileMap.emplace(I.first, I.second);
438   }
439 }
440 
441 std::error_code ProfileSymbolList::write(raw_ostream &OS) {
442   // Sort the symbols before output. If doing compression.
443   // It will make the compression much more effective.
444   std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
445   llvm::sort(SortedList);
446 
447   std::string OutputString;
448   for (auto &Sym : SortedList) {
449     OutputString.append(Sym.str());
450     OutputString.append(1, '\0');
451   }
452 
453   OS << OutputString;
454   return sampleprof_error::success;
455 }
456 
457 void ProfileSymbolList::dump(raw_ostream &OS) const {
458   OS << "======== Dump profile symbol list ========\n";
459   std::vector<StringRef> SortedList(Syms.begin(), Syms.end());
460   llvm::sort(SortedList);
461 
462   for (auto &Sym : SortedList)
463     OS << Sym << "\n";
464 }
465 
466 CSProfileConverter::FrameNode *
467 CSProfileConverter::FrameNode::getOrCreateChildFrame(
468     const LineLocation &CallSite, StringRef CalleeName) {
469   uint64_t Hash = FunctionSamples::getCallSiteHash(CalleeName, CallSite);
470   auto It = AllChildFrames.find(Hash);
471   if (It != AllChildFrames.end()) {
472     assert(It->second.FuncName == CalleeName &&
473            "Hash collision for child context node");
474     return &It->second;
475   }
476 
477   AllChildFrames[Hash] = FrameNode(CalleeName, nullptr, CallSite);
478   return &AllChildFrames[Hash];
479 }
480 
481 CSProfileConverter::CSProfileConverter(SampleProfileMap &Profiles)
482     : ProfileMap(Profiles) {
483   for (auto &FuncSample : Profiles) {
484     FunctionSamples *FSamples = &FuncSample.second;
485     auto *NewNode = getOrCreateContextPath(FSamples->getContext());
486     assert(!NewNode->FuncSamples && "New node cannot have sample profile");
487     NewNode->FuncSamples = FSamples;
488   }
489 }
490 
491 CSProfileConverter::FrameNode *
492 CSProfileConverter::getOrCreateContextPath(const SampleContext &Context) {
493   auto Node = &RootFrame;
494   LineLocation CallSiteLoc(0, 0);
495   for (auto &Callsite : Context.getContextFrames()) {
496     Node = Node->getOrCreateChildFrame(CallSiteLoc, Callsite.FuncName);
497     CallSiteLoc = Callsite.Location;
498   }
499   return Node;
500 }
501 
502 void CSProfileConverter::convertProfiles(CSProfileConverter::FrameNode &Node) {
503   // Process each child profile. Add each child profile to callsite profile map
504   // of the current node `Node` if `Node` comes with a profile. Otherwise
505   // promote the child profile to a standalone profile.
506   auto *NodeProfile = Node.FuncSamples;
507   for (auto &It : Node.AllChildFrames) {
508     auto &ChildNode = It.second;
509     convertProfiles(ChildNode);
510     auto *ChildProfile = ChildNode.FuncSamples;
511     if (!ChildProfile)
512       continue;
513     SampleContext OrigChildContext = ChildProfile->getContext();
514     // Reset the child context to be contextless.
515     ChildProfile->getContext().setName(OrigChildContext.getName());
516     if (NodeProfile) {
517       // Add child profile to the callsite profile map.
518       auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
519       SamplesMap.emplace(OrigChildContext.getName().str(), *ChildProfile);
520       NodeProfile->addTotalSamples(ChildProfile->getTotalSamples());
521       // Remove the corresponding body sample for the callsite and update the
522       // total weight.
523       auto Count = NodeProfile->removeCalledTargetAndBodySample(
524           ChildNode.CallSiteLoc.LineOffset, ChildNode.CallSiteLoc.Discriminator,
525           OrigChildContext.getName());
526       NodeProfile->removeTotalSamples(Count);
527     }
528 
529     // Separate child profile to be a standalone profile, if the current parent
530     // profile doesn't exist. This is a duplicating operation when the child
531     // profile is already incorporated into the parent which is still useful and
532     // thus done optionally. It is seen that duplicating context profiles into
533     // base profiles improves the code quality for thinlto build by allowing a
534     // profile in the prelink phase for to-be-fully-inlined functions.
535     if (!NodeProfile) {
536       ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
537     } else if (GenerateMergedBaseProfiles) {
538       ProfileMap[ChildProfile->getContext()].merge(*ChildProfile);
539       auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc);
540       SamplesMap[ChildProfile->getName().str()].getContext().setAttribute(
541           ContextDuplicatedIntoBase);
542     }
543 
544     // Remove the original child profile.
545     ProfileMap.erase(OrigChildContext);
546   }
547 }
548 
549 void CSProfileConverter::convertProfiles() { convertProfiles(RootFrame); }
550