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 work in progress.
126static constexpr uint64_t DefaultVersion = 103;
127
128// The latest supported version of the extensible binary profile format.
129static constexpr uint64_t LatestVersion = 104;
130
131// Query if a given format version is supported by this compiler.
135
136// Unused. Retained for downstream uses only.
137LLVM_DEPRECATED("Use DefaultVersion or LatestVersion instead", "DefaultVersion")
138static inline uint64_t SPVersion() { return 103; }
139
140// Section Type used by SampleProfileExtBinaryBaseReader and
141// SampleProfileExtBinaryBaseWriter. Never change the existing
142// value of enum. Only append new ones.
155
156static inline std::string getSecName(SecType Type) {
157 switch (static_cast<int>(Type)) { // Avoid -Wcovered-switch-default
158 case SecInValid:
159 return "InvalidSection";
160 case SecProfSummary:
161 return "ProfileSummarySection";
162 case SecNameTable:
163 return "NameTableSection";
165 return "ProfileSymbolListSection";
167 return "FuncOffsetTableSection";
168 case SecFuncMetadata:
169 return "FunctionMetadata";
170 case SecCSNameTable:
171 return "CSNameTableSection";
172 case SecLBRProfile:
173 return "LBRProfileSection";
174 default:
175 return "UnknownSection";
176 }
177}
178
179// Entry type of section header table used by SampleProfileExtBinaryBaseReader
180// and SampleProfileExtBinaryBaseWriter.
186 // The index indicating the location of the current entry in
187 // SectionHdrLayout table.
189};
190
191// Flags common for all sections are defined here. In SecHdrTableEntry::Flags,
192// common flags will be saved in the lower 32bits and section specific flags
193// will be saved in the higher 32 bits.
196 SecFlagCompress = (1 << 0),
197 // Indicate the section contains flat profiles (without callsite samples).
198 SecFlagFlat = (1 << 1)
199};
200
201// Section specific flags are defined here.
202// !!!Note: Everytime a new enum class is created here, please add
203// a new check in verifySecFlag.
206 SecFlagMD5Name = (1 << 0),
207 // Store MD5 in fixed length instead of ULEB128 so NameTable can be
208 // accessed like an array.
210 // Profile contains ".__uniq." suffix name. Compiler shouldn't strip
211 // the suffix when doing profile matching when seeing the flag.
213 // Name table is stored in 3-span Eytzinger layout (Nested, Flat, Inlinees).
215};
216
217enum class EytzingerSpan : size_t { Nested, Flat, Inlinee, NumSpans };
218
225 /// SecFlagPartial means the profile is for common/shared code.
226 /// The common profile is usually merged from profiles collected
227 /// from running other targets.
228 SecFlagPartial = (1 << 0),
229 /// SecFlagContext means this is context-sensitive flat profile for
230 /// CSSPGO
232 /// SecFlagFSDiscriminator means this profile uses flow-sensitive
233 /// discriminators.
235 /// SecFlagIsPreInlined means this profile contains ShouldBeInlined
236 /// contexts thus this is CS preinliner computed.
238
239 /// SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
241};
242
248
251 // Store function offsets in an order of contexts. The order ensures that
252 // callee contexts of a given context laid out next to it.
253 SecFlagOrdered = (1 << 0),
254 // Store function offsets in a parallel array aligned with Eytzinger NameTable
255 // span.
257};
258
259// Verify section specific flag is used for the correct section.
260template <class SecFlagType>
261static inline void verifySecFlag(SecType Type, SecFlagType Flag) {
262 // No verification is needed for common flags.
263 if (std::is_same<SecCommonFlags, SecFlagType>())
264 return;
265
266 // Verification starts here for section specific flag.
267 bool IsFlagLegal = false;
268 switch (Type) {
269 case SecNameTable:
270 IsFlagLegal = std::is_same<SecNameTableFlags, SecFlagType>();
271 break;
273 IsFlagLegal = std::is_same<SecProfileSymbolListFlags, SecFlagType>();
274 break;
275 case SecProfSummary:
276 IsFlagLegal = std::is_same<SecProfSummaryFlags, SecFlagType>();
277 break;
278 case SecFuncMetadata:
279 IsFlagLegal = std::is_same<SecFuncMetadataFlags, SecFlagType>();
280 break;
282 IsFlagLegal = std::is_same<SecFuncOffsetFlags, SecFlagType>();
283 break;
284 default:
285 break;
286 }
287 if (!IsFlagLegal)
288 llvm_unreachable("Misuse of a flag in an incompatible section");
289}
290
291template <class SecFlagType>
292static inline void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
293 verifySecFlag(Entry.Type, Flag);
294 auto FVal = static_cast<uint64_t>(Flag);
295 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
296 Entry.Flags |= IsCommon ? FVal : (FVal << 32);
297}
298
299template <class SecFlagType>
300static inline void removeSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag) {
301 verifySecFlag(Entry.Type, Flag);
302 auto FVal = static_cast<uint64_t>(Flag);
303 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
304 Entry.Flags &= ~(IsCommon ? FVal : (FVal << 32));
305}
306
307template <class SecFlagType>
308static inline bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag) {
309 verifySecFlag(Entry.Type, Flag);
310 auto FVal = static_cast<uint64_t>(Flag);
311 bool IsCommon = std::is_same<SecCommonFlags, SecFlagType>();
312 return Entry.Flags & (IsCommon ? FVal : (FVal << 32));
313}
314
315/// Represents the relative location of an instruction.
316///
317/// Instruction locations are specified by the line offset from the
318/// beginning of the function (marked by the line where the function
319/// header is) and the discriminator value within that line.
320///
321/// The discriminator value is useful to distinguish instructions
322/// that are on the same line but belong to different basic blocks
323/// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
326
327 LLVM_ABI void print(raw_ostream &OS) const;
328 LLVM_ABI void dump() const;
329
330 // Serialize the line location to the output stream using ULEB128 encoding.
331 LLVM_ABI void serialize(raw_ostream &OS) const;
332
333 bool operator<(const LineLocation &O) const {
334 return std::tie(LineOffset, Discriminator) <
335 std::tie(O.LineOffset, O.Discriminator);
336 }
337
338 bool operator==(const LineLocation &O) const {
339 return LineOffset == O.LineOffset && Discriminator == O.Discriminator;
340 }
341
342 bool operator!=(const LineLocation &O) const {
343 return LineOffset != O.LineOffset || Discriminator != O.Discriminator;
344 }
345
347 return ((uint64_t)Discriminator << 32) | LineOffset;
348 }
349
352};
353
355
356} // end namespace sampleprof
357
359 static unsigned getHashValue(const sampleprof::LineLocation &Val) {
361 }
362
365 return LHS == RHS;
366 }
367};
368
369namespace sampleprof {
370
371/// Key represents type of a C++ polymorphic class type by its vtable and value
372/// represents its counter.
373/// TODO: The class name FunctionId should be renamed to SymbolId in a refactor
374/// change.
375using TypeCountMap = std::map<FunctionId, uint64_t>;
376
377/// Write \p Map to the output stream. Keys are linearized using \p NameTable
378/// and written as ULEB128. Values are written as ULEB128 as well.
379LLVM_ABI std::error_code
381 const MapVector<FunctionId, uint32_t> &NameTable,
382 raw_ostream &OS);
383
384/// Representation of a single sample record.
385///
386/// A sample record is represented by a positive integer value, which
387/// indicates how frequently was the associated line location executed.
388///
389/// Additionally, if the associated location contains a function call,
390/// the record will hold a list of all the possible called targets and the types
391/// for virtual table dispatches. For direct calls, this will be the exact
392/// function being invoked. For indirect calls (function pointers, virtual table
393/// dispatch), this will be a list of one or more functions. For virtual table
394/// dispatches, this record will also hold the type of the object.
396public:
397 using CallTarget = std::pair<FunctionId, uint64_t>;
399 bool operator()(const CallTarget &LHS, const CallTarget &RHS) const {
400 if (LHS.second != RHS.second)
401 return LHS.second > RHS.second;
402
403 return LHS.first < RHS.first;
404 }
405 };
406
409 SampleRecord() = default;
410
411 /// Increment the number of samples for this record by \p S.
412 /// Optionally scale sample count \p S by \p Weight.
413 ///
414 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
415 /// around unsigned integers.
417 bool Overflowed;
418 NumSamples = SaturatingMultiplyAdd(S, Weight, NumSamples, &Overflowed);
419 return Overflowed ? sampleprof_error::counter_overflow
421 }
422
423 /// Decrease the number of samples for this record by \p S. Return the amout
424 /// of samples actually decreased.
426 if (S > NumSamples)
427 S = NumSamples;
428 NumSamples -= S;
429 return S;
430 }
431
432 /// Add called function \p F with samples \p S.
433 /// Optionally scale sample count \p S by \p Weight.
434 ///
435 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
436 /// around unsigned integers.
438 uint64_t Weight = 1) {
439 uint64_t &TargetSamples = CallTargets[F];
440 bool Overflowed;
441 TargetSamples =
442 SaturatingMultiplyAdd(S, Weight, TargetSamples, &Overflowed);
443 return Overflowed ? sampleprof_error::counter_overflow
445 }
446
447 /// Remove called function from the call target map. Return the target sample
448 /// count of the called function.
450 uint64_t Count = 0;
451 auto I = CallTargets.find(F);
452 if (I != CallTargets.end()) {
453 Count = I->second;
454 CallTargets.erase(I);
455 }
456 return Count;
457 }
458
459 /// Return true if this sample record contains function calls.
460 bool hasCalls() const { return !CallTargets.empty(); }
461
462 uint64_t getSamples() const { return NumSamples; }
463 const CallTargetMap &getCallTargets() const { return CallTargets; }
465 return sortCallTargets(CallTargets);
466 }
467
469 uint64_t Sum = 0;
470 for (const auto &I : CallTargets)
471 Sum += I.second;
472 return Sum;
473 }
474
475 /// Sort call targets in descending order of call frequency.
477 auto SortedTargets = llvm::to_vector_of<CallTarget>(Targets);
478 llvm::sort(SortedTargets, CallTargetComparator());
479 return SortedTargets;
480 }
481
482 /// Prorate call targets by a distribution factor.
483 static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets,
484 float DistributionFactor) {
485 CallTargetMap AdjustedTargets;
486 for (const auto &[Target, Frequency] : Targets) {
487 AdjustedTargets[Target] = Frequency * DistributionFactor;
488 }
489 return AdjustedTargets;
490 }
491
492 /// Merge the samples in \p Other into this record.
493 /// Optionally scale sample counts by \p Weight.
495 uint64_t Weight = 1);
496 LLVM_ABI void print(raw_ostream &OS, unsigned Indent) const;
497 LLVM_ABI void dump() const;
498 /// Serialize the sample record to the output stream using ULEB128 encoding.
499 /// The \p NameTable is used to map function names to their IDs.
500 LLVM_ABI std::error_code
502 const MapVector<FunctionId, uint32_t> &NameTable) const;
503
504 bool operator==(const SampleRecord &Other) const {
505 return NumSamples == Other.NumSamples && CallTargets == Other.CallTargets;
506 }
507
508 bool operator!=(const SampleRecord &Other) const { return !(*this == Other); }
509
510private:
511 uint64_t NumSamples = 0;
512 CallTargetMap CallTargets;
513};
514
516
517// State of context associated with FunctionSamples
519 UnknownContext = 0x0, // Profile without context
520 RawContext = 0x1, // Full context profile from input profile
521 SyntheticContext = 0x2, // Synthetic context created for context promotion
522 InlinedContext = 0x4, // Profile for context that is inlined into caller
523 MergedContext = 0x8 // Profile for context merged into base profile
524};
525
526// Attribute of context associated with FunctionSamples
529 ContextWasInlined = 0x1, // Leaf of context was inlined in previous build
530 ContextShouldBeInlined = 0x2, // Leaf of context should be inlined
532 0x4, // Leaf of context is duplicated into the base profile
533};
534
535// Represents a context frame with profile function and line location
539
541
544
545 bool operator==(const SampleContextFrame &That) const {
546 return Location == That.Location && Func == That.Func;
547 }
548
549 bool operator!=(const SampleContextFrame &That) const {
550 return !(*this == That);
551 }
552
553 std::string toString(bool OutputLineLocation) const {
554 std::ostringstream OContextStr;
555 OContextStr << Func.str();
556 if (OutputLineLocation) {
557 OContextStr << ":" << Location.LineOffset;
558 if (Location.Discriminator)
559 OContextStr << "." << Location.Discriminator;
560 }
561 return OContextStr.str();
562 }
563
565 // Context frame hash is heavily used in llvm-profgen context-sensitive
566 // pre-inliner. Use a lightweight hashing here to avoid speed regression.
567 uint64_t NameHash = 0;
568 if (Func.isStringRef())
569 NameHash = std::hash<std::string>{}(Func.str());
570 else
571 NameHash = Func.getHashCode();
572 uint64_t LocId = Location.getHashCode();
573 return NameHash + (LocId << 5) + LocId;
574 }
575};
576
577static inline hash_code hash_value(const SampleContextFrame &arg) {
578 return arg.getHashCode();
579}
580
583
589
590// Sample context for FunctionSamples. It consists of the calling context,
591// the function name and context state. Internally sample context is represented
592// using ArrayRef, which is also the input for constructing a `SampleContext`.
593// It can accept and represent both full context string as well as context-less
594// function name.
595// For a CS profile, a full context vector can look like:
596// `main:3 _Z5funcAi:1 _Z8funcLeafi`
597// For a base CS profile without calling context, the context vector should only
598// contain the leaf frame name.
599// For a non-CS profile, the context vector should be empty.
601public:
602 SampleContext() : State(UnknownContext), Attributes(ContextNone) {}
603
605 : Func(Name), State(UnknownContext), Attributes(ContextNone) {
606 assert(!Name.empty() && "Name is empty");
607 }
608
610 : Func(Func), State(UnknownContext), Attributes(ContextNone) {}
611
614 : Attributes(ContextNone) {
615 assert(!Context.empty() && "Context is empty");
616 setContext(Context, CState);
617 }
618
619 // Give a context string, decode and populate internal states like
620 // Function name, Calling context and context state. Example of input
621 // `ContextStr`: `[main:3 @ _Z5funcAi:1 @ _Z8funcLeafi]`
623 std::list<SampleContextFrameVector> &CSNameTable,
625 : Attributes(ContextNone) {
626 assert(!ContextStr.empty());
627 // Note that `[]` wrapped input indicates a full context string, otherwise
628 // it's treated as context-less function name only.
629 bool HasContext = ContextStr.starts_with("[");
630 if (!HasContext) {
631 State = UnknownContext;
632 Func = FunctionId(ContextStr);
633 } else {
634 CSNameTable.emplace_back();
635 SampleContextFrameVector &Context = CSNameTable.back();
636 createCtxVectorFromStr(ContextStr, Context);
637 setContext(Context, CState);
638 }
639 }
640
641 /// Create a context vector from a given context string and save it in
642 /// `Context`.
643 static void createCtxVectorFromStr(StringRef ContextStr,
644 SampleContextFrameVector &Context) {
645 // Remove encapsulating '[' and ']' if any
646 ContextStr = ContextStr.substr(1, ContextStr.size() - 2);
647 StringRef ContextRemain = ContextStr;
648 StringRef ChildContext;
649 FunctionId Callee;
650 while (!ContextRemain.empty()) {
651 auto ContextSplit = ContextRemain.split(" @ ");
652 ChildContext = ContextSplit.first;
653 ContextRemain = ContextSplit.second;
654 LineLocation CallSiteLoc(0, 0);
655 decodeContextString(ChildContext, Callee, CallSiteLoc);
656 Context.emplace_back(Callee, CallSiteLoc);
657 }
658 }
659
660 // Decode context string for a frame to get function name and location.
661 // `ContextStr` is in the form of `FuncName:StartLine.Discriminator`.
662 static void decodeContextString(StringRef ContextStr, FunctionId &Func,
663 LineLocation &LineLoc) {
664 // Get function name
665 auto EntrySplit = ContextStr.split(':');
666 Func = FunctionId(EntrySplit.first);
667
668 LineLoc = {0, 0};
669 if (!EntrySplit.second.empty()) {
670 // Get line offset, use signed int for getAsInteger so string will
671 // be parsed as signed.
672 int LineOffset = 0;
673 auto LocSplit = EntrySplit.second.split('.');
674 LocSplit.first.getAsInteger(10, LineOffset);
675 LineLoc.LineOffset = LineOffset;
676
677 // Get discriminator
678 if (!LocSplit.second.empty())
679 LocSplit.second.getAsInteger(10, LineLoc.Discriminator);
680 }
681 }
682
683 operator SampleContextFrames() const { return FullContext; }
684 bool hasAttribute(ContextAttributeMask A) { return Attributes & (uint32_t)A; }
685 void setAttribute(ContextAttributeMask A) { Attributes |= (uint32_t)A; }
686 uint32_t getAllAttributes() { return Attributes; }
687 void setAllAttributes(uint32_t A) { Attributes = A; }
688 bool hasState(ContextStateMask S) { return State & (uint32_t)S; }
689 void setState(ContextStateMask S) { State |= (uint32_t)S; }
690 void clearState(ContextStateMask S) { State &= (uint32_t)~S; }
691 bool hasContext() const { return State != UnknownContext; }
692 bool isBaseContext() const { return FullContext.size() == 1; }
693 FunctionId getFunction() const { return Func; }
694 SampleContextFrames getContextFrames() const { return FullContext; }
695
696 static std::string getContextString(SampleContextFrames Context,
697 bool IncludeLeafLineLocation = false) {
698 std::ostringstream OContextStr;
699 for (uint32_t I = 0; I < Context.size(); I++) {
700 if (OContextStr.str().size()) {
701 OContextStr << " @ ";
702 }
703 OContextStr << Context[I].toString(I != Context.size() - 1 ||
704 IncludeLeafLineLocation);
705 }
706 return OContextStr.str();
707 }
708
709 std::string toString() const {
710 if (!hasContext())
711 return Func.str();
712 return getContextString(FullContext, false);
713 }
714
716 if (hasContext())
718 return getFunction().getHashCode();
719 }
720
721 /// Set the name of the function and clear the current context.
722 void setFunction(FunctionId NewFunctionID) {
723 Func = NewFunctionID;
724 FullContext = SampleContextFrames();
725 State = UnknownContext;
726 }
727
729 ContextStateMask CState = RawContext) {
730 assert(CState != UnknownContext);
731 FullContext = Context;
732 Func = Context.back().Func;
733 State = CState;
734 }
735
736 bool operator==(const SampleContext &That) const {
737 return State == That.State && Func == That.Func &&
738 FullContext == That.FullContext;
739 }
740
741 bool operator!=(const SampleContext &That) const { return !(*this == That); }
742
743 bool operator<(const SampleContext &That) const {
744 if (State != That.State)
745 return State < That.State;
746
747 if (!hasContext()) {
748 return Func < That.Func;
749 }
750
751 uint64_t I = 0;
752 while (I < std::min(FullContext.size(), That.FullContext.size())) {
753 auto &Context1 = FullContext[I];
754 auto &Context2 = That.FullContext[I];
755 auto V = Context1.Func.compare(Context2.Func);
756 if (V)
757 return V < 0;
758 if (Context1.Location != Context2.Location)
759 return Context1.Location < Context2.Location;
760 I++;
761 }
762
763 return FullContext.size() < That.FullContext.size();
764 }
765
766 struct Hash {
767 uint64_t operator()(const SampleContext &Context) const {
768 return Context.getHashCode();
769 }
770 };
771
772 bool isPrefixOf(const SampleContext &That) const {
773 auto ThisContext = FullContext;
774 auto ThatContext = That.FullContext;
775 if (ThatContext.size() < ThisContext.size())
776 return false;
777 ThatContext = ThatContext.take_front(ThisContext.size());
778 // Compare Leaf frame first
779 if (ThisContext.back().Func != ThatContext.back().Func)
780 return false;
781 // Compare leading context
782 return ThisContext.drop_back() == ThatContext.drop_back();
783 }
784
785private:
786 // The function associated with this context. If CS profile, this is the leaf
787 // function.
788 FunctionId Func;
789 // Full context including calling context and leaf function name
790 SampleContextFrames FullContext;
791 // State of the associated sample profile
792 uint32_t State;
793 // Attribute of the associated sample profile
794 uint32_t Attributes;
795};
796
797static inline hash_code hash_value(const SampleContext &Context) {
798 return Context.getHashCode();
799}
800
801inline raw_ostream &operator<<(raw_ostream &OS, const SampleContext &Context) {
802 return OS << Context.toString();
803}
804
805class FunctionSamples;
807
808using BodySampleMap = std::map<LineLocation, SampleRecord>;
809// NOTE: Using a StringMap here makes parsed profiles consume around 17% more
810// memory, which is *very* significant for large profiles.
811using FunctionSamplesMap = std::map<FunctionId, FunctionSamples>;
812using CallsiteSampleMap = std::map<LineLocation, FunctionSamplesMap>;
813using CallsiteTypeMap = std::map<LineLocation, TypeCountMap>;
815
816/// Representation of the samples collected for a function.
817///
818/// This data structure contains all the collected samples for the body
819/// of a function. Each sample corresponds to a LineLocation instance
820/// within the body of the function.
822public:
823 FunctionSamples() = default;
824
825 LLVM_ABI void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
826 LLVM_ABI void dump() const;
827
829 bool Overflowed;
830 TotalSamples =
831 SaturatingMultiplyAdd(Num, Weight, TotalSamples, &Overflowed);
832 return Overflowed ? sampleprof_error::counter_overflow
834 }
835
837 if (TotalSamples < Num)
838 TotalSamples = 0;
839 else
840 TotalSamples -= Num;
841 }
842
843 void setTotalSamples(uint64_t Num) { TotalSamples = Num; }
844
845 void setHeadSamples(uint64_t Num) { TotalHeadSamples = Num; }
846
848 bool Overflowed;
849 TotalHeadSamples =
850 SaturatingMultiplyAdd(Num, Weight, TotalHeadSamples, &Overflowed);
851 return Overflowed ? sampleprof_error::counter_overflow
853 }
854
856 uint64_t Num, uint64_t Weight = 1) {
857 return BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(
858 Num, Weight);
859 }
860
862 uint32_t Discriminator,
863 FunctionId Func, uint64_t Num,
864 uint64_t Weight = 1) {
865 return BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(
866 Func, Num, Weight);
867 }
868
871 uint64_t Weight = 1) {
872 return BodySamples[Location].merge(SampleRecord, Weight);
873 }
874
875 // Remove a call target and decrease the body sample correspondingly. Return
876 // the number of body samples actually decreased.
878 uint32_t Discriminator,
879 FunctionId Func) {
880 uint64_t Count = 0;
881 auto I = BodySamples.find(LineLocation(LineOffset, Discriminator));
882 if (I != BodySamples.end()) {
883 Count = I->second.removeCalledTarget(Func);
884 Count = I->second.removeSamples(Count);
885 if (!I->second.getSamples())
886 BodySamples.erase(I);
887 }
888 return Count;
889 }
890
891 // Remove all call site samples for inlinees. This is needed when flattening
892 // a nested profile.
893 void removeAllCallsiteSamples() { CallsiteSamples.clear(); }
894
895 // Accumulate all call target samples to update the body samples.
897 for (auto &I : BodySamples) {
898 uint64_t TargetSamples = I.second.getCallTargetSum();
899 // It's possible that the body sample count can be greater than the call
900 // target sum. E.g, if some call targets are external targets, they won't
901 // be considered valid call targets, but the body sample count which is
902 // from lbr ranges can actually include them.
903 if (TargetSamples > I.second.getSamples())
904 I.second.addSamples(TargetSamples - I.second.getSamples());
905 }
906 }
907
908 // Accumulate all body samples to set total samples.
911 for (const auto &I : BodySamples)
912 addTotalSamples(I.second.getSamples());
913
914 for (auto &I : CallsiteSamples) {
915 for (auto &CS : I.second) {
916 CS.second.updateTotalSamples();
917 addTotalSamples(CS.second.getTotalSamples());
918 }
919 }
920 }
921
922 // Set current context and all callee contexts to be synthetic.
924 Context.setState(SyntheticContext);
925 for (auto &I : CallsiteSamples) {
926 for (auto &CS : I.second) {
927 CS.second.setContextSynthetic();
928 }
929 }
930 }
931
932 // Propagate the given attribute to this profile context and all callee
933 // contexts.
935 Context.setAttribute(Attr);
936 for (auto &I : CallsiteSamples) {
937 for (auto &CS : I.second) {
938 CS.second.setContextAttribute(Attr);
939 }
940 }
941 }
942
943 // Query the stale profile matching results and remap the location.
944 const LineLocation &mapIRLocToProfileLoc(const LineLocation &IRLoc) const {
945 // There is no remapping if the profile is not stale or the matching gives
946 // the same location.
947 if (!IRToProfileLocationMap)
948 return IRLoc;
949 const auto &ProfileLoc = IRToProfileLocationMap->find(IRLoc);
950 if (ProfileLoc != IRToProfileLocationMap->end())
951 return ProfileLoc->second;
952 return IRLoc;
953 }
954
955 /// Return the number of samples collected at the given location.
956 /// Each location is specified by \p LineOffset and \p Discriminator.
957 /// If the location is not found in profile, return error.
959 uint32_t Discriminator) const {
960 const auto &Ret = BodySamples.find(
961 mapIRLocToProfileLoc(LineLocation(LineOffset, Discriminator)));
962 if (Ret == BodySamples.end())
963 return std::error_code();
964 return Ret->second.getSamples();
965 }
966
967 /// Returns the call target map collected at a given location.
968 /// Each location is specified by \p LineOffset and \p Discriminator.
969 /// If the location is not found in profile, return error.
971 findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const {
972 const auto &Ret = BodySamples.find(
973 mapIRLocToProfileLoc(LineLocation(LineOffset, Discriminator)));
974 if (Ret == BodySamples.end())
975 return std::error_code();
976 return Ret->second.getCallTargets();
977 }
978
979 /// Returns the call target map collected at a given location specified by \p
980 /// CallSite. If the location is not found in profile, return error.
982 findCallTargetMapAt(const LineLocation &CallSite) const {
983 const auto &Ret = BodySamples.find(mapIRLocToProfileLoc(CallSite));
984 if (Ret == BodySamples.end())
985 return std::error_code();
986 return Ret->second.getCallTargets();
987 }
988
989 /// Return the function samples at the given callsite location.
991 return CallsiteSamples[mapIRLocToProfileLoc(Loc)];
992 }
993
994 /// Returns the FunctionSamplesMap at the given \p Loc.
995 const FunctionSamplesMap *
997 auto Iter = CallsiteSamples.find(mapIRLocToProfileLoc(Loc));
998 if (Iter == CallsiteSamples.end())
999 return nullptr;
1000 return &Iter->second;
1001 }
1002
1003 /// Returns the TypeCountMap for inlined callsites at the given \p Loc.
1005 auto Iter = VirtualCallsiteTypeCounts.find(mapIRLocToProfileLoc(Loc));
1006 if (Iter == VirtualCallsiteTypeCounts.end())
1007 return nullptr;
1008 return &Iter->second;
1009 }
1010
1011 /// Returns a pointer to FunctionSamples at the given callsite location
1012 /// \p Loc with callee \p CalleeName. If no callsite can be found, relax
1013 /// the restriction to return the FunctionSamples at callsite location
1014 /// \p Loc with the maximum total sample count. If \p Remapper or \p
1015 /// FuncNameToProfNameMap is not nullptr, use them to find FunctionSamples
1016 /// with equivalent name as \p CalleeName.
1021 *FuncNameToProfNameMap = nullptr) const;
1022
1023 bool empty() const { return TotalSamples == 0; }
1024
1025 /// Return the total number of samples collected inside the function.
1026 uint64_t getTotalSamples() const { return TotalSamples; }
1027
1028 /// For top-level functions, return the total number of branch samples that
1029 /// have the function as the branch target (or 0 otherwise). This is the raw
1030 /// data fetched from the profile. This should be equivalent to the sample of
1031 /// the first instruction of the symbol. But as we directly get this info for
1032 /// raw profile without referring to potentially inaccurate debug info, this
1033 /// gives more accurate profile data and is preferred for standalone symbols.
1034 uint64_t getHeadSamples() const { return TotalHeadSamples; }
1035
1036 /// Return an estimate of the sample count of the function entry basic block.
1037 /// The function can be either a standalone symbol or an inlined function.
1038 /// For Context-Sensitive profiles, this will prefer returning the head
1039 /// samples (i.e. getHeadSamples()), if non-zero. Otherwise it estimates from
1040 /// the function body's samples or callsite samples.
1043 // For CS profile, if we already have more accurate head samples
1044 // counted by branch sample from caller, use them as entry samples.
1045 return getHeadSamples();
1046 }
1047 uint64_t Count = 0;
1048 // Use either BodySamples or CallsiteSamples which ever has the smaller
1049 // lineno.
1050 if (!BodySamples.empty() &&
1051 (CallsiteSamples.empty() ||
1052 BodySamples.begin()->first < CallsiteSamples.begin()->first))
1053 Count = BodySamples.begin()->second.getSamples();
1054 else if (!CallsiteSamples.empty()) {
1055 // An indirect callsite may be promoted to several inlined direct calls.
1056 // We need to get the sum of them.
1057 for (const auto &FuncSamples : CallsiteSamples.begin()->second)
1058 Count += FuncSamples.second.getHeadSamplesEstimate();
1059 }
1060 // Return at least 1 if total sample is not 0.
1061 return Count ? Count : TotalSamples > 0;
1062 }
1063
1064 /// Return all the samples collected in the body of the function.
1065 const BodySampleMap &getBodySamples() const { return BodySamples; }
1066
1067 /// Return all the callsite samples collected in the body of the function.
1069 return CallsiteSamples;
1070 }
1071
1072 /// Return whether this function profile contains callsite samples.
1073 bool hasCallsiteSamples() const { return !CallsiteSamples.empty(); }
1074
1075 /// Returns vtable access samples for the C++ types collected in this
1076 /// function.
1078 return VirtualCallsiteTypeCounts;
1079 }
1080
1081 /// Returns the vtable access samples for the C++ types for \p Loc.
1082 /// Under the hood, the caller-specified \p Loc will be un-drifted before the
1083 /// type sample lookup if possible.
1085 return VirtualCallsiteTypeCounts[mapIRLocToProfileLoc(Loc)];
1086 }
1087
1088 /// At location \p Loc, add a type sample for the given \p Type with
1089 /// \p Count. This function uses saturating add which clamp the result to
1090 /// maximum uint64_t (the counter type), and inserts the saturating add result
1091 /// to map. Returns counter_overflow to caller if the actual result is larger
1092 /// than maximum uint64_t.
1094 uint64_t Count) {
1095 auto &TypeCounts = getTypeSamplesAt(Loc);
1096 bool Overflowed = false;
1097 TypeCounts[Type] = SaturatingMultiplyAdd(Count, /* Weight= */ (uint64_t)1,
1098 TypeCounts[Type], &Overflowed);
1099 return Overflowed ? sampleprof_error::counter_overflow
1101 }
1102
1103 /// Scale \p Other sample counts by \p Weight and add the scaled result to the
1104 /// type samples for \p Loc. Under the hoold, the caller-provided \p Loc will
1105 /// be un-drifted before the type sample lookup if possible.
1106 /// typename T is either a std::map or a DenseMap.
1107 template <typename T>
1109 const T &Other,
1110 uint64_t Weight = 1) {
1111 static_assert((std::is_same_v<typename T::key_type, StringRef> ||
1112 std::is_same_v<typename T::key_type, FunctionId>) &&
1113 std::is_same_v<typename T::mapped_type, uint64_t>,
1114 "T must be a map with StringRef or FunctionId as key and "
1115 "uint64_t as value");
1116 TypeCountMap &TypeCounts = getTypeSamplesAt(Loc);
1117 bool Overflowed = false;
1118
1119 for (const auto &[Type, Count] : Other) {
1120 FunctionId TypeId(Type);
1121 bool RowOverflow = false;
1122 TypeCounts[TypeId] = SaturatingMultiplyAdd(
1123 Count, Weight, TypeCounts[TypeId], &RowOverflow);
1124 Overflowed |= RowOverflow;
1125 }
1126 return Overflowed ? sampleprof_error::counter_overflow
1128 }
1129
1130 /// Return the maximum of sample counts in a function body. When SkipCallSite
1131 /// is false, which is the default, the return count includes samples in the
1132 /// inlined functions. When SkipCallSite is true, the return count only
1133 /// considers the body samples.
1134 uint64_t getMaxCountInside(bool SkipCallSite = false) const {
1135 uint64_t MaxCount = 0;
1136 for (const auto &L : getBodySamples())
1137 MaxCount = std::max(MaxCount, L.second.getSamples());
1138 if (SkipCallSite)
1139 return MaxCount;
1140 for (const auto &C : getCallsiteSamples())
1141 for (const FunctionSamplesMap::value_type &F : C.second)
1142 MaxCount = std::max(MaxCount, F.second.getMaxCountInside());
1143 return MaxCount;
1144 }
1145
1146 /// Merge the samples in \p Other into this one.
1147 /// Optionally scale samples by \p Weight.
1150 if (!GUIDToFuncNameMap)
1151 GUIDToFuncNameMap = Other.GUIDToFuncNameMap;
1152 if (Context.getFunction().empty())
1153 Context = Other.getContext();
1154 if (FunctionHash == 0) {
1155 // Set the function hash code for the target profile.
1156 FunctionHash = Other.getFunctionHash();
1157 } else if (FunctionHash != Other.getFunctionHash()) {
1158 // The two profiles coming with different valid hash codes indicates
1159 // either:
1160 // 1. They are same-named static functions from different compilation
1161 // units (without using -unique-internal-linkage-names), or
1162 // 2. They are really the same function but from different compilations.
1163 // Let's bail out in either case for now, which means one profile is
1164 // dropped.
1166 }
1167
1168 mergeSampleProfErrors(Result,
1169 addTotalSamples(Other.getTotalSamples(), Weight));
1170 mergeSampleProfErrors(Result,
1171 addHeadSamples(Other.getHeadSamples(), Weight));
1172 for (const auto &I : Other.getBodySamples()) {
1173 const LineLocation &Loc = I.first;
1174 const SampleRecord &Rec = I.second;
1175 mergeSampleProfErrors(Result, BodySamples[Loc].merge(Rec, Weight));
1176 }
1177 for (const auto &I : Other.getCallsiteSamples()) {
1178 const LineLocation &Loc = I.first;
1180 for (const auto &Rec : I.second)
1181 mergeSampleProfErrors(Result,
1182 FSMap[Rec.first].merge(Rec.second, Weight));
1183 }
1184 for (const auto &[Loc, OtherTypeMap] : Other.getCallsiteTypeCounts())
1186 Result, addCallsiteVTableTypeProfAt(Loc, OtherTypeMap, Weight));
1187
1188 return Result;
1189 }
1190
1191 /// Recursively traverses all children, if the total sample count of the
1192 /// corresponding function is no less than \p Threshold, add its corresponding
1193 /// GUID to \p S. Also traverse the BodySamples to add hot CallTarget's GUID
1194 /// to \p S.
1198 uint64_t Threshold) const {
1199 if (TotalSamples <= Threshold)
1200 return;
1201 auto IsDeclaration = [](const Function *F) {
1202 return !F || F->isDeclaration();
1203 };
1204 if (IsDeclaration(SymbolMap.lookup(getFunction()))) {
1205 // Add to the import list only when it's defined out of module.
1206 S.insert(getGUID());
1207 }
1208 // Import hot CallTargets, which may not be available in IR because full
1209 // profile annotation cannot be done until backend compilation in ThinLTO.
1210 for (const auto &BS : BodySamples)
1211 for (const auto &TS : BS.second.getCallTargets())
1212 if (TS.second > Threshold) {
1213 const Function *Callee = SymbolMap.lookup(TS.first);
1214 if (IsDeclaration(Callee))
1215 S.insert(TS.first.getHashCode());
1216 }
1217 for (const auto &CS : CallsiteSamples)
1218 for (const auto &NameFS : CS.second)
1219 NameFS.second.findInlinedFunctions(S, SymbolMap, Threshold);
1220 }
1221
1222 /// Set the name of the function.
1223 void setFunction(FunctionId NewFunctionID) {
1224 Context.setFunction(NewFunctionID);
1225 }
1226
1227 /// Return the function name.
1228 FunctionId getFunction() const { return Context.getFunction(); }
1229
1230 /// Return the original function name.
1232
1233 void setFunctionHash(uint64_t Hash) { FunctionHash = Hash; }
1234
1235 uint64_t getFunctionHash() const { return FunctionHash; }
1236
1238 assert(IRToProfileLocationMap == nullptr && "this should be set only once");
1239 IRToProfileLocationMap = LTLM;
1240 }
1241
1242 /// Return the canonical name for a function, taking into account
1243 /// suffix elision policy attributes.
1245 const char *AttrName = "sample-profile-suffix-elision-policy";
1246 auto Attr = F.getFnAttribute(AttrName).getValueAsString();
1247 return getCanonicalFnName(F.getName(), Attr);
1248 }
1249
1250 /// Name suffixes which canonicalization should handle to avoid
1251 /// profile mismatch.
1252 static constexpr const char *LLVMSuffix = ".llvm.";
1253 static constexpr const char *PartSuffix = ".part.";
1254 static constexpr const char *UniqSuffix = ".__uniq.";
1255
1257 StringRef Attr = "selected") {
1258 // Note the sequence of the suffixes in the knownSuffixes array matters.
1259 // If suffix "A" is appended after the suffix "B", "A" should be in front
1260 // of "B" in knownSuffixes.
1261 const SmallVector<StringRef> KnownSuffixes{LLVMSuffix, PartSuffix,
1262 UniqSuffix};
1263 return getCanonicalFnName(FnName, KnownSuffixes, Attr);
1264 }
1265
1267 StringRef Attr = "selected") {
1268 // A local coroutine function from another CU can be promoted to a global
1269 // function during ThinLTO import. This will create a linkage name like
1270 // "_Zfoo.llvm.xxxx.cleanup". Remove the ".llvm." suffix after stripping all
1271 // the coroutine suffixes to avoid pseudo probe mismatch.
1272 const SmallVector<StringRef, 3> CoroSuffixes{".cleanup", ".destroy",
1273 ".resume", LLVMSuffix};
1274 return getCanonicalFnName(FnName, CoroSuffixes, Attr);
1275 }
1276
1278 ArrayRef<StringRef> Suffixes,
1279 StringRef Attr = "selected") {
1280 if (Attr == "" || Attr == "all")
1281 return FnName.split('.').first;
1282 if (Attr == "selected") {
1283 StringRef Cand(FnName);
1284 for (const auto Suffix : Suffixes) {
1285 // If the profile contains ".__uniq." suffix, don't strip the
1286 // suffix for names in the IR.
1288 continue;
1289 auto It = Cand.rfind(Suffix);
1290 if (It == StringRef::npos)
1291 continue;
1292 auto Dit = Cand.rfind('.');
1293 if (Dit == It || Dit == It + Suffix.size() - 1)
1294 Cand = Cand.substr(0, It);
1295 }
1296 return Cand;
1297 }
1298 if (Attr == "none")
1299 return FnName;
1300 assert(false && "internal error: unknown suffix elision policy");
1301 return FnName;
1302 }
1303
1304 /// Translate \p Func into its original name.
1305 /// When profile doesn't use MD5, \p Func needs no translation.
1306 /// When profile uses MD5, \p Func in current FunctionSamples
1307 /// is actually GUID of the original function name. getFuncName will
1308 /// translate \p Func in current FunctionSamples into its original name
1309 /// by looking up in the function map GUIDToFuncNameMap.
1310 /// If the original name doesn't exist in the map, return empty StringRef.
1312 if (!UseMD5)
1313 return Func.stringRef();
1314
1316 "GUIDToFuncNameMap needs to be populated first");
1317 return GUIDToFuncNameMap->lookup(Func.getHashCode());
1318 }
1319
1320 /// Returns the line offset to the start line of the subprogram.
1321 /// We assume that a single function will not exceed 65535 LOC.
1322 LLVM_ABI static unsigned getOffset(const DILocation *DIL);
1323
1324 /// Returns a unique call site identifier for a given debug location of a call
1325 /// instruction. This is wrapper of two scenarios, the probe-based profile and
1326 /// regular profile, to hide implementation details from the sample loader and
1327 /// the context tracker.
1329 bool ProfileIsFS = false);
1330
1331 /// Returns a unique hash code for a combination of a callsite location and
1332 /// the callee function name.
1333 /// Guarantee MD5 and non-MD5 representation of the same function results in
1334 /// the same hash.
1336 const LineLocation &Callsite) {
1337 return SampleContextFrame(Callee, Callsite).getHashCode();
1338 }
1339
1340 /// Get the FunctionSamples of the inline instance where DIL originates
1341 /// from.
1342 ///
1343 /// The FunctionSamples of the instruction (Machine or IR) associated to
1344 /// \p DIL is the inlined instance in which that instruction is coming from.
1345 /// We traverse the inline stack of that instruction, and match it with the
1346 /// tree nodes in the profile.
1347 ///
1348 /// \returns the FunctionSamples pointer to the inlined instance.
1349 /// If \p Remapper or \p FuncNameToProfNameMap is not nullptr, it will be used
1350 /// to find matching FunctionSamples with not exactly the same but equivalent
1351 /// name.
1354 SampleProfileReaderItaniumRemapper *Remapper = nullptr,
1356 *FuncNameToProfNameMap = nullptr) const;
1357
1358 SampleContext &getContext() const { return Context; }
1359
1360 void setContext(const SampleContext &FContext) { Context = FContext; }
1361
1362 // These boolean variables are atomic so that parallel in-process ThinLTO
1363 // backends writing the same value do not race.
1364 LLVM_ABI static std::atomic<bool> ProfileIsProbeBased;
1365
1366 LLVM_ABI static std::atomic<bool> ProfileIsCS;
1367
1368 LLVM_ABI static std::atomic<bool> ProfileIsPreInlined;
1369
1370 /// Whether the profile uses MD5 to represent string.
1371 LLVM_ABI static std::atomic<bool> UseMD5;
1372
1373 /// Whether the profile contains any ".__uniq." suffix in a name.
1374 LLVM_ABI static std::atomic<bool> HasUniqSuffix;
1375
1376 /// If this profile uses flow sensitive discriminators.
1377 LLVM_ABI static std::atomic<bool> ProfileIsFS;
1378
1379 /// GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
1380 /// all the function symbols defined or declared in current module.
1382
1383 /// Return the GUID of the context's name. If the context is already using
1384 /// MD5, don't hash it again.
1385 uint64_t getGUID() const { return getFunction().getHashCode(); }
1386
1387 // Find all the names in the current FunctionSamples including names in
1388 // all the inline instances and names of call targets.
1389 LLVM_ABI void findAllNames(DenseSet<FunctionId> &NameSet) const;
1390
1391 bool operator==(const FunctionSamples &Other) const {
1392 return (GUIDToFuncNameMap == Other.GUIDToFuncNameMap ||
1393 (GUIDToFuncNameMap && Other.GUIDToFuncNameMap &&
1394 *GUIDToFuncNameMap == *Other.GUIDToFuncNameMap)) &&
1395 FunctionHash == Other.FunctionHash && Context == Other.Context &&
1396 TotalSamples == Other.TotalSamples &&
1397 TotalHeadSamples == Other.TotalHeadSamples &&
1398 BodySamples == Other.BodySamples &&
1399 CallsiteSamples == Other.CallsiteSamples;
1400 }
1401
1402 bool operator!=(const FunctionSamples &Other) const {
1403 return !(*this == Other);
1404 }
1405
1406private:
1407 /// CFG hash value for the function.
1408 uint64_t FunctionHash = 0;
1409
1410 /// Calling context for function profile
1411 mutable SampleContext Context;
1412
1413 /// Total number of samples collected inside this function.
1414 ///
1415 /// Samples are cumulative, they include all the samples collected
1416 /// inside this function and all its inlined callees.
1417 uint64_t TotalSamples = 0;
1418
1419 /// Total number of samples collected at the head of the function.
1420 /// This is an approximation of the number of calls made to this function
1421 /// at runtime.
1422 uint64_t TotalHeadSamples = 0;
1423
1424 /// Map instruction locations to collected samples.
1425 ///
1426 /// Each entry in this map contains the number of samples
1427 /// collected at the corresponding line offset. All line locations
1428 /// are an offset from the start of the function.
1429 BodySampleMap BodySamples;
1430
1431 /// Map call sites to collected samples for the called function.
1432 ///
1433 /// Each entry in this map corresponds to all the samples
1434 /// collected for the inlined function call at the given
1435 /// location. For example, given:
1436 ///
1437 /// void foo() {
1438 /// 1 bar();
1439 /// ...
1440 /// 8 baz();
1441 /// }
1442 ///
1443 /// If the bar() and baz() calls were inlined inside foo(), this
1444 /// map will contain two entries. One for all the samples collected
1445 /// in the call to bar() at line offset 1, the other for all the samples
1446 /// collected in the call to baz() at line offset 8.
1447 CallsiteSampleMap CallsiteSamples;
1448
1449 /// Map a virtual callsite to the list of accessed vtables and vtable counts.
1450 /// The callsite is referenced by its source location.
1451 ///
1452 /// For example, given:
1453 ///
1454 /// void foo() {
1455 /// ...
1456 /// 5 inlined_vcall_bar();
1457 /// ...
1458 /// 5 inlined_vcall_baz();
1459 /// ...
1460 /// 200 inlined_vcall_qux();
1461 /// }
1462 /// This map will contain two entries. One with two types for line offset 5
1463 /// and one with one type for line offset 200.
1464 CallsiteTypeMap VirtualCallsiteTypeCounts;
1465
1466 /// IR to profile location map generated by stale profile matching.
1467 ///
1468 /// Each entry is a mapping from the location on current build to the matched
1469 /// location in the "stale" profile. For example:
1470 /// Profiled source code:
1471 /// void foo() {
1472 /// 1 bar();
1473 /// }
1474 ///
1475 /// Current source code:
1476 /// void foo() {
1477 /// 1 // Code change
1478 /// 2 bar();
1479 /// }
1480 /// Supposing the stale profile matching algorithm generated the mapping [2 ->
1481 /// 1], the profile query using the location of bar on the IR which is 2 will
1482 /// be remapped to 1 and find the location of bar in the profile.
1483 const LocToLocMap *IRToProfileLocationMap = nullptr;
1484};
1485
1486/// Get the proper representation of a string according to whether the
1487/// current Format uses MD5 to represent the string.
1489 if (Name.empty() || !FunctionSamples::UseMD5)
1490 return FunctionId(Name);
1492}
1493
1495
1496/// This class provides operator overloads to the map container using MD5 as the
1497/// key type, so that existing code can still work in most cases using
1498/// SampleContext as key.
1499/// Note: when populating container, make sure to assign the SampleContext to
1500/// the mapped value immediately because the key no longer holds it.
1502 : public HashKeyMap<std::unordered_map, SampleContext, FunctionSamples> {
1503public:
1504 // Convenience method because this is being used in many places. Set the
1505 // FunctionSamples' context if its newly inserted.
1507 auto Ret = try_emplace(Ctx, FunctionSamples());
1508 if (Ret.second)
1509 Ret.first->second.setContext(Ctx);
1510 return Ret.first->second;
1511 }
1512
1517
1522
1523 size_t erase(const SampleContext &Ctx) {
1524 return HashKeyMap<std::unordered_map, SampleContext,
1526 }
1527
1528 size_t erase(const key_type &Key) { return base_type::erase(Key); }
1529
1530 iterator erase(iterator It) { return base_type::erase(It); }
1531};
1532
1533using NameFunctionSamples = std::pair<hash_code, const FunctionSamples *>;
1534
1535LLVM_ABI void
1536sortFuncProfiles(const SampleProfileMap &ProfileMap,
1537 std::vector<NameFunctionSamples> &SortedProfiles);
1538
1539/// SampleContextTrimmer impelements helper functions to trim, merge cold
1540/// context profiles. It also supports context profile canonicalization to make
1541/// sure ProfileMap's key is consistent with FunctionSample's name/context.
1543public:
1544 SampleContextTrimmer(SampleProfileMap &Profiles) : ProfileMap(Profiles) {};
1545 // Trim and merge cold context profile when requested. TrimBaseProfileOnly
1546 // should only be effective when TrimColdContext is true. On top of
1547 // TrimColdContext, TrimBaseProfileOnly can be used to specify to trim all
1548 // cold profiles or only cold base profiles. Trimming base profiles only is
1549 // mainly to honor the preinliner decsion. Note that when MergeColdContext is
1550 // true, preinliner decsion is not honored anyway so TrimBaseProfileOnly will
1551 // be ignored.
1553 bool TrimColdContext,
1554 bool MergeColdContext,
1555 uint32_t ColdContextFrameLength,
1556 bool TrimBaseProfileOnly);
1557
1558private:
1559 SampleProfileMap &ProfileMap;
1560};
1561
1562/// Helper class for profile conversion.
1563///
1564/// It supports full context-sensitive profile to nested profile conversion,
1565/// nested profile to flatten profile conversion, etc.
1567public:
1569 // Convert a full context-sensitive flat sample profile into a nested sample
1570 // profile.
1572 struct FrameNode {
1574 FunctionSamples *FSamples = nullptr,
1575 LineLocation CallLoc = {0, 0})
1576 : FuncName(FName), FuncSamples(FSamples), CallSiteLoc(CallLoc) {};
1577
1578 // Map line+discriminator location to child frame
1579 std::map<uint64_t, FrameNode> AllChildFrames;
1580 // Function name for current frame
1582 // Function Samples for current frame
1584 // Callsite location in parent context
1586
1588 FunctionId CalleeName);
1589 };
1590
1591 static void flattenProfile(SampleProfileMap &ProfileMap,
1592 bool ProfileIsCS = false) {
1593 SampleProfileMap TmpProfiles;
1594 flattenProfile(ProfileMap, TmpProfiles, ProfileIsCS);
1595 ProfileMap = std::move(TmpProfiles);
1596 }
1597
1598 static void flattenProfile(const SampleProfileMap &InputProfiles,
1599 SampleProfileMap &OutputProfiles,
1600 bool ProfileIsCS = false) {
1601 if (ProfileIsCS) {
1602 for (const auto &I : InputProfiles) {
1603 // Retain the profile name and clear the full context for each function
1604 // profile.
1605 FunctionSamples &FS = OutputProfiles.create(I.second.getFunction());
1606 FS.merge(I.second);
1607 }
1608 } else {
1609 for (const auto &I : InputProfiles)
1610 flattenNestedProfile(OutputProfiles, I.second);
1611 }
1612 }
1613
1614private:
1615 static void flattenNestedProfile(SampleProfileMap &OutputProfiles,
1616 const FunctionSamples &FS) {
1617 // To retain the context, checksum, attributes of the original profile, make
1618 // a copy of it if no profile is found.
1619 SampleContext &Context = FS.getContext();
1620 auto Ret = OutputProfiles.try_emplace(Context, FS);
1621 FunctionSamples &Profile = Ret.first->second;
1622 if (Ret.second) {
1623 // Clear nested inlinees' samples for the flattened copy. These inlinees
1624 // will have their own top-level entries after flattening.
1625 Profile.removeAllCallsiteSamples();
1626 // We recompute TotalSamples later, so here set to zero.
1627 Profile.setTotalSamples(0);
1628 } else {
1629 for (const auto &[LineLocation, SampleRecord] : FS.getBodySamples()) {
1630 Profile.addSampleRecord(LineLocation, SampleRecord);
1631 }
1632 }
1633
1634 assert(Profile.getCallsiteSamples().empty() &&
1635 "There should be no inlinees' profiles after flattening.");
1636
1637 // TotalSamples might not be equal to the sum of all samples from
1638 // BodySamples and CallsiteSamples. So here we use "TotalSamples =
1639 // Original_TotalSamples - All_of_Callsite_TotalSamples +
1640 // All_of_Callsite_HeadSamples" to compute the new TotalSamples.
1641 uint64_t TotalSamples = FS.getTotalSamples();
1642
1643 for (const auto &I : FS.getCallsiteSamples()) {
1644 for (const auto &Callee : I.second) {
1645 const auto &CalleeProfile = Callee.second;
1646 // Add body sample.
1647 Profile.addBodySamples(I.first.LineOffset, I.first.Discriminator,
1648 CalleeProfile.getHeadSamplesEstimate());
1649 // Add callsite sample.
1650 Profile.addCalledTargetSamples(I.first.LineOffset,
1651 I.first.Discriminator,
1652 CalleeProfile.getFunction(),
1653 CalleeProfile.getHeadSamplesEstimate());
1654 // Update total samples.
1655 TotalSamples = TotalSamples >= CalleeProfile.getTotalSamples()
1656 ? TotalSamples - CalleeProfile.getTotalSamples()
1657 : 0;
1658 TotalSamples += CalleeProfile.getHeadSamplesEstimate();
1659 // Recursively convert callee profile.
1660 flattenNestedProfile(OutputProfiles, CalleeProfile);
1661 }
1662 }
1663 Profile.addTotalSamples(TotalSamples);
1664
1665 Profile.setHeadSamples(Profile.getHeadSamplesEstimate());
1666 }
1667
1668 // Nest all children profiles into the profile of Node.
1669 void convertCSProfiles(FrameNode &Node);
1670 FrameNode *getOrCreateContextPath(const SampleContext &Context);
1671
1672 SampleProfileMap &ProfileMap;
1673 FrameNode RootFrame;
1674};
1675
1676/// ProfileSymbolList records the list of function symbols shown up
1677/// in the binary used to generate the profile. It is useful to
1678/// to discriminate a function being so cold as not to shown up
1679/// in the profile and a function newly added.
1681public:
1682 /// copy indicates whether we need to copy the underlying memory
1683 /// for the input Name.
1684 void add(StringRef Name, bool Copy = false) {
1685 if (!Copy) {
1686 Syms.insert(Name);
1687 return;
1688 }
1689 Syms.insert(Name.copy(Allocator));
1690 }
1691
1692 bool contains(StringRef Name) const {
1693 return IsMD5 ? ColdGUIDTable.contains(llvm::MD5Hash(Name))
1694 : Syms.count(Name);
1695 }
1696
1698 assert(!List.IsMD5 &&
1699 "Merging pre-hashed MD5 ProfileSymbolList not yet implemented");
1700 for (auto Sym : List.Syms)
1701 add(Sym, true);
1702 }
1703
1704 unsigned size() const { return IsMD5 ? ColdGUIDTable.size() : Syms.size(); }
1705 void reserve(size_t Size) { Syms.reserve(Size); }
1706
1707 std::vector<uint64_t> collectGUIDs() const {
1708 assert(!IsMD5 &&
1709 "Collecting GUIDs from existing MD5 table not yet implemented");
1710 std::vector<uint64_t> Keys;
1711 Keys.reserve(Syms.size());
1713 llvm::sort(Keys);
1714 Keys.erase(llvm::unique(Keys), Keys.end());
1715 return Keys;
1716 }
1717
1719 assert(Syms.empty() &&
1720 "Setting ColdGUIDTable shadows existing strings in Syms");
1721 ColdGUIDTable = Table;
1722 IsMD5 = true;
1723 }
1725 assert(IsMD5 && "Retrieving ColdGUIDTable from non-MD5 ProfileSymbolList");
1726 return ColdGUIDTable;
1727 }
1728 bool isMD5() const { return IsMD5; }
1729
1730 LLVM_ABI std::error_code read(const uint8_t *Data, uint64_t ListSize);
1731 LLVM_ABI std::error_code write(raw_ostream &OS);
1732 LLVM_ABI void dump(raw_ostream &OS = dbgs()) const;
1733
1734private:
1735 bool IsMD5 = false;
1739};
1740
1741} // end namespace sampleprof
1742
1743using namespace sampleprof;
1744// Provide DenseMapInfo for SampleContext.
1745template <> struct DenseMapInfo<SampleContext> {
1746 static unsigned getHashValue(const SampleContext &Val) {
1747 return Val.getHashCode();
1748 }
1749
1750 static bool isEqual(const SampleContext &LHS, const SampleContext &RHS) {
1751 return LHS == RHS;
1752 }
1753};
1754
1755// Prepend "__uniq" before the hash for tools like profilers to understand
1756// that this symbol is of internal linkage type. The "__uniq" is the
1757// pre-determined prefix that is used to tell tools that this symbol was
1758// created with -funique-internal-linkage-symbols and the tools can strip or
1759// keep the prefix as needed.
1760inline std::string getUniqueInternalLinkagePostfix(const StringRef &FName) {
1761 llvm::MD5 Md5;
1762 Md5.update(FName);
1764 Md5.final(R);
1765 SmallString<32> Str;
1767 // Convert MD5hash to Decimal. Demangler suffixes can either contain
1768 // numbers or characters but not both.
1769 llvm::APInt IntHash(128, Str.str(), 16);
1770 return toString(IntHash, /* Radix = */ 10, /* Signed = */ false)
1771 .insert(0, FunctionSamples::UniqSuffix);
1772}
1773
1774} // end namespace llvm
1775
1776#endif // LLVM_PROFILEDATA_SAMPLEPROF_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
always inline
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_DEPRECATED(MSG, FIX)
Definition Compiler.h:260
#define LLVM_ABI
Definition Compiler.h:215
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 HashKeyMap template.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Load MIR Sample Profile
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)
This file implements a map that provides insertion order iteration.
#define T
Defines FunctionId class.
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:250
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
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:286
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:233
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
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.
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
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:209
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:821
void setTotalSamples(uint64_t Num)
Definition SampleProf.h:843
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:934
LLVM_ABI const FunctionSamples * findFunctionSamples(const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper=nullptr, const HashKeyMap< DenseMap, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const
Get the FunctionSamples of the inline instance where DIL originates from.
bool operator!=(const FunctionSamples &Other) const
void setHeadSamples(uint64_t Num)
Definition SampleProf.h:845
sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:828
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.
LLVM_ABI const FunctionSamples * findFunctionSamplesAt(const LineLocation &Loc, StringRef CalleeName, SampleProfileReaderItaniumRemapper *Remapper, const HashKeyMap< DenseMap, FunctionId, FunctionId > *FuncNameToProfNameMap=nullptr) const
Returns a pointer to FunctionSamples at the given callsite location Loc with callee CalleeName.
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")
const FunctionSamplesMap * findFunctionSamplesMapAt(const LineLocation &Loc) const
Returns the FunctionSamplesMap at the given Loc.
Definition SampleProf.h:996
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:836
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:958
ErrorOr< const SampleRecord::CallTargetMap & > findCallTargetMapAt(const LineLocation &CallSite) const
Returns the call target map collected at a given location specified by CallSite.
Definition SampleProf.h:982
const LineLocation & mapIRLocToProfileLoc(const LineLocation &IRLoc) const
Definition SampleProf.h:944
static StringRef getCanonicalFnName(StringRef FnName, ArrayRef< StringRef > Suffixes, StringRef Attr="selected")
FunctionId getFunction() const
Return the function name.
const CallsiteTypeMap & getCallsiteTypeCounts() const
Returns vtable access samples for the C++ types collected in this function.
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.
StringRef getFuncName(FunctionId Func) const
Translate Func into its original name.
const TypeCountMap * findCallsiteTypeSamplesAt(const LineLocation &Loc) const
Returns the TypeCountMap for inlined callsites at the given Loc.
sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:847
sampleprof_error addSampleRecord(LineLocation Location, const SampleRecord &SampleRecord, uint64_t Weight=1)
Definition SampleProf.h:869
uint64_t removeCalledTargetAndBodySample(uint32_t LineOffset, uint32_t Discriminator, FunctionId Func)
Definition SampleProf.h:877
DenseMap< uint64_t, StringRef > * GUIDToFuncNameMap
GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for all the function symbols define...
sampleprof_error addCalledTargetSamples(uint32_t LineOffset, uint32_t Discriminator, FunctionId Func, uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:861
FunctionSamplesMap & functionSamplesAt(const LineLocation &Loc)
Return the function samples at the given callsite location.
Definition SampleProf.h:990
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
sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator, uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:855
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)
static LLVM_ABI std::atomic< bool > ProfileIsProbeBased
ErrorOr< const SampleRecord::CallTargetMap & > findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const
Returns the call target map collected at a given location.
Definition SampleProf.h:971
SampleContext & getContext() const
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.
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
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 findInlinedFunctions(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, uint64_t Threshold) const
Recursively traverses all children, if the total sample count of the corresponding function is no les...
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.
TypeCountMap & getTypeSamplesAt(const LineLocation &Loc)
Returns the vtable access samples for the C++ types for Loc.
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
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:643
bool operator==(const SampleContext &That) const
Definition SampleProf.h:736
void setFunction(FunctionId NewFunctionID)
Set the name of the function and clear the current context.
Definition SampleProf.h:722
SampleContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
Definition SampleProf.h:612
bool operator<(const SampleContext &That) const
Definition SampleProf.h:743
SampleContext(StringRef ContextStr, std::list< SampleContextFrameVector > &CSNameTable, ContextStateMask CState=RawContext)
Definition SampleProf.h:622
bool hasState(ContextStateMask S)
Definition SampleProf.h:688
void clearState(ContextStateMask S)
Definition SampleProf.h:690
SampleContextFrames getContextFrames() const
Definition SampleProf.h:694
static void decodeContextString(StringRef ContextStr, FunctionId &Func, LineLocation &LineLoc)
Definition SampleProf.h:662
static std::string getContextString(SampleContextFrames Context, bool IncludeLeafLineLocation=false)
Definition SampleProf.h:696
bool operator!=(const SampleContext &That) const
Definition SampleProf.h:741
void setState(ContextStateMask S)
Definition SampleProf.h:689
void setAllAttributes(uint32_t A)
Definition SampleProf.h:687
void setContext(SampleContextFrames Context, ContextStateMask CState=RawContext)
Definition SampleProf.h:728
FunctionId getFunction() const
Definition SampleProf.h:693
void setAttribute(ContextAttributeMask A)
Definition SampleProf.h:685
bool hasAttribute(ContextAttributeMask A)
Definition SampleProf.h:684
std::string toString() const
Definition SampleProf.h:709
bool isPrefixOf(const SampleContext &That) const
Definition SampleProf.h:772
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:395
static SortedCallTargetSet sortCallTargets(const CallTargetMap &Targets)
Sort call targets in descending order of call frequency.
Definition SampleProf.h:476
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:460
LLVM_ABI sampleprof_error merge(const SampleRecord &Other, uint64_t Weight=1)
Merge the samples in Other into this record.
const CallTargetMap & getCallTargets() const
Definition SampleProf.h:463
SortedCallTargetSet getSortedCallTargets() const
Definition SampleProf.h:464
uint64_t getCallTargetSum() const
Definition SampleProf.h:468
uint64_t removeSamples(uint64_t S)
Decrease the number of samples for this record by S.
Definition SampleProf.h:425
sampleprof_error addSamples(uint64_t S, uint64_t Weight=1)
Increment the number of samples for this record by S.
Definition SampleProf.h:416
uint64_t removeCalledTarget(FunctionId F)
Remove called function from the call target map.
Definition SampleProf.h:449
static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets, float DistributionFactor)
Prorate call targets by a distribution factor.
Definition SampleProf.h:483
SortedVectorMap< FunctionId, uint64_t, 0 > CallTargetMap
Definition SampleProf.h:408
std::pair< FunctionId, uint64_t > CallTarget
Definition SampleProf.h:397
bool operator!=(const SampleRecord &Other) const
Definition SampleProf.h:508
SmallVector< CallTarget > SortedCallTargetSet
Definition SampleProf.h:407
bool operator==(const SampleRecord &Other) const
Definition SampleProf.h:504
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:437
#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:261
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:132
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:292
std::map< LineLocation, FunctionSamplesMap > CallsiteSampleMap
Definition SampleProf.h:812
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:308
static constexpr uint64_t LatestVersion
Definition SampleProf.h:129
ArrayRef< SampleContextFrame > SampleContextFrames
Definition SampleProf.h:582
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:237
@ SecFlagHasVTableTypeProf
SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
Definition SampleProf.h:240
@ SecFlagPartial
SecFlagPartial means the profile is for common/shared code.
Definition SampleProf.h:228
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
Definition SampleProf.h:234
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
Definition SampleProf.h:231
static void removeSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:300
DenseMap< LineLocation, LineLocation > LocToLocMap
Definition SampleProf.h:814
SmallVector< SampleContextFrame, 1 > SampleContextFrameVector
Definition SampleProf.h:581
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
Definition SampleProf.h:811
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:126
std::map< FunctionId, uint64_t > TypeCountMap
Key represents type of a C++ polymorphic class type by its vtable and value represents its counter.
Definition SampleProf.h:375
static std::string getSecName(SecType Type)
Definition SampleProf.h:156
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.
static uint64_t SPVersion()
Definition SampleProf.h:138
std::map< LineLocation, TypeCountMap > CallsiteTypeMap
Definition SampleProf.h:813
std::map< LineLocation, SampleRecord > BodySampleMap
Definition SampleProf.h:808
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:2208
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:365
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:1636
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:685
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:390
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:285
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
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:359
static bool isEqual(const sampleprof::LineLocation &LHS, const sampleprof::LineLocation &RHS)
Definition SampleProf.h:363
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:324
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:325
bool operator!=(const LineLocation &O) const
Definition SampleProf.h:342
bool operator<(const LineLocation &O) const
Definition SampleProf.h:333
bool operator==(const LineLocation &O) const
Definition SampleProf.h:338
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:585
bool operator==(const SampleContextFrame &That) const
Definition SampleProf.h:545
SampleContextFrame(FunctionId Func, LineLocation Location)
Definition SampleProf.h:542
bool operator!=(const SampleContextFrame &That) const
Definition SampleProf.h:549
std::string toString(bool OutputLineLocation) const
Definition SampleProf.h:553
uint64_t operator()(const SampleContext &Context) const
Definition SampleProf.h:767
bool operator()(const CallTarget &LHS, const CallTarget &RHS) const
Definition SampleProf.h:399