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