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