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