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