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