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