LLVM 24.0.0git
SampleProf.h
Go to the documentation of this file.
1//===- SampleProf.h - Sampling profiling format support ---------*- C++ -*-===//
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#ifndef LLVM_PROFILEDATA_SAMPLEPROF_H
15#define LLVM_PROFILEDATA_SAMPLEPROF_H
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/Eytzinger.h"
20#include "llvm/ADT/MapVector.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/GlobalValue.h"
31#include "llvm/Support/Debug.h"
34#include <algorithm>
35#include <atomic>
36#include <cstdint>
37#include <list>
38#include <map>
39#include <sstream>
40#include <string>
41#include <system_error>
42#include <unordered_map>
43#include <utility>
44
45namespace llvm {
46
47class DILocation;
48class raw_ostream;
49
50LLVM_ABI const std::error_category &sampleprof_category();
51
70
71inline std::error_code make_error_code(sampleprof_error E) {
72 return std::error_code(static_cast<int>(E), sampleprof_category());
73}
74
76 sampleprof_error Result) {
77 // Prefer first error encountered as later errors may be secondary effects of
78 // the initial problem.
81 Accumulator = Result;
82 return Accumulator;
83}
84
85} // end namespace llvm
86
87namespace std {
88
89template <>
90struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
91
92} // end namespace std
93
94namespace llvm {
95namespace sampleprof {
96
97constexpr char kVTableProfPrefix[] = "vtables ";
98
101 SPF_Text = 0x1,
102 SPF_Compact_Binary = 0x2, // Deprecated
103 SPF_GCC = 0x3,
106};
107
113
115 return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
116 uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
117 uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
118 uint64_t('2') << (64 - 56) | uint64_t(Format);
119}
120
121// The oldest version of the extensible binary format we support.
122static constexpr uint64_t MinSupportedVersion = 103;
123
124// The default version of the extensible binary profile format written by the
125// compiler. We default to v103 as v104 is reserved for the in-progress on-disk
126// hash table.
127static constexpr uint64_t DefaultVersion = 103;
128
129// The first version that permits composite profile sections.
130static constexpr uint64_t CompositeProfileVersion = 105;
131
132// The latest supported version of the extensible binary profile format.
134
135// Query if a given format version is supported by this compiler.
139
140// Unused. Retained for downstream uses only.
141LLVM_DEPRECATED_WITH_FIXIT("Use DefaultVersion or LatestVersion instead",
142 "DefaultVersion")
143static inline uint64_t SPVersion() { return 103; }
144
145// Section Type used by SampleProfileExtBinaryBaseReader and
146// SampleProfileExtBinaryBaseWriter. Never change the existing
147// value of enum. Only append new ones.
156 // Function offset table used by the composite profile representation.
158 // marker for the first type of profile.
161 // Function profile section used by the composite profile representation.
163};
164
165static inline std::string getSecName(SecType Type) {
166 switch (static_cast<int>(Type)) { // Avoid -Wcovered-switch-default
167 case SecInValid:
168 return "InvalidSection";
169 case SecProfSummary:
170 return "ProfileSummarySection";
171 case SecNameTable:
172 return "NameTableSection";
174 return "ProfileSymbolListSection";
176 return "FuncOffsetTableSection";
177 case SecFuncMetadata:
178 return "FunctionMetadata";
179 case SecCSNameTable:
180 return "CSNameTableSection";
182 return "CompositeFuncOffsetTableSection";
183 case SecLBRProfile:
184 return "LBRProfileSection";
186 return "CompositeProfileSection";
187 default:
188 return "UnknownSection";
189 }
190}
191
192// Types of sample profiles that can be placed in SecCompositeProfile. These
193// values are persisted on disk; never change existing values, only append new
194// profile type IDs.
196
198 switch (Type) {
199 case ProfTypeLBR:
200 return "LBR";
201 default:
202 return "unknown";
203 }
204}
205
206// Entry type of section header table used by SampleProfileExtBinaryBaseReader
207// and SampleProfileExtBinaryBaseWriter.
213 // The index indicating the location of the current entry in
214 // SectionHdrLayout table.
216};
217
218// Flags common for all sections are defined here. In SecHdrTableEntry::Flags,
219// common flags will be saved in the lower 32bits and section specific flags
220// will be saved in the higher 32 bits.
223 SecFlagCompress = (1 << 0),
224 // Indicate the section contains flat profiles (without callsite samples).
225 SecFlagFlat = (1 << 1)
226};
227
228// Section specific flags are defined here.
229// !!!Note: Everytime a new enum class is created here, please add
230// a new check in verifySecFlag.
233 SecFlagMD5Name = (1 << 0),
234 // Store MD5 in fixed length instead of ULEB128 so NameTable can be
235 // accessed like an array.
237 // Profile contains ".__uniq." suffix name. Compiler shouldn't strip
238 // the suffix when doing profile matching when seeing the flag.
240 // Name table is stored in 3-span Eytzinger layout (Nested, Flat, Inlinees).
242};
243
244enum class EytzingerSpan : size_t { Nested, Flat, Inlinee, NumSpans };
245
252 /// SecFlagPartial means the profile is for common/shared code.
253 /// The common profile is usually merged from profiles collected
254 /// from running other targets.
255 SecFlagPartial = (1 << 0),
256 /// SecFlagContext means this is context-sensitive flat profile for
257 /// CSSPGO
259 /// SecFlagFSDiscriminator means this profile uses flow-sensitive
260 /// discriminators.
262 /// SecFlagIsPreInlined means this profile contains ShouldBeInlined
263 /// contexts thus this is CS preinliner computed.
265
266 /// SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
268};
269
275
278 // Store function offsets in an order of contexts. The order ensures that
279 // callee contexts of a given context laid out next to it.
280 SecFlagOrdered = (1 << 0),
281 // Store function offsets in a parallel array aligned with Eytzinger NameTable
282 // span.
284};
285
286// Verify section specific flag is used for the correct section.
287template <class SecFlagType>
288static inline void verifySecFlag(SecType Type, SecFlagType Flag) {
289 // No verification is needed for common flags.
290 if (std::is_same<SecCommonFlags, SecFlagType>())
291 return;
292
293 // Verification starts here for section specific flag.
294 bool IsFlagLegal = false;
295 switch (Type) {
296 case SecNameTable:
297 IsFlagLegal = std::is_same<SecNameTableFlags, SecFlagType>();
298 break;
300 IsFlagLegal = std::is_same<SecProfileSymbolListFlags, SecFlagType>();
301 break;
302 case SecProfSummary:
303 IsFlagLegal = std::is_same<SecProfSummaryFlags, SecFlagType>();
304 break;
305 case SecFuncMetadata:
306 IsFlagLegal = std::is_same<SecFuncMetadataFlags, SecFlagType>();
307 break;
310 IsFlagLegal = std::is_same<SecFuncOffsetFlags, SecFlagType>();
311 break;
312 default:
313 break;
314 }
315 if (!IsFlagLegal)
316 llvm_unreachable("Misuse of a flag in an incompatible section");
317}
318
319template <class SecFlagType>
320static inline void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
321 verifySecFlag(Entry.Type, Flag);
322 auto FVal = static_cast<uint64_t>(Flag);
323 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
324 Entry.Flags |= IsCommon ? FVal : (FVal << 32);
325}
326
327template <class SecFlagType>
328static inline void removeSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
329 verifySecFlag(Entry.Type, Flag);
330 auto FVal = static_cast<uint64_t>(Flag);
331 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
332 Entry.Flags &= ~(IsCommon ? FVal : (FVal << 32));
333}
334
335template <class SecFlagType>
336static inline bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag) {
337 verifySecFlag(Entry.Type, Flag);
338 auto FVal = static_cast<uint64_t>(Flag);
339 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
340 return Entry.Flags & (IsCommon ? FVal : (FVal << 32));
341}
342
343/// Represents the relative location of an instruction.
344///
345/// Instruction locations are specified by the line offset from the
346/// beginning of the function (marked by the line where the function
347/// header is) and the discriminator value within that line.
348///
349/// The discriminator value is useful to distinguish instructions
350/// that are on the same line but belong to different basic blocks
351/// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
354
355 LLVM_ABI void print(raw_ostream &OS) const;
356 LLVM_ABI void dump() const;
357
358 // Serialize the line location to the output stream using ULEB128 encoding.
359 LLVM_ABI void serialize(raw_ostream &OS) const;
360
361 bool operator<(const LineLocation &O) const {
362 return std::tie(LineOffset, Discriminator) <
363 std::tie(O.LineOffset, O.Discriminator);
364 }
365
366 bool operator==(const LineLocation &O) const {
367 return LineOffset == O.LineOffset && Discriminator == O.Discriminator;
368 }
369
370 bool operator!=(const LineLocation &O) const {
371 return LineOffset != O.LineOffset || Discriminator != O.Discriminator;
372 }
373
375 return ((uint64_t)Discriminator << 32) | LineOffset;
376 }
377
380};
381
383
384} // end namespace sampleprof
385
387 static unsigned getHashValue(const sampleprof::LineLocation &Val) {
389 }
390
393 return LHS == RHS;
394 }
395};
396
397namespace sampleprof {
398
399/// Key represents type of a C++ polymorphic class type by its vtable and value
400/// represents its counter.
401/// TODO: The class name FunctionId should be renamed to SymbolId in a refactor
402/// change.
404
405/// Write \p Map to the output stream. Keys are linearized using \p NameTable
406/// and written as ULEB128. Values are written as ULEB128 as well.
407LLVM_ABI std::error_code
409 const MapVector<FunctionId, uint32_t> &NameTable,
410 raw_ostream &OS);
411
412/// Representation of a single sample record.
413///
414/// A sample record is represented by a positive integer value, which
415/// indicates how frequently was the associated line location executed.
416///
417/// Additionally, if the associated location contains a function call,
418/// the record will hold a list of all the possible called targets and the types
419/// for virtual table dispatches. For direct calls, this will be the exact
420/// function being invoked. For indirect calls (function pointers, virtual table
421/// dispatch), this will be a list of one or more functions. For virtual table
422/// dispatches, this record will also hold the type of the object.
424public:
425 using CallTarget = std::pair<FunctionId, uint64_t>;
427 bool operator()(const CallTarget &LHS, const CallTarget &RHS) const {
428 if (LHS.second != RHS.second)
429 return LHS.second > RHS.second;
430
431 return LHS.first < RHS.first;
432 }
433 };
434
437 SampleRecord() = default;
438
439 /// Increment the number of samples for this record by \p S.
440 /// Optionally scale sample count \p S by \p Weight.
441 ///
442 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
443 /// around unsigned integers.
445 bool Overflowed;
446 NumSamples = SaturatingMultiplyAdd(S, Weight, NumSamples, &Overflowed);
447 return Overflowed ? sampleprof_error::counter_overflow
449 }
450
451 /// Decrease the number of samples for this record by \p S. Return the amout
452 /// of samples actually decreased.
454 if (S > NumSamples)
455 S = NumSamples;
456 NumSamples -= S;
457 return S;
458 }
459
460 /// Add called function \p F with samples \p S.
461 /// Optionally scale sample count \p S by \p Weight.
462 ///
463 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
464 /// around unsigned integers.
466 uint64_t Weight = 1) {
467 uint64_t &TargetSamples = CallTargets[F];
468 bool Overflowed;
469 TargetSamples =
470 SaturatingMultiplyAdd(S, Weight, TargetSamples, &Overflowed);
471 return Overflowed ? sampleprof_error::counter_overflow
473 }
474
475 /// Remove called function from the call target map. Return the target sample
476 /// count of the called function.
478 uint64_t Count = 0;
479 auto I = CallTargets.find(F);
480 if (I != CallTargets.end()) {
481 Count = I->second;
482 CallTargets.erase(I);
483 }
484 return Count;
485 }
486
487 /// Return true if this sample record contains function calls.
488 bool hasCalls() const { return !CallTargets.empty(); }
489
490 uint64_t getSamples() const { return NumSamples; }
491 /// Return the call targets collected in this sample record.
492 /// The returned reference may be invalidated by subsequent modifications to
493 /// this SampleRecord.
495 return CallTargets;
496 }
498 return sortCallTargets(CallTargets);
499 }
500
502 uint64_t Sum = 0;
503 for (const auto &I : CallTargets)
504 Sum += I.second;
505 return Sum;
506 }
507
508 /// Sort call targets in descending order of call frequency.
510 auto SortedTargets = llvm::to_vector_of<CallTarget>(Targets);
511 llvm::sort(SortedTargets, CallTargetComparator());
512 return SortedTargets;
513 }
514
515 /// Prorate call targets by a distribution factor.
516 static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets,
517 float DistributionFactor) {
518 CallTargetMap AdjustedTargets;
519 for (const auto &[Target, Frequency] : Targets) {
520 AdjustedTargets[Target] = Frequency * DistributionFactor;
521 }
522 return AdjustedTargets;
523 }
524
525 /// Merge the samples in \p Other into this record.
526 /// Optionally scale sample counts by \p Weight.
528 uint64_t Weight = 1);
529 LLVM_ABI void print(raw_ostream &OS, unsigned Indent) const;
530 LLVM_ABI void dump() const;
531 /// Serialize the sample record to the output stream using ULEB128 encoding.
532 /// The \p NameTable is used to map function names to their IDs.
533 LLVM_ABI std::error_code
535 const MapVector<FunctionId, uint32_t> &NameTable) const;
536
537 bool operator==(const SampleRecord &Other) const {
538 return NumSamples == Other.NumSamples && CallTargets == Other.CallTargets;
539 }
540
541 bool operator!=(const SampleRecord &Other) const { return !(*this == Other); }
542
543private:
544 uint64_t NumSamples = 0;
545 CallTargetMap CallTargets;
546};
547
549
550// State of context associated with FunctionSamples
552 UnknownContext = 0x0, // Profile without context
553 RawContext = 0x1, // Full context profile from input profile
554 SyntheticContext = 0x2, // Synthetic context created for context promotion
555 InlinedContext = 0x4, // Profile for context that is inlined into caller
556 MergedContext = 0x8 // Profile for context merged into base profile
557};
558
559// Attribute of context associated with FunctionSamples
562 ContextWasInlined = 0x1, // Leaf of context was inlined in previous build
563 ContextShouldBeInlined = 0x2, // Leaf of context should be inlined
565 0x4, // Leaf of context is duplicated into the base profile
566};
567
568// Represents a context frame with profile function and line location
572
574
577
578 bool operator==(const SampleContextFrame &That) const {
579 return Location == That.Location && Func == That.Func;
580 }
581
582 bool operator!=(const SampleContextFrame &That) const {
583 return !(*this == That);
584 }
585
586 std::string toString(bool OutputLineLocation) const {
587 std::ostringstream OContextStr;
588 OContextStr << Func.str();
589 if (OutputLineLocation) {
590 OContextStr << ":" << Location.LineOffset;
591 if (Location.Discriminator)
592 OContextStr << "." << Location.Discriminator;
593 }
594 return OContextStr.str();
595 }
596
598 // Context frame hash is heavily used in llvm-profgen context-sensitive
599 // pre-inliner. Use a lightweight hashing here to avoid speed regression.
600 uint64_t NameHash = 0;
601 if (Func.isStringRef())
602 NameHash = std::hash<std::string>{}(Func.str());
603 else
604 NameHash = Func.getHashCode();
605 uint64_t LocId = Location.getHashCode();
606 return NameHash + (LocId << 5) + LocId;
607 }
608};
609
610static inline hash_code hash_value(const SampleContextFrame &arg) {
611 return arg.getHashCode();
612}
613
616
622
623// Sample context for FunctionSamples. It consists of the calling context,
624// the function name and context state. Internally sample context is represented
625// using ArrayRef, which is also the input for constructing a `SampleContext`.
626// It can accept and represent both full context string as well as context-less
627// function name.
628// For a CS profile, a full context vector can look like:
629// `main:3 _Z5funcAi:1 _Z8funcLeafi`
630// For a base CS profile without calling context, the context vector should only
631// contain the leaf frame name.
632// For a non-CS profile, the context vector should be empty.
634public:
635 SampleContext() : State(UnknownContext), Attributes(ContextNone) {}
636
638 : Func(Name), State(UnknownContext), Attributes(ContextNone) {
639 assert(!Name.empty() && "Name is empty");
640 }
641
643 : Func(Func), State(UnknownContext), Attributes(ContextNone) {}
644
647 : Attributes(ContextNone) {
648 assert(!Context.empty() && "Context is empty");
649 setContext(Context, CState);
650 }
651
652 // Give a context string, decode and populate internal states like
653 // Function name, Calling context and context state. Example of input
654 // `ContextStr`: `[main:3 @ _Z5funcAi:1 @ _Z8funcLeafi]`
656 std::list<SampleContextFrameVector> &CSNameTable,
658 : Attributes(ContextNone) {
659 assert(!ContextStr.empty());
660 // Note that `[]` wrapped input indicates a full context string, otherwise
661 // it's treated as context-less function name only.
662 bool HasContext = ContextStr.starts_with("[");
663 if (!HasContext) {
664 State = UnknownContext;
665 Func = FunctionId(ContextStr);
666 } else {
667 CSNameTable.emplace_back();
668 SampleContextFrameVector &Context = CSNameTable.back();
669 createCtxVectorFromStr(ContextStr, Context);
670 setContext(Context, CState);
671 }
672 }
673
674 /// Create a context vector from a given context string and save it in
675 /// `Context`.
676 static void createCtxVectorFromStr(StringRef ContextStr,
677 SampleContextFrameVector &Context) {
678 // Remove encapsulating '[' and ']' if any
679 ContextStr = ContextStr.substr(1, ContextStr.size() - 2);
680 StringRef ContextRemain = ContextStr;
681 StringRef ChildContext;
682 FunctionId Callee;
683 while (!ContextRemain.empty()) {
684 auto ContextSplit = ContextRemain.split(" @ ");
685 ChildContext = ContextSplit.first;
686 ContextRemain = ContextSplit.second;
687 LineLocation CallSiteLoc(0, 0);
688 decodeContextString(ChildContext, Callee, CallSiteLoc);
689 Context.emplace_back(Callee, CallSiteLoc);
690 }
691 }
692
693 // Decode context string for a frame to get function name and location.
694 // `ContextStr` is in the form of `FuncName:StartLine.Discriminator`.
695 static void decodeContextString(StringRef ContextStr, FunctionId &Func,
696 LineLocation &LineLoc) {
697 // Get function name
698 auto EntrySplit = ContextStr.split(':');
699 Func = FunctionId(EntrySplit.first);
700
701 LineLoc = {0, 0};
702 if (!EntrySplit.second.empty()) {
703 // Get line offset, use signed int for getAsInteger so string will
704 // be parsed as signed.
705 int LineOffset = 0;
706 auto LocSplit = EntrySplit.second.split('.');
707 LocSplit.first.getAsInteger(10, LineOffset);
708 LineLoc.LineOffset = LineOffset;
709
710 // Get discriminator
711 if (!LocSplit.second.empty())
712 LocSplit.second.getAsInteger(10, LineLoc.Discriminator);
713 }
714 }
715
716 operator SampleContextFrames() const { return FullContext; }
717 bool hasAttribute(ContextAttributeMask A) { return Attributes & (uint32_t)A; }
718 void setAttribute(ContextAttributeMask A) { Attributes |= (uint32_t)A; }
719 uint32_t getAllAttributes() { return Attributes; }
720 void setAllAttributes(uint32_t A) { Attributes = A; }
721 bool hasState(ContextStateMask S) { return State & (uint32_t)S; }
722 void setState(ContextStateMask S) { State |= (uint32_t)S; }
723 void clearState(ContextStateMask S) { State &= (uint32_t)~S; }
724 bool hasContext() const { return State != UnknownContext; }
725 bool isBaseContext() const { return FullContext.size() == 1; }
726 FunctionId getFunction() const { return Func; }
727 SampleContextFrames getContextFrames() const { return FullContext; }
728
729 static std::string getContextString(SampleContextFrames Context,
730 bool IncludeLeafLineLocation = false) {
731 std::ostringstream OContextStr;
732 for (uint32_t I = 0; I < Context.size(); I++) {
733 if (OContextStr.str().size()) {
734 OContextStr << " @ ";
735 }
736 OContextStr << Context[I].toString(I != Context.size() - 1 ||
737 IncludeLeafLineLocation);
738 }
739 return OContextStr.str();
740 }
741
742 std::string toString() const {
743 if (!hasContext())
744 return Func.str();
745 return getContextString(FullContext, false);
746 }
747
749 if (hasContext())
751 return getFunction().getHashCode();
752 }
753
754 /// Set the name of the function and clear the current context.
755 void setFunction(FunctionId NewFunctionID) {
756 Func = NewFunctionID;
757 FullContext = SampleContextFrames();
758 State = UnknownContext;
759 }
760
762 ContextStateMask CState = RawContext) {
763 assert(CState != UnknownContext);
764 FullContext = Context;
765 Func = Context.back().Func;
766 State = CState;
767 }
768
769 bool operator==(const SampleContext &That) const {
770 return State == That.State && Func == That.Func &&
771 FullContext == That.FullContext;
772 }
773
774 bool operator!=(const SampleContext &That) const { return !(*this == That); }
775
776 bool operator<(const SampleContext &That) const {
777 if (State != That.State)
778 return State < That.State;
779
780 if (!hasContext()) {
781 return Func < That.Func;
782 }
783
784 uint64_t I = 0;
785 while (I < std::min(FullContext.size(), That.FullContext.size())) {
786 auto &Context1 = FullContext[I];
787 auto &Context2 = That.FullContext[I];
788 auto V = Context1.Func.compare(Context2.Func);
789 if (V)
790 return V < 0;
791 if (Context1.Location != Context2.Location)
792 return Context1.Location < Context2.Location;
793 I++;
794 }
795
796 return FullContext.size() < That.FullContext.size();
797 }
798
799 struct Hash {
800 uint64_t operator()(const SampleContext &Context) const {
801 return Context.getHashCode();
802 }
803 };
804
805 bool isPrefixOf(const SampleContext &That) const {
806 auto ThisContext = FullContext;
807 auto ThatContext = That.FullContext;
808 if (ThatContext.size() < ThisContext.size())
809 return false;
810 ThatContext = ThatContext.take_front(ThisContext.size());
811 // Compare Leaf frame first
812 if (ThisContext.back().Func != ThatContext.back().Func)
813 return false;
814 // Compare leading context
815 return ThisContext.drop_back() == ThatContext.drop_back();
816 }
817
818private:
819 // The function associated with this context. If CS profile, this is the leaf
820 // function.
821 FunctionId Func;
822 // Full context including calling context and leaf function name
823 SampleContextFrames FullContext;
824 // State of the associated sample profile
825 uint32_t State;
826 // Attribute of the associated sample profile
827 uint32_t Attributes;
828};
829
830static inline hash_code hash_value(const SampleContext &Context) {
831 return Context.getHashCode();
832}
833
834inline raw_ostream &operator<<(raw_ostream &OS, const SampleContext &Context) {
835 return OS << Context.toString();
836}
837
838class FunctionSamples;
840
842// NOTE: Using a StringMap here makes parsed profiles consume around 17% more
843// memory, which is *very* significant for large profiles.
844using FunctionSamplesMap = std::map<FunctionId, FunctionSamples>;
845using CallsiteSampleMap = std::map<LineLocation, FunctionSamplesMap>;
848
849/// Representation of the samples collected for a function.
850///
851/// This data structure contains all the collected samples for the body
852/// of a function. Each sample corresponds to a LineLocation instance
853/// within the body of the function.
855public:
856 FunctionSamples() = default;
857
858 LLVM_ABI void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
859 LLVM_ABI void dump() const;
860
862 bool Overflowed;
863 TotalSamples =
864 SaturatingMultiplyAdd(Num, Weight, TotalSamples, &Overflowed);
865 return Overflowed ? sampleprof_error::counter_overflow
867 }
868
870 if (TotalSamples < Num)
871 TotalSamples = 0;
872 else
873 TotalSamples -= Num;
874 }
875
876 void setTotalSamples(uint64_t Num) { TotalSamples = Num; }
877
878 void setHeadSamples(uint64_t Num) { TotalHeadSamples = Num; }
879
881 bool Overflowed;
882 TotalHeadSamples =
883 SaturatingMultiplyAdd(Num, Weight, TotalHeadSamples, &Overflowed);
884 return Overflowed ? sampleprof_error::counter_overflow
886 }
887
889 uint64_t Num, uint64_t Weight = 1) {
890 return BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(
891 Num, Weight);
892 }
893
895 uint32_t Discriminator,
896 FunctionId Func, uint64_t Num,
897 uint64_t Weight = 1) {
898 return BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(
899 Func, Num, Weight);
900 }
901
904 uint64_t Weight = 1) {
905 return BodySamples[Location].merge(SampleRecord, Weight);
906 }
907
908 void reserveBodySamples(size_t NumEntries) {
909 BodySamples.reserve(NumEntries);
910 }
911
912 void reserveCallsiteTypeCounts(size_t NumEntries) {
913 VirtualCallsiteTypeCounts.reserve(NumEntries);
914 }
915
916 // Remove a call target and decrease the body sample correspondingly. Return
917 // the number of body samples actually decreased.
919 uint32_t Discriminator,
920 FunctionId Func) {
921 uint64_t Count = 0;
922 auto I = BodySamples.find(LineLocation(LineOffset, Discriminator));
923 if (I != BodySamples.end()) {
924 Count = I->second.removeCalledTarget(Func);
925 Count = I->second.removeSamples(Count);
926 if (!I->second.getSamples())
927 BodySamples.erase(I);
928 }
929 return Count;
930 }
931
932 // Remove all call site samples for inlinees. This is needed when flattening
933 // a nested profile.
934 void removeAllCallsiteSamples() { CallsiteSamples.clear(); }
935
936 // Accumulate all call target samples to update the body samples.
938 for (auto &I : BodySamples) {
939 uint64_t TargetSamples = I.second.getCallTargetSum();
940 // It's possible that the body sample count can be greater than the call
941 // target sum. E.g, if some call targets are external targets, they won't
942 // be considered valid call targets, but the body sample count which is
943 // from lbr ranges can actually include them.
944 if (TargetSamples > I.second.getSamples())
945 I.second.addSamples(TargetSamples - I.second.getSamples());
946 }
947 }
948
949 // Accumulate all body samples to set total samples.
952 for (const auto &I : BodySamples)
953 addTotalSamples(I.second.getSamples());
954
955 for (auto &I : CallsiteSamples) {
956 for (auto &CS : I.second) {
957 CS.second.updateTotalSamples();
958 addTotalSamples(CS.second.getTotalSamples());
959 }
960 }
961 }
962
963 // Set current context and all callee contexts to be synthetic.
965 Context.setState(SyntheticContext);
966 for (auto &I : CallsiteSamples) {
967 for (auto &CS : I.second) {
968 CS.second.setContextSynthetic();
969 }
970 }
971 }
972
973 // Propagate the given attribute to this profile context and all callee
974 // contexts.
976 Context.setAttribute(Attr);
977 for (auto &I : CallsiteSamples) {
978 for (auto &CS : I.second) {
979 CS.second.setContextAttribute(Attr);
980 }
981 }
982 }
983
984 // Query the stale profile matching results and remap the location.
985 const LineLocation &mapIRLocToProfileLoc(const LineLocation &IRLoc) const {
986 // There is no remapping if the profile is not stale or the matching gives
987 // the same location.
988 if (!IRToProfileLocationMap)
989 return IRLoc;
990 const auto &ProfileLoc = IRToProfileLocationMap->find(IRLoc);
991 if (ProfileLoc != IRToProfileLocationMap->end())
992 return ProfileLoc->second;
993 return IRLoc;
994 }
995
996 /// Return the number of samples collected at the given location.
997 /// Each location is specified by \p LineOffset and \p Discriminator.
998 /// If the location is not found in profile, return error.
1000 uint32_t Discriminator) const {
1001 const auto &Ret = BodySamples.find(
1002 mapIRLocToProfileLoc(LineLocation(LineOffset, Discriminator)));
1003 if (Ret == BodySamples.end())
1004 return std::error_code();
1005 return Ret->second.getSamples();
1006 }
1007
1008 /// Returns the call target map collected at a given location.
1009 /// Each location is specified by \p LineOffset and \p Discriminator.
1010 /// If the location is not found in profile, return error.
1011 /// The returned reference may be invalidated by subsequent modifications to
1012 /// this FunctionSamples.
1015 uint32_t Discriminator) const LLVM_LIFETIME_BOUND {
1016 const auto &Ret = BodySamples.find(
1017 mapIRLocToProfileLoc(LineLocation(LineOffset, Discriminator)));
1018 if (Ret == BodySamples.end())
1019 return std::error_code();
1020 return Ret->second.getCallTargets();
1021 }
1022
1023 /// Returns the call target map collected at a given location specified by \p
1024 /// CallSite. If the location is not found in profile, return error.
1025 /// The returned reference may be invalidated by subsequent modifications to
1026 /// this FunctionSamples.
1029 const auto &Ret = BodySamples.find(mapIRLocToProfileLoc(CallSite));
1030 if (Ret == BodySamples.end())
1031 return std::error_code();
1032 return Ret->second.getCallTargets();
1033 }
1034
1035 /// Return the function samples at the given callsite location.
1038 return CallsiteSamples[mapIRLocToProfileLoc(Loc)];
1039 }
1040
1041 /// Returns the FunctionSamplesMap at the given \p Loc.
1042 const FunctionSamplesMap *
1044 auto Iter = CallsiteSamples.find(mapIRLocToProfileLoc(Loc));
1045 if (Iter == CallsiteSamples.end())
1046 return nullptr;
1047 return &Iter->second;
1048 }
1049
1050 /// Returns the TypeCountMap for inlined callsites at the given \p Loc.
1051 /// The returned pointer may be invalidated by subsequent modifications to
1052 /// this FunctionSamples.
1053 const TypeCountMap *
1055 auto Iter = VirtualCallsiteTypeCounts.find(mapIRLocToProfileLoc(Loc));
1056 if (Iter == VirtualCallsiteTypeCounts.end())
1057 return nullptr;
1058 return &Iter->second;
1059 }
1060
1061 /// Returns a pointer to FunctionSamples at the given callsite location
1062 /// \p Loc with callee \p CalleeName. If no callsite can be found, relax
1063 /// the restriction to return the FunctionSamples at callsite location
1064 /// \p Loc with the maximum total sample count. If \p Remapper or \p
1065 /// FuncNameToProfNameMap is not nullptr, use them to find FunctionSamples
1066 /// with equivalent name as \p CalleeName.
1068 const LineLocation &Loc, StringRef CalleeName,
1071 *FuncNameToProfNameMap = nullptr) const LLVM_LIFETIME_BOUND;
1072
1073 bool empty() const { return TotalSamples == 0; }
1074
1075 /// Return the total number of samples collected inside the function.
1076 uint64_t getTotalSamples() const { return TotalSamples; }
1077
1078 /// For top-level functions, return the total number of branch samples that
1079 /// have the function as the branch target (or 0 otherwise). This is the raw
1080 /// data fetched from the profile. This should be equivalent to the sample of
1081 /// the first instruction of the symbol. But as we directly get this info for
1082 /// raw profile without referring to potentially inaccurate debug info, this
1083 /// gives more accurate profile data and is preferred for standalone symbols.
1084 uint64_t getHeadSamples() const { return TotalHeadSamples; }
1085
1086 /// Return an estimate of the sample count of the function entry basic block.
1087 /// The function can be either a standalone symbol or an inlined function.
1088 /// For Context-Sensitive profiles, this will prefer returning the head
1089 /// samples (i.e. getHeadSamples()), if non-zero. Otherwise it estimates from
1090 /// the function body's samples or callsite samples.
1093 // For CS profile, if we already have more accurate head samples
1094 // counted by branch sample from caller, use them as entry samples.
1095 return getHeadSamples();
1096 }
1097 uint64_t Count = 0;
1098 // Use either BodySamples or CallsiteSamples which ever has the smaller
1099 // lineno.
1100 if (!BodySamples.empty() &&
1101 (CallsiteSamples.empty() ||
1102 BodySamples.begin()->first < CallsiteSamples.begin()->first))
1103 Count = BodySamples.begin()->second.getSamples();
1104 else if (!CallsiteSamples.empty()) {
1105 // An indirect callsite may be promoted to several inlined direct calls.
1106 // We need to get the sum of them.
1107 for (const auto &FuncSamples : CallsiteSamples.begin()->second)
1108 Count += FuncSamples.second.getHeadSamplesEstimate();
1109 }
1110 // Return at least 1 if total sample is not 0.
1111 return Count ? Count : TotalSamples > 0;
1112 }
1113
1114 /// Return all the samples collected in the body of the function.
1115 /// The returned reference may be invalidated by subsequent modifications to
1116 /// this FunctionSamples.
1118 return BodySamples;
1119 }
1120
1121 /// Return all the callsite samples collected in the body of the function.
1123 return CallsiteSamples;
1124 }
1125
1126 /// Return whether this function profile contains callsite samples.
1127 bool hasCallsiteSamples() const { return !CallsiteSamples.empty(); }
1128
1129 /// Returns vtable access samples for the C++ types collected in this
1130 /// function.
1131 /// The returned reference may be invalidated by subsequent modifications to
1132 /// this FunctionSamples.
1134 return VirtualCallsiteTypeCounts;
1135 }
1136
1137 /// Returns the vtable access samples for the C++ types for \p Loc.
1138 /// Under the hood, the caller-specified \p Loc will be un-drifted before the
1139 /// type sample lookup if possible.
1140 /// The returned reference may be invalidated by subsequent modifications to
1141 /// this FunctionSamples.
1143 return VirtualCallsiteTypeCounts[mapIRLocToProfileLoc(Loc)];
1144 }
1145
1146 /// At location \p Loc, add a type sample for the given \p Type with
1147 /// \p Count. This function uses saturating add which clamp the result to
1148 /// maximum uint64_t (the counter type), and inserts the saturating add result
1149 /// to map. Returns counter_overflow to caller if the actual result is larger
1150 /// than maximum uint64_t.
1152 uint64_t Count) {
1153 auto &TypeCounts = getTypeSamplesAt(Loc);
1154 bool Overflowed = false;
1155 TypeCounts[Type] = SaturatingMultiplyAdd(Count, /* Weight= */ (uint64_t)1,
1156 TypeCounts[Type], &Overflowed);
1157 return Overflowed ? sampleprof_error::counter_overflow
1159 }
1160
1161 /// Scale \p Other sample counts by \p Weight and add the scaled result to the
1162 /// type samples for \p Loc. Under the hoold, the caller-provided \p Loc will
1163 /// be un-drifted before the type sample lookup if possible.
1164 /// typename T is either a std::map or a DenseMap.
1165 template <typename T>
1167 const T &Other,
1168 uint64_t Weight = 1) {
1169 static_assert((std::is_same_v<typename T::key_type, StringRef> ||
1170 std::is_same_v<typename T::key_type, FunctionId>) &&
1171 std::is_same_v<typename T::mapped_type, uint64_t>,
1172 "T must be a map with StringRef or FunctionId as key and "
1173 "uint64_t as value");
1174 TypeCountMap &TypeCounts = getTypeSamplesAt(Loc);
1175 TypeCounts.reserve(TypeCounts.size() + Other.size());
1176 bool Overflowed = false;
1177
1178 for (const auto &[Type, Count] : Other) {
1179 FunctionId TypeId(Type);
1180 bool RowOverflow = false;
1181 TypeCounts[TypeId] = SaturatingMultiplyAdd(
1182 Count, Weight, TypeCounts[TypeId], &RowOverflow);
1183 Overflowed |= RowOverflow;
1184 }
1185 return Overflowed ? sampleprof_error::counter_overflow
1187 }
1188
1189 /// Return the maximum of sample counts in a function body. When SkipCallSite
1190 /// is false, which is the default, the return count includes samples in the
1191 /// inlined functions. When SkipCallSite is true, the return count only
1192 /// considers the body samples.
1193 uint64_t getMaxCountInside(bool SkipCallSite = false) const {
1194 uint64_t MaxCount = 0;
1195 for (const auto &L : getBodySamples())
1196 MaxCount = std::max(MaxCount, L.second.getSamples());
1197 if (SkipCallSite)
1198 return MaxCount;
1199 for (const auto &C : getCallsiteSamples())
1200 for (const FunctionSamplesMap::value_type &F : C.second)
1201 MaxCount = std::max(MaxCount, F.second.getMaxCountInside());
1202 return MaxCount;
1203 }
1204
1205 /// Merge the samples in \p Other into this one.
1206 /// Optionally scale samples by \p Weight.
1209 if (!GUIDToFuncNameMap)
1210 GUIDToFuncNameMap = Other.GUIDToFuncNameMap;
1211 if (Context.getFunction().empty())
1212 Context = Other.getContext();
1213 if (FunctionHash == 0) {
1214 // Set the function hash code for the target profile.
1215 FunctionHash = Other.getFunctionHash();
1216 } else if (FunctionHash != Other.getFunctionHash()) {
1217 // The two profiles coming with different valid hash codes indicates
1218 // either:
1219 // 1. They are same-named static functions from different compilation
1220 // units (without using -unique-internal-linkage-names), or
1221 // 2. They are really the same function but from different compilations.
1222 // Let's bail out in either case for now, which means one profile is
1223 // dropped.
1225 }
1226
1227 mergeSampleProfErrors(Result,
1228 addTotalSamples(Other.getTotalSamples(), Weight));
1229 mergeSampleProfErrors(Result,
1230 addHeadSamples(Other.getHeadSamples(), Weight));
1231 BodySamples.reserve(BodySamples.size() + Other.getBodySamples().size());
1232 for (const auto &I : Other.getBodySamples()) {
1233 const LineLocation &Loc = I.first;
1234 const SampleRecord &Rec = I.second;
1235 mergeSampleProfErrors(Result, BodySamples[Loc].merge(Rec, Weight));
1236 }
1237 for (const auto &I : Other.getCallsiteSamples()) {
1238 const LineLocation &Loc = I.first;
1240 for (const auto &Rec : I.second)
1241 mergeSampleProfErrors(Result,
1242 FSMap[Rec.first].merge(Rec.second, Weight));
1243 }
1244 VirtualCallsiteTypeCounts.reserve(VirtualCallsiteTypeCounts.size() +
1245 Other.getCallsiteTypeCounts().size());
1246 for (const auto &[Loc, OtherTypeMap] : Other.getCallsiteTypeCounts())
1248 Result, addCallsiteVTableTypeProfAt(Loc, OtherTypeMap, Weight));
1249
1250 return Result;
1251 }
1252
1253 /// Add the import GUID of profiled function \p Name to \p S. Only functions
1254 /// defined outside this module need importing, unless \p IncludeLocal is
1255 /// set: then another module that imports the caller also imports the
1256 /// function, as needed for a deferred indirect call target.
1257 static void
1260 FunctionId Name, bool IncludeLocal) {
1261 const Function *F = SymbolMap.lookup(Name);
1262 if (!F || F->isDeclaration())
1263 S.insert(Name.getHashCode());
1264 else if (IncludeLocal)
1265 // GUID metadata is assigned at the end of pre-link, so use the fallback
1266 // identity, which includes the source file name for locals.
1267 S.insert(F->getGUIDOrFallback());
1268 }
1269
1270 /// Recursively collect import GUIDs from contexts with total samples greater
1271 /// than \p Threshold, including hot call targets in their body samples.
1272 /// \p IncludeLocalTargets is passed to addImportGUID.
1276 uint64_t Threshold, bool IncludeLocalTargets = false) const {
1277 if (TotalSamples <= Threshold)
1278 return;
1279 addImportGUID(S, SymbolMap, getFunction(), IncludeLocalTargets);
1280 // Import hot CallTargets, which may not be available in IR because full
1281 // profile annotation cannot be done until backend compilation in ThinLTO.
1282 for (const auto &BS : BodySamples)
1283 for (const auto &TS : BS.second.getCallTargets())
1284 if (TS.second > Threshold)
1285 addImportGUID(S, SymbolMap, TS.first, IncludeLocalTargets);
1286 for (const auto &CS : CallsiteSamples)
1287 for (const auto &NameFS : CS.second)
1288 NameFS.second.findInlinedFunctions(S, SymbolMap, Threshold,
1289 IncludeLocalTargets);
1290 }
1291
1292 /// Set the name of the function.
1293 void setFunction(FunctionId NewFunctionID) {
1294 Context.setFunction(NewFunctionID);
1295 }
1296
1297 /// Return the function name.
1298 FunctionId getFunction() const { return Context.getFunction(); }
1299
1300 /// Return the original function name.
1302
1303 void setFunctionHash(uint64_t Hash) { FunctionHash = Hash; }
1304
1305 uint64_t getFunctionHash() const { return FunctionHash; }
1306
1308 assert(IRToProfileLocationMap == nullptr && "this should be set only once");
1309 IRToProfileLocationMap = LTLM;
1310 }
1311
1312 /// Return the canonical name for a function, taking into account
1313 /// suffix elision policy attributes.
1315 const char *AttrName = "sample-profile-suffix-elision-policy";
1316 auto Attr = F.getFnAttribute(AttrName).getValueAsString();
1317 return getCanonicalFnName(F.getName(), Attr);
1318 }
1319
1320 /// Name suffixes which canonicalization should handle to avoid
1321 /// profile mismatch.
1322 static constexpr const char *LLVMSuffix = ".llvm.";
1323 static constexpr const char *PartSuffix = ".part.";
1324 static constexpr const char *UniqSuffix = ".__uniq.";
1325 // Appended by LowerTypeTests to the body of a CFI jump table member, whose
1326 // original name then refers to the jump table entry.
1327 static constexpr const char *CfiSuffix = ".cfi";
1328
1330 StringRef Attr = "selected") {
1331 // Note the sequence of the suffixes in the knownSuffixes array matters.
1332 // If suffix "A" is appended after the suffix "B", "A" should be in front
1333 // of "B" in knownSuffixes. The CFI suffix is appended in the ThinLTO
1334 // backend, after all the others.
1335 const SmallVector<StringRef> KnownSuffixes{CfiSuffix, LLVMSuffix,
1337 return getCanonicalFnName(FnName, KnownSuffixes, Attr);
1338 }
1339
1341 StringRef Attr = "selected") {
1342 // A local coroutine function from another CU can be promoted to a global
1343 // function during ThinLTO import. This will create a linkage name like
1344 // "_Zfoo.llvm.xxxx.cleanup". Remove the ".llvm." suffix after stripping all
1345 // the coroutine suffixes to avoid pseudo probe mismatch.
1346 const SmallVector<StringRef, 4> CoroSuffixes{".cleanup", ".destroy",
1347 ".resume", LLVMSuffix};
1348 return getCanonicalFnName(FnName, CoroSuffixes, Attr);
1349 }
1350
1352 ArrayRef<StringRef> Suffixes,
1353 StringRef Attr = "selected") {
1354 if (Attr == "" || Attr == "all")
1355 return FnName.split('.').first;
1356 if (Attr == "selected") {
1357 StringRef Cand(FnName);
1358 for (const auto Suffix : Suffixes) {
1359 // If the profile contains ".__uniq." suffix, don't strip the
1360 // suffix for names in the IR.
1362 continue;
1363 if (!Suffix.ends_with(".")) {
1364 Cand.consume_back(Suffix);
1365 continue;
1366 }
1367 auto It = Cand.rfind(Suffix);
1368 if (It == StringRef::npos)
1369 continue;
1370 auto Dit = Cand.rfind('.');
1371 if (Dit == It + Suffix.size() - 1)
1372 Cand = Cand.substr(0, It);
1373 }
1374 return Cand;
1375 }
1376 if (Attr == "none")
1377 return FnName;
1378 assert(false && "internal error: unknown suffix elision policy");
1379 return FnName;
1380 }
1381
1382 /// Translate \p Func into its original name.
1383 /// When profile doesn't use MD5, \p Func needs no translation.
1384 /// When profile uses MD5, \p Func in current FunctionSamples
1385 /// is actually GUID of the original function name. getFuncName will
1386 /// translate \p Func in current FunctionSamples into its original name
1387 /// by looking up in the function map GUIDToFuncNameMap.
1388 /// If the original name doesn't exist in the map, return empty StringRef.
1390 if (!UseMD5)
1391 return Func.stringRef();
1392
1394 "GUIDToFuncNameMap needs to be populated first");
1395 return GUIDToFuncNameMap->lookup(Func.getHashCode());
1396 }
1397
1398 /// Returns the line offset to the start line of the subprogram.
1399 /// We assume that a single function will not exceed 65535 LOC.
1400 LLVM_ABI static unsigned getOffset(const DILocation *DIL);
1401
1402 /// Returns a unique call site identifier for a given debug location of a call
1403 /// instruction. This is wrapper of two scenarios, the probe-based profile and
1404 /// regular profile, to hide implementation details from the sample loader and
1405 /// the context tracker.
1407 bool ProfileIsFS = false);
1408
1409 /// Returns a unique hash code for a combination of a callsite location and
1410 /// the callee function name.
1411 /// Guarantee MD5 and non-MD5 representation of the same function results in
1412 /// the same hash.
1414 const LineLocation &Callsite) {
1415 return SampleContextFrame(Callee, Callsite).getHashCode();
1416 }
1417
1418 /// Get the FunctionSamples of the inline instance where DIL originates
1419 /// from.
1420 ///
1421 /// The FunctionSamples of the instruction (Machine or IR) associated to
1422 /// \p DIL is the inlined instance in which that instruction is coming from.
1423 /// We traverse the inline stack of that instruction, and match it with the
1424 /// tree nodes in the profile.
1425 ///
1426 /// \returns the FunctionSamples pointer to the inlined instance.
1427 /// If \p Remapper or \p FuncNameToProfNameMap is not nullptr, it will be used
1428 /// to find matching FunctionSamples with not exactly the same but equivalent
1429 /// name.
1431 const DILocation *DIL,
1432 SampleProfileReaderItaniumRemapper *Remapper = nullptr,
1434 *FuncNameToProfNameMap = nullptr) const LLVM_LIFETIME_BOUND;
1435
1437
1438 void setContext(const SampleContext &FContext) { Context = FContext; }
1439
1440 // These boolean variables are atomic so that parallel in-process ThinLTO
1441 // backends writing the same value do not race.
1442 LLVM_ABI static std::atomic<bool> ProfileIsProbeBased;
1443
1444 LLVM_ABI static std::atomic<bool> ProfileIsCS;
1445
1446 LLVM_ABI static std::atomic<bool> ProfileIsPreInlined;
1447
1448 /// Whether the profile uses MD5 to represent string.
1449 LLVM_ABI static std::atomic<bool> UseMD5;
1450
1451 /// Whether the profile contains any ".__uniq." suffix in a name.
1452 LLVM_ABI static std::atomic<bool> HasUniqSuffix;
1453
1454 /// If this profile uses flow sensitive discriminators.
1455 LLVM_ABI static std::atomic<bool> ProfileIsFS;
1456
1457 /// GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
1458 /// all the function symbols defined or declared in current module.
1460
1461 /// Return the GUID of the context's name. If the context is already using
1462 /// MD5, don't hash it again.
1463 uint64_t getGUID() const { return getFunction().getHashCode(); }
1464
1465 // Find all the names in the current FunctionSamples including names in
1466 // all the inline instances and names of call targets.
1467 LLVM_ABI void findAllNames(DenseSet<FunctionId> &NameSet) const;
1468
1469 bool operator==(const FunctionSamples &Other) const {
1470 return (GUIDToFuncNameMap == Other.GUIDToFuncNameMap ||
1471 (GUIDToFuncNameMap && Other.GUIDToFuncNameMap &&
1472 *GUIDToFuncNameMap == *Other.GUIDToFuncNameMap)) &&
1473 FunctionHash == Other.FunctionHash && Context == Other.Context &&
1474 TotalSamples == Other.TotalSamples &&
1475 TotalHeadSamples == Other.TotalHeadSamples &&
1476 BodySamples == Other.BodySamples &&
1477 CallsiteSamples == Other.CallsiteSamples;
1478 }
1479
1480 bool operator!=(const FunctionSamples &Other) const {
1481 return !(*this == Other);
1482 }
1483
1484private:
1485 /// CFG hash value for the function.
1486 uint64_t FunctionHash = 0;
1487
1488 /// Calling context for function profile
1489 mutable SampleContext Context;
1490
1491 /// Total number of samples collected inside this function.
1492 ///
1493 /// Samples are cumulative, they include all the samples collected
1494 /// inside this function and all its inlined callees.
1495 uint64_t TotalSamples = 0;
1496
1497 /// Total number of samples collected at the head of the function.
1498 /// This is an approximation of the number of calls made to this function
1499 /// at runtime.
1500 uint64_t TotalHeadSamples = 0;
1501
1502 /// Map instruction locations to collected samples.
1503 ///
1504 /// Each entry in this map contains the number of samples
1505 /// collected at the corresponding line offset. All line locations
1506 /// are an offset from the start of the function.
1507 BodySampleMap BodySamples;
1508
1509 /// Map call sites to collected samples for the called function.
1510 ///
1511 /// Each entry in this map corresponds to all the samples
1512 /// collected for the inlined function call at the given
1513 /// location. For example, given:
1514 ///
1515 /// void foo() {
1516 /// 1 bar();
1517 /// ...
1518 /// 8 baz();
1519 /// }
1520 ///
1521 /// If the bar() and baz() calls were inlined inside foo(), this
1522 /// map will contain two entries. One for all the samples collected
1523 /// in the call to bar() at line offset 1, the other for all the samples
1524 /// collected in the call to baz() at line offset 8.
1525 CallsiteSampleMap CallsiteSamples;
1526
1527 /// Map a virtual callsite to the list of accessed vtables and vtable counts.
1528 /// The callsite is referenced by its source location.
1529 ///
1530 /// For example, given:
1531 ///
1532 /// void foo() {
1533 /// ...
1534 /// 5 inlined_vcall_bar();
1535 /// ...
1536 /// 5 inlined_vcall_baz();
1537 /// ...
1538 /// 200 inlined_vcall_qux();
1539 /// }
1540 /// This map will contain two entries. One with two types for line offset 5
1541 /// and one with one type for line offset 200.
1542 CallsiteTypeMap VirtualCallsiteTypeCounts;
1543
1544 /// IR to profile location map generated by stale profile matching.
1545 ///
1546 /// Each entry is a mapping from the location on current build to the matched
1547 /// location in the "stale" profile. For example:
1548 /// Profiled source code:
1549 /// void foo() {
1550 /// 1 bar();
1551 /// }
1552 ///
1553 /// Current source code:
1554 /// void foo() {
1555 /// 1 // Code change
1556 /// 2 bar();
1557 /// }
1558 /// Supposing the stale profile matching algorithm generated the mapping [2 ->
1559 /// 1], the profile query using the location of bar on the IR which is 2 will
1560 /// be remapped to 1 and find the location of bar in the profile.
1561 const LocToLocMap *IRToProfileLocationMap = nullptr;
1562};
1563
1564/// Get the proper representation of a string according to whether the
1565/// current Format uses MD5 to represent the string.
1567 if (Name.empty() || !FunctionSamples::UseMD5)
1568 return FunctionId(Name);
1570}
1571
1573
1574/// This class provides operator overloads to the map container using MD5 as the
1575/// key type, so that existing code can still work in most cases using
1576/// SampleContext as key.
1577/// Note: when populating container, make sure to assign the SampleContext to
1578/// the mapped value immediately because the key no longer holds it.
1580 : public HashKeyMap<std::unordered_map, SampleContext, FunctionSamples> {
1581public:
1582 // Convenience method because this is being used in many places. Set the
1583 // FunctionSamples' context if its newly inserted.
1585 auto Ret = try_emplace(Ctx, FunctionSamples());
1586 if (Ret.second)
1587 Ret.first->second.setContext(Ctx);
1588 return Ret.first->second;
1589 }
1590
1595
1600
1601 size_t erase(const SampleContext &Ctx) {
1602 return HashKeyMap<std::unordered_map, SampleContext,
1604 }
1605
1606 size_t erase(const key_type &Key) { return base_type::erase(Key); }
1607
1608 iterator erase(iterator It) { return base_type::erase(It); }
1609};
1610
1611using NameFunctionSamples = std::pair<hash_code, const FunctionSamples *>;
1612
1613LLVM_ABI void
1614sortFuncProfiles(const SampleProfileMap &ProfileMap,
1615 std::vector<NameFunctionSamples> &SortedProfiles);
1616
1617/// SampleContextTrimmer impelements helper functions to trim, merge cold
1618/// context profiles. It also supports context profile canonicalization to make
1619/// sure ProfileMap's key is consistent with FunctionSample's name/context.
1621public:
1622 SampleContextTrimmer(SampleProfileMap &Profiles) : ProfileMap(Profiles) {};
1623 // Trim and merge cold context profile when requested. TrimBaseProfileOnly
1624 // should only be effective when TrimColdContext is true. On top of
1625 // TrimColdContext, TrimBaseProfileOnly can be used to specify to trim all
1626 // cold profiles or only cold base profiles. Trimming base profiles only is
1627 // mainly to honor the preinliner decsion. Note that when MergeColdContext is
1628 // true, preinliner decsion is not honored anyway so TrimBaseProfileOnly will
1629 // be ignored.
1631 bool TrimColdContext,
1632 bool MergeColdContext,
1633 uint32_t ColdContextFrameLength,
1634 bool TrimBaseProfileOnly);
1635
1636private:
1637 SampleProfileMap &ProfileMap;
1638};
1639
1640/// Helper class for profile conversion.
1641///
1642/// It supports full context-sensitive profile to nested profile conversion,
1643/// nested profile to flatten profile conversion, etc.
1645public:
1647 // Convert a full context-sensitive flat sample profile into a nested sample
1648 // profile.
1650 struct FrameNode {
1652 FunctionSamples *FSamples = nullptr,
1653 LineLocation CallLoc = {0, 0})
1654 : FuncName(FName), FuncSamples(FSamples), CallSiteLoc(CallLoc) {};
1655
1656 // Map line+discriminator location to child frame
1657 std::map<uint64_t, FrameNode> AllChildFrames;
1658 // Function name for current frame
1660 // Function Samples for current frame
1662 // Callsite location in parent context
1664
1666 FunctionId CalleeName);
1667 };
1668
1669 static void flattenProfile(SampleProfileMap &ProfileMap,
1670 bool ProfileIsCS = false) {
1671 SampleProfileMap TmpProfiles;
1672 flattenProfile(ProfileMap, TmpProfiles, ProfileIsCS);
1673 ProfileMap = std::move(TmpProfiles);
1674 }
1675
1676 static void flattenProfile(const SampleProfileMap &InputProfiles,
1677 SampleProfileMap &OutputProfiles,
1678 bool ProfileIsCS = false) {
1679 if (ProfileIsCS) {
1680 for (const auto &I : InputProfiles) {
1681 // Retain the profile name and clear the full context for each function
1682 // profile.
1683 FunctionSamples &FS = OutputProfiles.create(I.second.getFunction());
1684 FS.merge(I.second);
1685 }
1686 } else {
1687 for (const auto &I : InputProfiles)
1688 flattenNestedProfile(OutputProfiles, I.second);
1689 }
1690 }
1691
1692private:
1693 static void flattenNestedProfile(SampleProfileMap &OutputProfiles,
1694 const FunctionSamples &FS) {
1695 // To retain the context, checksum, attributes of the original profile, make
1696 // a copy of it if no profile is found.
1697 SampleContext &Context = FS.getContext();
1698 auto Ret = OutputProfiles.try_emplace(Context, FS);
1699 FunctionSamples &Profile = Ret.first->second;
1700 if (Ret.second) {
1701 // Clear nested inlinees' samples for the flattened copy. These inlinees
1702 // will have their own top-level entries after flattening.
1703 Profile.removeAllCallsiteSamples();
1704 // We recompute TotalSamples later, so here set to zero.
1705 Profile.setTotalSamples(0);
1706 } else {
1707 Profile.reserveBodySamples(FS.getBodySamples().size());
1708 for (const auto &[LineLocation, SampleRecord] : FS.getBodySamples()) {
1709 Profile.addSampleRecord(LineLocation, SampleRecord);
1710 }
1711 }
1712
1713 assert(Profile.getCallsiteSamples().empty() &&
1714 "There should be no inlinees' profiles after flattening.");
1715
1716 // TotalSamples might not be equal to the sum of all samples from
1717 // BodySamples and CallsiteSamples. So here we use "TotalSamples =
1718 // Original_TotalSamples - All_of_Callsite_TotalSamples +
1719 // All_of_Callsite_HeadSamples" to compute the new TotalSamples.
1720 uint64_t TotalSamples = FS.getTotalSamples();
1721
1722 for (const auto &I : FS.getCallsiteSamples()) {
1723 for (const auto &Callee : I.second) {
1724 const auto &CalleeProfile = Callee.second;
1725 // Add body sample.
1726 Profile.addBodySamples(I.first.LineOffset, I.first.Discriminator,
1727 CalleeProfile.getHeadSamplesEstimate());
1728 // Add callsite sample.
1729 Profile.addCalledTargetSamples(I.first.LineOffset,
1730 I.first.Discriminator,
1731 CalleeProfile.getFunction(),
1732 CalleeProfile.getHeadSamplesEstimate());
1733 // Update total samples.
1734 TotalSamples = TotalSamples >= CalleeProfile.getTotalSamples()
1735 ? TotalSamples - CalleeProfile.getTotalSamples()
1736 : 0;
1737 TotalSamples += CalleeProfile.getHeadSamplesEstimate();
1738 // Recursively convert callee profile.
1739 flattenNestedProfile(OutputProfiles, CalleeProfile);
1740 }
1741 }
1742 Profile.addTotalSamples(TotalSamples);
1743
1744 Profile.setHeadSamples(Profile.getHeadSamplesEstimate());
1745 }
1746
1747 // Nest all children profiles into the profile of Node.
1748 void convertCSProfiles(FrameNode &Node);
1749 FrameNode *getOrCreateContextPath(const SampleContext &Context);
1750
1751 SampleProfileMap &ProfileMap;
1752 FrameNode RootFrame;
1753};
1754
1755/// ProfileSymbolList records the list of function symbols shown up
1756/// in the binary used to generate the profile. It is useful to
1757/// to discriminate a function being so cold as not to shown up
1758/// in the profile and a function newly added.
1760public:
1761 /// copy indicates whether we need to copy the underlying memory
1762 /// for the input Name.
1763 void add(StringRef Name, bool Copy = false) {
1764 assert(!IsMD5 && "Adding string to MD5 ProfileSymbolList is not supported");
1765 if (!Copy) {
1766 Syms.insert(Name);
1767 return;
1768 }
1769 Syms.insert(Name.copy(Allocator));
1770 }
1771
1772 bool contains(StringRef Name) const {
1773 if (!IsMD5)
1774 return Syms.contains(Name);
1775 uint64_t GUID = llvm::MD5Hash(Name);
1776 return !ColdGUIDTable.empty() ? ColdGUIDTable.contains(GUID)
1777 : GUIDs.contains(GUID);
1778 }
1779
1781 if (List.size() == 0)
1782 return;
1783 if (!List.IsMD5) {
1784 assert(!IsMD5 &&
1785 "Merging string and MD5 ProfileSymbolLists is not supported");
1786 for (auto Sym : List.Syms)
1787 add(Sym, true);
1788 return;
1789 }
1790 assert(Syms.empty() && ColdGUIDTable.empty() &&
1791 "Merging into non-empty string or ColdGUIDTable ProfileSymbolList "
1792 "is not supported");
1793 IsMD5 = true;
1794 GUIDs.insert_range(List.ColdGUIDTable);
1795 GUIDs.insert_range(List.GUIDs);
1796 }
1797
1798 unsigned size() const {
1799 if (!IsMD5)
1800 return Syms.size();
1801 return !ColdGUIDTable.empty() ? ColdGUIDTable.size() : GUIDs.size();
1802 }
1803 void reserve(size_t Size) { Syms.reserve(Size); }
1804
1805 std::vector<uint64_t> collectGUIDs() const {
1806 std::vector<uint64_t> Keys;
1807 Keys.reserve(size());
1808 if (!IsMD5)
1810 else if (!ColdGUIDTable.empty())
1811 llvm::append_range(Keys, ColdGUIDTable);
1812 else
1813 llvm::append_range(Keys, GUIDs);
1814 llvm::sort(Keys);
1815 Keys.erase(llvm::unique(Keys), Keys.end());
1816 return Keys;
1817 }
1818
1820 assert(Syms.empty() && GUIDs.empty() &&
1821 "Setting ColdGUIDTable shadows existing entries");
1822 ColdGUIDTable = Table;
1823 IsMD5 = true;
1824 }
1826 assert(IsMD5 && GUIDs.empty() &&
1827 "Retrieving ColdGUIDTable from non-table-backed ProfileSymbolList");
1828 return ColdGUIDTable;
1829 }
1830 bool isMD5() const { return IsMD5; }
1831
1832 LLVM_ABI std::error_code read(const uint8_t *Data, uint64_t ListSize);
1833 LLVM_ABI std::error_code write(raw_ostream &OS);
1834 LLVM_ABI void dump(raw_ostream &OS = dbgs()) const;
1835
1836private:
1837 // Whether symbols are stored as 64-bit MD5 hashes (in ColdGUIDTable or
1838 // GUIDs) rather than plain strings (in Syms). At most one of Syms,
1839 // ColdGUIDTable, or GUIDs is non-empty at any given time.
1840 bool IsMD5 = false;
1841 // Symbol names for string-based symbol lists (!IsMD5).
1843 // Non-owning view of Eytzinger-ordered MD5 hashes backed by the profile
1844 // reader's buffer, used for zero-copy lookups during compilation.
1846 // Owning set of MD5 hashes populated when merging MD5 symbol lists.
1847 DenseSet<uint64_t> GUIDs;
1849};
1850
1851} // end namespace sampleprof
1852
1853using namespace sampleprof;
1854// Provide DenseMapInfo for SampleContext.
1855template <> struct DenseMapInfo<SampleContext> {
1856 static unsigned getHashValue(const SampleContext &Val) {
1857 return Val.getHashCode();
1858 }
1859
1860 static bool isEqual(const SampleContext &LHS, const SampleContext &RHS) {
1861 return LHS == RHS;
1862 }
1863};
1864
1865// Prepend "__uniq" before the hash for tools like profilers to understand
1866// that this symbol is of internal linkage type. The "__uniq" is the
1867// pre-determined prefix that is used to tell tools that this symbol was
1868// created with -funique-internal-linkage-symbols and the tools can strip or
1869// keep the prefix as needed.
1870inline std::string getUniqueInternalLinkagePostfix(const StringRef &FName) {
1871 llvm::MD5 Md5;
1872 Md5.update(FName);
1874 Md5.final(R);
1875 SmallString<32> Str;
1877 // Convert MD5hash to Decimal. Demangler suffixes can either contain
1878 // numbers or characters but not both.
1879 llvm::APInt IntHash(128, Str.str(), 16);
1880 return toString(IntHash, /* Radix = */ 10, /* Signed = */ false)
1881 .insert(0, FunctionSamples::UniqSuffix);
1882}
1883
1884} // end namespace llvm
1885
1886#endif // LLVM_PROFILEDATA_SAMPLEPROF_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
This file defines the BumpPtrAllocator interface.
always inline
static cl::opt< unsigned > ColdCountThreshold("mfs-count-threshold", cl::desc("Minimum number of times a block must be executed to be retained."), cl::init(1), cl::Hidden)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_DEPRECATED_WITH_FIXIT(MSG, FIX)
Definition Compiler.h:259
#define LLVM_LIFETIME_BOUND
Definition Compiler.h:464
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Provides ErrorOr<T> smart pointer.
This file defines the EytzingerTableSpan class, a non-owning view of a buffer formatted as a complete...
Defines FunctionId class.
Defines HashKeyMap template.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Load MIR Sample Profile
This file implements a map that provides insertion order iteration.
#define T
Basic Register Allocator
This file defines the SmallVector class.
This file implements a map backed by a sorted SmallVector.
This file contains some functions that are useful when dealing with strings.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition ArrayRef.h:218
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
Definition ArrayRef.h:200
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Represents either an error or a value T.
Definition ErrorOr.h:56
Non-owning view of a buffer formatted as a complete binary search tree in Eytzinger (breadth-first) o...
Definition Eytzinger.h:30
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
static LLVM_ABI void stringifyResult(MD5Result &Result, SmallVectorImpl< char > &Str)
Translates the bytes in Res to a hex string that is deposited into Str.
Definition MD5.cpp:290
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:237
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A map implementation backed by a sorted SmallVector.
void reserve(size_type Cap)
size_type size() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
static constexpr size_t npos
Definition StringRef.h:58
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition StringRef.h:691
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
Definition StringRef.h:365
Target - Wrapper for Target specific information.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
An opaque object representing a hash code.
Definition Hashing.h:77
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This class represents a function that is read from a sample profile.
Definition FunctionId.h:36
uint64_t getHashCode() const
Get hash code of this object.
Definition FunctionId.h:123
Representation of the samples collected for a function.
Definition SampleProf.h:854
void setTotalSamples(uint64_t Num)
Definition SampleProf.h:876
static LLVM_ABI std::atomic< bool > ProfileIsFS
If this profile uses flow sensitive discriminators.
static LLVM_ABI std::atomic< bool > ProfileIsPreInlined
void setContextAttribute(ContextAttributeMask Attr)
Definition SampleProf.h:975
const FunctionSamplesMap * findFunctionSamplesMapAt(const LineLocation &Loc) const LLVM_LIFETIME_BOUND
Returns the FunctionSamplesMap at the given Loc.
bool operator!=(const FunctionSamples &Other) const
void setHeadSamples(uint64_t Num)
Definition SampleProf.h:878
sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:861
void findInlinedFunctions(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, uint64_t Threshold, bool IncludeLocalTargets=false) const
Recursively collect import GUIDs from contexts with total samples greater than Threshold,...
static constexpr const char * UniqSuffix
static LLVM_ABI std::atomic< bool > UseMD5
Whether the profile uses MD5 to represent string.
bool hasCallsiteSamples() const
Return whether this function profile contains callsite samples.
static StringRef getCanonicalFnName(StringRef FnName, StringRef Attr="selected")
sampleprof_error addTypeSamplesAt(const LineLocation &Loc, FunctionId Type, uint64_t Count)
At location Loc, add a type sample for the given Type with Count.
bool operator==(const FunctionSamples &Other) const
static constexpr const char * PartSuffix
static uint64_t getCallSiteHash(FunctionId Callee, const LineLocation &Callsite)
Returns a unique hash code for a combination of a callsite location and the callee function name.
static StringRef getCanonicalCoroFnName(StringRef FnName, StringRef Attr="selected")
uint64_t getMaxCountInside(bool SkipCallSite=false) const
Return the maximum of sample counts in a function body.
void removeTotalSamples(uint64_t Num)
Definition SampleProf.h:869
uint64_t getHeadSamples() const
For top-level functions, return the total number of branch samples that have the function as the bran...
void setFunction(FunctionId NewFunctionID)
Set the name of the function.
ErrorOr< uint64_t > findSamplesAt(uint32_t LineOffset, uint32_t Discriminator) const
Return the number of samples collected at the given location.
Definition SampleProf.h:999
LLVM_ABI const FunctionSamples * findFunctionSamples(const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper=nullptr, const HashKeyMap< DenseMap, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const LLVM_LIFETIME_BOUND
Get the FunctionSamples of the inline instance where DIL originates from.
const CallsiteSampleMap & getCallsiteSamples() const LLVM_LIFETIME_BOUND
Return all the callsite samples collected in the body of the function.
const LineLocation & mapIRLocToProfileLoc(const LineLocation &IRLoc) const
Definition SampleProf.h:985
LLVM_ABI const FunctionSamples * findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName, SampleProfileReaderItaniumRemapper *Remapper, const HashKeyMap< DenseMap, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const LLVM_LIFETIME_BOUND
Returns a pointer to FunctionSamples at the given callsite location Loc with callee CalleeName.
static StringRef getCanonicalFnName(StringRef FnName, ArrayRef< StringRef > Suffixes, StringRef Attr="selected")
FunctionId getFunction() const
Return the function name.
SampleContext & getContext() const LLVM_LIFETIME_BOUND
sampleprof_error addCallsiteVTableTypeProfAt(const LineLocation &Loc, const T &Other, uint64_t Weight=1)
Scale Other sample counts by Weight and add the scaled result to the type samples for Loc.
static constexpr const char * LLVMSuffix
Name suffixes which canonicalization should handle to avoid profile mismatch.
FunctionSamplesMap & functionSamplesAt(const LineLocation &Loc) LLVM_LIFETIME_BOUND
Return the function samples at the given callsite location.
StringRef getFuncName(FunctionId Func) const
Translate Func into its original name.
ErrorOr< const SampleRecord::CallTargetMap & > findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const LLVM_LIFETIME_BOUND
Returns the call target map collected at a given location.
sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:880
void reserveBodySamples(size_t NumEntries)
Definition SampleProf.h:908
sampleprof_error addSampleRecord(LineLocation Location, const SampleRecord &SampleRecord, uint64_t Weight=1)
Definition SampleProf.h:902
uint64_t removeCalledTargetAndBodySample(uint32_t LineOffset, uint32_t Discriminator, FunctionId Func)
Definition SampleProf.h:918
DenseMap< uint64_t, StringRef > * GUIDToFuncNameMap
GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for all the function symbols define...
TypeCountMap & getTypeSamplesAt(const LineLocation &Loc) LLVM_LIFETIME_BOUND
Returns the vtable access samples for the C++ types for Loc.
sampleprof_error addCalledTargetSamples(uint32_t LineOffset, uint32_t Discriminator, FunctionId Func, uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:894
void setIRToProfileLocationMap(const LocToLocMap *LTLM)
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
StringRef getFuncName() const
Return the original function name.
LLVM_ABI void findAllNames(DenseSet< FunctionId > &NameSet) const
static constexpr const char * CfiSuffix
sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator, uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:888
static void addImportGUID(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, FunctionId Name, bool IncludeLocal)
Add the import GUID of profiled function Name to S.
static LLVM_ABI unsigned getOffset(const DILocation *DIL)
Returns the line offset to the start line of the subprogram.
static LLVM_ABI std::atomic< bool > HasUniqSuffix
Whether the profile contains any ".__uniq." suffix in a name.
void setFunctionHash(uint64_t Hash)
const TypeCountMap * findCallsiteTypeSamplesAt(const LineLocation &Loc) const LLVM_LIFETIME_BOUND
Returns the TypeCountMap for inlined callsites at the given Loc.
static LLVM_ABI std::atomic< bool > ProfileIsProbeBased
const CallsiteTypeMap & getCallsiteTypeCounts() const LLVM_LIFETIME_BOUND
Returns vtable access samples for the C++ types collected in this function.
ErrorOr< const SampleRecord::CallTargetMap & > findCallTargetMapAt(const LineLocation &CallSite) const LLVM_LIFETIME_BOUND
Returns the call target map collected at a given location specified by CallSite.
const BodySampleMap & getBodySamples() const LLVM_LIFETIME_BOUND
Return all the samples collected in the body of the function.
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
LLVM_ABI void print(raw_ostream &OS=dbgs(), unsigned Indent=0) const
Print the samples collected for a function on stream OS.
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
void setContext(const SampleContext &FContext)
static LLVM_ABI std::atomic< bool > ProfileIsCS
static LLVM_ABI LineLocation getCallSiteIdentifier(const DILocation *DIL, bool ProfileIsFS=false)
Returns a unique call site identifier for a given debug location of a call instruction.
void reserveCallsiteTypeCounts(size_t NumEntries)
Definition SampleProf.h:912
uint64_t getHeadSamplesEstimate() const
Return an estimate of the sample count of the function entry basic block.
uint64_t getGUID() const
Return the GUID of the context's name.
This class is a wrapper to associative container MapT<KeyT, ValueT> using the hash value of the origi...
Definition HashKeyMap.h:52
std::pair< iterator, bool > try_emplace(const key_type &Hash, const original_key_type &Key, Ts &&...Args)
Definition HashKeyMap.h:64
iterator find(const original_key_type &Key)
Definition HashKeyMap.h:85
LLVM_ABI ProfileConverter(SampleProfileMap &Profiles)
static void flattenProfile(SampleProfileMap &ProfileMap, bool ProfileIsCS=false)
static void flattenProfile(const SampleProfileMap &InputProfiles, SampleProfileMap &OutputProfiles, bool ProfileIsCS=false)
ProfileSymbolList records the list of function symbols shown up in the binary used to generate the pr...
void add(StringRef Name, bool Copy=false)
copy indicates whether we need to copy the underlying memory for the input Name.
LLVM_ABI std::error_code write(raw_ostream &OS)
bool contains(StringRef Name) const
LLVM_ABI void dump(raw_ostream &OS=dbgs()) const
void setColdGUIDTable(EytzingerTableSpan< support::ulittle64_t > Table)
std::vector< uint64_t > collectGUIDs() const
void merge(const ProfileSymbolList &List)
EytzingerTableSpan< support::ulittle64_t > getColdGUIDTable() const
LLVM_ABI std::error_code read(const uint8_t *Data, uint64_t ListSize)
SampleContextTrimmer(SampleProfileMap &Profiles)
LLVM_ABI void trimAndMergeColdContextProfiles(uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext, uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly)
static void createCtxVectorFromStr(StringRef ContextStr, SampleContextFrameVector &Context)
Create a context vector from a given context string and save it in Context.
Definition SampleProf.h:676
bool operator==(const SampleContext &That) const
Definition SampleProf.h:769
void setFunction(FunctionId NewFunctionID)
Set the name of the function and clear the current context.
Definition SampleProf.h:755
SampleContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
Definition SampleProf.h:645
bool operator<(const SampleContext &That) const
Definition SampleProf.h:776
SampleContext(StringRef ContextStr, std::list< SampleContextFrameVector > &CSNameTable, ContextStateMask CState=RawContext)
Definition SampleProf.h:655
bool hasState(ContextStateMask S)
Definition SampleProf.h:721
void clearState(ContextStateMask S)
Definition SampleProf.h:723
SampleContextFrames getContextFrames() const
Definition SampleProf.h:727
static void decodeContextString(StringRef ContextStr, FunctionId &Func, LineLocation &LineLoc)
Definition SampleProf.h:695
static std::string getContextString(SampleContextFrames Context, bool IncludeLeafLineLocation=false)
Definition SampleProf.h:729
bool operator!=(const SampleContext &That) const
Definition SampleProf.h:774
void setState(ContextStateMask S)
Definition SampleProf.h:722
void setAllAttributes(uint32_t A)
Definition SampleProf.h:720
void setContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
Definition SampleProf.h:761
FunctionId getFunction() const
Definition SampleProf.h:726
void setAttribute(ContextAttributeMask A)
Definition SampleProf.h:718
bool hasAttribute(ContextAttributeMask A)
Definition SampleProf.h:717
std::string toString() const
Definition SampleProf.h:742
bool isPrefixOf(const SampleContext &That) const
Definition SampleProf.h:805
This class provides operator overloads to the map container using MD5 as the key type,...
iterator find(const SampleContext &Ctx)
mapped_type & create(const SampleContext &Ctx)
size_t erase(const key_type &Key)
const_iterator find(const SampleContext &Ctx) const
size_t erase(const SampleContext &Ctx)
SampleProfileReaderItaniumRemapper remaps the profile data from a sample profile data reader,...
Representation of a single sample record.
Definition SampleProf.h:423
static SortedCallTargetSet sortCallTargets(const CallTargetMap &Targets)
Sort call targets in descending order of call frequency.
Definition SampleProf.h:509
LLVM_ABI std::error_code serialize(raw_ostream &OS, const MapVector< FunctionId, uint32_t > &NameTable) const
Serialize the sample record to the output stream using ULEB128 encoding.
LLVM_ABI void dump() const
bool hasCalls() const
Return true if this sample record contains function calls.
Definition SampleProf.h:488
LLVM_ABI sampleprof_error merge(const SampleRecord &Other, uint64_t Weight=1)
Merge the samples in Other into this record.
SortedCallTargetSet getSortedCallTargets() const
Definition SampleProf.h:497
uint64_t getCallTargetSum() const
Definition SampleProf.h:501
uint64_t removeSamples(uint64_t S)
Decrease the number of samples for this record by S.
Definition SampleProf.h:453
sampleprof_error addSamples(uint64_t S, uint64_t Weight=1)
Increment the number of samples for this record by S.
Definition SampleProf.h:444
uint64_t removeCalledTarget(FunctionId F)
Remove called function from the call target map.
Definition SampleProf.h:477
const CallTargetMap & getCallTargets() const LLVM_LIFETIME_BOUND
Return the call targets collected in this sample record.
Definition SampleProf.h:494
static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets, float DistributionFactor)
Prorate call targets by a distribution factor.
Definition SampleProf.h:516
SortedVectorMap< FunctionId, uint64_t, 0 > CallTargetMap
Definition SampleProf.h:436
std::pair< FunctionId, uint64_t > CallTarget
Definition SampleProf.h:425
bool operator!=(const SampleRecord &Other) const
Definition SampleProf.h:541
SmallVector< CallTarget > SortedCallTargetSet
Definition SampleProf.h:435
bool operator==(const SampleRecord &Other) const
Definition SampleProf.h:537
LLVM_ABI void print(raw_ostream &OS, unsigned Indent) const
Print the sample record to the stream OS indented by Indent.
sampleprof_error addCalledTarget(FunctionId F, uint64_t S, uint64_t Weight=1)
Add called function F with samples S.
Definition SampleProf.h:465
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static FunctionId getRepInFormat(StringRef Name)
Get the proper representation of a string according to whether the current Format uses MD5 to represe...
static void verifySecFlag(SecType Type, SecFlagType Flag)
Definition SampleProf.h:288
LLVM_ABI void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
Definition SampleProf.h:114
static bool formatVersionIsSupported(uint64_t Version)
Definition SampleProf.h:136
SortedVectorMap< LineLocation, TypeCountMap, 0 > CallsiteTypeMap
Definition SampleProf.h:846
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:320
std::map< LineLocation, FunctionSamplesMap > CallsiteSampleMap
Definition SampleProf.h:845
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:336
static constexpr uint64_t LatestVersion
Definition SampleProf.h:133
SortedVectorMap< LineLocation, SampleRecord, 0 > BodySampleMap
Definition SampleProf.h:841
ArrayRef< SampleContextFrame > SampleContextFrames
Definition SampleProf.h:615
std::pair< hash_code, const FunctionSamples * > NameFunctionSamples
uint64_t MD5Hash(const FunctionId &Obj)
Definition FunctionId.h:167
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
Definition SampleProf.h:264
@ SecFlagHasVTableTypeProf
SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
Definition SampleProf.h:267
@ SecFlagPartial
SecFlagPartial means the profile is for common/shared code.
Definition SampleProf.h:255
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
Definition SampleProf.h:261
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
Definition SampleProf.h:258
static void removeSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:328
static StringRef getProfTypeName(uint64_t Type)
Definition SampleProf.h:197
DenseMap< LineLocation, LineLocation > LocToLocMap
Definition SampleProf.h:847
SmallVector< SampleContextFrame, 1 > SampleContextFrameVector
Definition SampleProf.h:614
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
Definition SampleProf.h:844
static constexpr uint64_t MinSupportedVersion
Definition SampleProf.h:122
raw_ostream & operator<<(raw_ostream &OS, const FunctionId &Obj)
Definition FunctionId.h:159
static constexpr uint64_t DefaultVersion
Definition SampleProf.h:127
static std::string getSecName(SecType Type)
Definition SampleProf.h:165
static constexpr uint64_t CompositeProfileVersion
Definition SampleProf.h:130
constexpr char kVTableProfPrefix[]
Definition SampleProf.h:97
uint64_t hash_value(const FunctionId &Obj)
Definition FunctionId.h:171
LLVM_ABI std::error_code serializeTypeMap(const TypeCountMap &Map, const MapVector< FunctionId, uint32_t > &NameTable, raw_ostream &OS)
Write Map to the output stream.
SortedVectorMap< FunctionId, uint64_t, 0 > TypeCountMap
Key represents type of a C++ polymorphic class type by its vtable and value represents its counter.
Definition SampleProf.h:403
This is an optimization pass for GlobalISel generic memory operations.
std::error_code make_error_code(BitcodeError E)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
sampleprof_error mergeSampleProfErrors(sampleprof_error &Accumulator, sampleprof_error Result)
Definition SampleProf.h:75
sampleprof_error
Definition SampleProf.h:52
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition MathExtras.h:684
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI const std::error_category & sampleprof_category()
std::string getUniqueInternalLinkagePostfix(const StringRef &FName)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
LogicalResult success(bool IsSuccess=true)
Utility function to generate a LogicalResult.
SmallVector< Out, Size > to_vector_of(R &&Range)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
static unsigned getHashValue(const SampleContext &Val)
static bool isEqual(const SampleContext &LHS, const SampleContext &RHS)
static unsigned getHashValue(const sampleprof::LineLocation &Val)
Definition SampleProf.h:387
static bool isEqual(const sampleprof::LineLocation &LHS, const sampleprof::LineLocation &RHS)
Definition SampleProf.h:391
An information struct used to provide DenseMap with the various necessary components for a given valu...
Represents the relative location of an instruction.
Definition SampleProf.h:352
LLVM_ABI void serialize(raw_ostream &OS) const
LLVM_ABI void print(raw_ostream &OS) const
LineLocation(uint32_t L, uint32_t D)
Definition SampleProf.h:353
bool operator!=(const LineLocation &O) const
Definition SampleProf.h:370
bool operator<(const LineLocation &O) const
Definition SampleProf.h:361
bool operator==(const LineLocation &O) const
Definition SampleProf.h:366
LLVM_ABI void dump() const
FrameNode(FunctionId FName=FunctionId(), FunctionSamples *FSamples=nullptr, LineLocation CallLoc={0, 0})
LLVM_ABI FrameNode * getOrCreateChildFrame(const LineLocation &CallSite, FunctionId CalleeName)
std::map< uint64_t, FrameNode > AllChildFrames
uint64_t operator()(const SampleContextFrameVector &S) const
Definition SampleProf.h:618
bool operator==(const SampleContextFrame &That) const
Definition SampleProf.h:578
SampleContextFrame(FunctionId Func, LineLocation Location)
Definition SampleProf.h:575
bool operator!=(const SampleContextFrame &That) const
Definition SampleProf.h:582
std::string toString(bool OutputLineLocation) const
Definition SampleProf.h:586
uint64_t operator()(const SampleContext &Context) const
Definition SampleProf.h:800
bool operator()(const CallTarget &LHS, const CallTarget &RHS) const
Definition SampleProf.h:427