LLVM 24.0.0git
SampleProfReader.h
Go to the documentation of this file.
1//===- SampleProfReader.h - Read LLVM sample profile data -------*- 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 definitions needed for reading sample profiles.
10//
11// NOTE: If you are making changes to this file format, please remember
12// to document them in the Clang documentation at
13// tools/clang/docs/UsersManual.rst.
14//
15// Text format
16// -----------
17//
18// Sample profiles are written as ASCII text. The file is divided into
19// sections, which correspond to each of the functions executed at runtime.
20// Each section has the following format
21//
22// function1:total_samples:total_head_samples
23// offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
24// offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
25// ...
26// offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
27// offsetA[.discriminator]: fnA:num_of_total_samples
28// offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
29// ...
30// !CFGChecksum: num
31// !Attribute: flags
32//
33// This is a nested tree in which the indentation represents the nesting level
34// of the inline stack. There are no blank lines in the file. And the spacing
35// within a single line is fixed. Additional spaces will result in an error
36// while reading the file.
37//
38// Any line starting with the '#' character is completely ignored.
39//
40// Inlined calls are represented with indentation. The Inline stack is a
41// stack of source locations in which the top of the stack represents the
42// leaf function, and the bottom of the stack represents the actual
43// symbol to which the instruction belongs.
44//
45// Function names must be mangled in order for the profile loader to
46// match them in the current translation unit. The two numbers in the
47// function header specify how many total samples were accumulated in the
48// function (first number), and the total number of samples accumulated
49// in the prologue of the function (second number). This head sample
50// count provides an indicator of how frequently the function is invoked.
51//
52// There are three types of lines in the function body.
53//
54// * Sampled line represents the profile information of a source location.
55// * Callsite line represents the profile information of a callsite.
56// * Metadata line represents extra metadata of the function.
57//
58// Each sampled line may contain several items. Some are optional (marked
59// below):
60//
61// a. Source line offset. This number represents the line number
62// in the function where the sample was collected. The line number is
63// always relative to the line where symbol of the function is
64// defined. So, if the function has its header at line 280, the offset
65// 13 is at line 293 in the file.
66//
67// Note that this offset should never be a negative number. This could
68// happen in cases like macros. The debug machinery will register the
69// line number at the point of macro expansion. So, if the macro was
70// expanded in a line before the start of the function, the profile
71// converter should emit a 0 as the offset (this means that the optimizers
72// will not be able to associate a meaningful weight to the instructions
73// in the macro).
74//
75// b. [OPTIONAL] Discriminator. This is used if the sampled program
76// was compiled with DWARF discriminator support
77// (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
78// DWARF discriminators are unsigned integer values that allow the
79// compiler to distinguish between multiple execution paths on the
80// same source line location.
81//
82// For example, consider the line of code ``if (cond) foo(); else bar();``.
83// If the predicate ``cond`` is true 80% of the time, then the edge
84// into function ``foo`` should be considered to be taken most of the
85// time. But both calls to ``foo`` and ``bar`` are at the same source
86// line, so a sample count at that line is not sufficient. The
87// compiler needs to know which part of that line is taken more
88// frequently.
89//
90// This is what discriminators provide. In this case, the calls to
91// ``foo`` and ``bar`` will be at the same line, but will have
92// different discriminator values. This allows the compiler to correctly
93// set edge weights into ``foo`` and ``bar``.
94//
95// c. Number of samples. This is an integer quantity representing the
96// number of samples collected by the profiler at this source
97// location.
98//
99// d. [OPTIONAL] Potential call targets and samples. If present, this
100// line contains a call instruction. This models both direct and
101// number of samples. For example,
102//
103// 130: 7 foo:3 bar:2 baz:7
104//
105// The above means that at relative line offset 130 there is a call
106// instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
107// with ``baz()`` being the relatively more frequently called target.
108//
109// Each callsite line may contain several items. Some are optional.
110//
111// a. Source line offset. This number represents the line number of the
112// callsite that is inlined in the profiled binary.
113//
114// b. [OPTIONAL] Discriminator. Same as the discriminator for sampled line.
115//
116// c. Number of samples. This is an integer quantity representing the
117// total number of samples collected for the inlined instance at this
118// callsite
119//
120// Metadata line can occur in lines with one indent only, containing extra
121// information for the top-level function. Furthermore, metadata can only
122// occur after all the body samples and callsite samples.
123// Each metadata line may contain a particular type of metadata, marked by
124// the starting characters annotated with !. We process each metadata line
125// independently, hence each metadata line has to form an independent piece
126// of information that does not require cross-line reference.
127// We support the following types of metadata:
128//
129// a. CFG Checksum (a.k.a. function hash):
130// !CFGChecksum: 12345
131// b. CFG Checksum (see ContextAttributeMask):
132// !Atribute: 1
133//
134//
135// Binary format
136// -------------
137//
138// This is a more compact encoding. Numbers are encoded as ULEB128 values
139// and all strings are encoded in a name table. The file is organized in
140// the following sections:
141//
142// MAGIC (uint64_t)
143// File identifier computed by function SPMagic() (0x5350524f463432ff)
144//
145// VERSION (uint32_t)
146// File format version number computed by SPVersion()
147//
148// SUMMARY
149// TOTAL_COUNT (uint64_t)
150// Total number of samples in the profile.
151// MAX_COUNT (uint64_t)
152// Maximum value of samples on a line.
153// MAX_FUNCTION_COUNT (uint64_t)
154// Maximum number of samples at function entry (head samples).
155// NUM_COUNTS (uint64_t)
156// Number of lines with samples.
157// NUM_FUNCTIONS (uint64_t)
158// Number of functions with samples.
159// NUM_DETAILED_SUMMARY_ENTRIES (size_t)
160// Number of entries in detailed summary
161// DETAILED_SUMMARY
162// A list of detailed summary entry. Each entry consists of
163// CUTOFF (uint32_t)
164// Required percentile of total sample count expressed as a fraction
165// multiplied by 1000000.
166// MIN_COUNT (uint64_t)
167// The minimum number of samples required to reach the target
168// CUTOFF.
169// NUM_COUNTS (uint64_t)
170// Number of samples to get to the desrired percentile.
171//
172// NAME TABLE
173// SIZE (uint64_t)
174// Number of entries in the name table.
175// NAMES
176// A NUL-separated list of SIZE strings.
177//
178// FUNCTION BODY (one for each uninlined function body present in the profile)
179// HEAD_SAMPLES (uint64_t) [only for top-level functions]
180// Total number of samples collected at the head (prologue) of the
181// function.
182// NOTE: This field should only be present for top-level functions
183// (i.e., not inlined into any caller). Inlined function calls
184// have no prologue, so they don't need this.
185// NAME_IDX (uint64_t)
186// Index into the name table indicating the function name.
187// SAMPLES (uint64_t)
188// Total number of samples collected in this function.
189// NRECS (uint32_t)
190// Total number of sampling records this function's profile.
191// BODY RECORDS
192// A list of NRECS entries. Each entry contains:
193// OFFSET (uint32_t)
194// Line offset from the start of the function.
195// DISCRIMINATOR (uint32_t)
196// Discriminator value (see description of discriminators
197// in the text format documentation above).
198// SAMPLES (uint64_t)
199// Number of samples collected at this location.
200// NUM_CALLS (uint32_t)
201// Number of non-inlined function calls made at this location. In the
202// case of direct calls, this number will always be 1. For indirect
203// calls (virtual functions and function pointers) this will
204// represent all the actual functions called at runtime.
205// CALL_TARGETS
206// A list of NUM_CALLS entries for each called function:
207// NAME_IDX (uint64_t)
208// Index into the name table with the callee name.
209// SAMPLES (uint64_t)
210// Number of samples collected at the call site.
211// NUM_INLINED_FUNCTIONS (uint32_t)
212// Number of callees inlined into this function.
213// INLINED FUNCTION RECORDS
214// A list of NUM_INLINED_FUNCTIONS entries describing each of the inlined
215// callees.
216// OFFSET (uint32_t)
217// Line offset from the start of the function.
218// DISCRIMINATOR (uint32_t)
219// Discriminator value (see description of discriminators
220// in the text format documentation above).
221// FUNCTION BODY
222// A FUNCTION BODY entry describing the inlined function.
223//===----------------------------------------------------------------------===//
224
225#ifndef LLVM_PROFILEDATA_SAMPLEPROFREADER_H
226#define LLVM_PROFILEDATA_SAMPLEPROFREADER_H
227
228#include "llvm/ADT/Eytzinger.h"
229#include "llvm/ADT/STLExtras.h"
231#include "llvm/ADT/SmallVector.h"
232#include "llvm/ADT/StringRef.h"
233#include "llvm/ADT/StringSet.h"
235#include "llvm/IR/LLVMContext.h"
241#include "llvm/Support/Debug.h"
243#include "llvm/Support/ErrorOr.h"
246#include <array>
247#include <cstdint>
248#include <list>
249#include <memory>
250#include <optional>
251#include <string>
252#include <system_error>
253#include <vector>
254
255namespace llvm {
256
257class raw_ostream;
258class Twine;
259
260namespace vfs {
261class FileSystem;
262} // namespace vfs
263
264namespace sampleprof {
265
267
268/// SampleProfileReaderItaniumRemapper remaps the profile data from a
269/// sample profile data reader, by applying a provided set of equivalences
270/// between components of the symbol names in the profile.
272public:
273 SampleProfileReaderItaniumRemapper(std::unique_ptr<MemoryBuffer> B,
274 std::unique_ptr<SymbolRemappingReader> SRR,
276 : Buffer(std::move(B)), Remappings(std::move(SRR)), Reader(R) {
277 assert(Remappings && "Remappings cannot be nullptr");
278 }
279
280 /// Create a remapper from the given remapping file. The remapper will
281 /// be used for profile read in by Reader.
284 LLVMContext &C);
285
286 /// Create a remapper from the given Buffer. The remapper will
287 /// be used for profile read in by Reader.
289 create(std::unique_ptr<MemoryBuffer> &B, SampleProfileReader &Reader,
290 LLVMContext &C);
291
292 /// Apply remappings to the profile read by Reader.
294
295 bool hasApplied() { return RemappingApplied; }
296
297 /// Insert function name into remapper.
298 void insert(StringRef FunctionName) { Remappings->insert(FunctionName); }
299
300 /// Query whether there is equivalent in the remapper which has been
301 /// inserted.
302 bool exist(StringRef FunctionName) {
303 return Remappings->lookup(FunctionName);
304 }
305
306 /// Return the equivalent name in the profile for \p FunctionName if
307 /// it exists.
308 LLVM_ABI std::optional<StringRef> lookUpNameInProfile(StringRef FunctionName);
309
310private:
311 // The buffer holding the content read from remapping file.
312 std::unique_ptr<MemoryBuffer> Buffer;
313 std::unique_ptr<SymbolRemappingReader> Remappings;
314 // Map remapping key to the name in the profile. By looking up the
315 // key in the remapper, a given new name can be mapped to the
316 // cannonical name using the NameMap.
318 // The Reader the remapper is servicing.
319 SampleProfileReader &Reader;
320 // Indicate whether remapping has been applied to the profile read
321 // by Reader -- by calling applyRemapping.
322 bool RemappingApplied = false;
323};
324
325/// Sample-based profile reader.
326///
327/// Each profile contains sample counts for all the functions
328/// executed. Inside each function, statements are annotated with the
329/// collected samples on all the instructions associated with that
330/// statement.
331///
332/// For this to produce meaningful data, the program needs to be
333/// compiled with some debug information (at minimum, line numbers:
334/// -gline-tables-only). Otherwise, it will be impossible to match IR
335/// instructions to the line numbers collected by the profiler.
336///
337/// From the profile file, we are interested in collecting the
338/// following information:
339///
340/// * A list of functions included in the profile (mangled names).
341///
342/// * For each function F:
343/// 1. The total number of samples collected in F.
344///
345/// 2. The samples collected at each line in F. To provide some
346/// protection against source code shuffling, line numbers should
347/// be relative to the start of the function.
348///
349/// The reader supports two file formats: text and binary. The text format
350/// is useful for debugging and testing, while the binary format is more
351/// compact and I/O efficient. They can both be used interchangeably.
352
353/// Manages the sample profile name table, supporting both an eagerly loaded
354/// std::vector of FunctionId objects and lazy-loaded MD5 hashes read directly
355/// from the memory-mapped buffer. It enforces the exclusivity of these
356/// two formats and provides a unified read-only container interface.
358public:
360 : public llvm::iterator_facade_base<iterator, std::input_iterator_tag,
361 FunctionId, std::ptrdiff_t,
362 const FunctionId *, FunctionId> {
363 public:
364 iterator() = default;
365 iterator(const SampleProfileNameTable *Table, size_t Idx)
366 : Table(Table), Idx(Idx) {}
367
368 bool operator==(const iterator &RHS) const {
369 return Table == RHS.Table && Idx == RHS.Idx;
370 }
371
373 ++Idx;
374 return *this;
375 }
376
378 assert(Table && Idx < Table->size() &&
379 "Dereferencing invalid or out-of-bounds iterator");
380 return (*Table)[Idx];
381 }
382
383 private:
384 const SampleProfileNameTable *Table = nullptr;
385 size_t Idx = 0;
386 };
387
389
395 virtual ~SampleProfileNameTable() = default;
396
397 virtual size_t size() const = 0;
398 bool empty() const { return size() == 0; }
399 virtual FunctionId operator[](size_t Idx) const = 0;
400 virtual bool contains(StringRef Key) const {
401 return contains(FunctionId(Key).getHashCode());
402 }
403 virtual bool contains(uint64_t GUID) const {
404 return getOrCreateSet(GUIDSet, *this, GetFunctionIdHash).contains(GUID);
405 }
406
407 iterator begin() const { return iterator(this, 0); }
408 iterator end() const { return iterator(this, size()); }
409
410protected:
411 mutable std::optional<DenseSet<uint64_t>> GUIDSet;
412
413 static constexpr auto GetFunctionIdHash = [](FunctionId F) {
414 return F.getHashCode();
415 };
416 static constexpr auto GetFunctionIdString = [](FunctionId F) {
417 return F.stringRef();
418 };
419
420 template <typename SetT, typename RangeT, typename ProjT = llvm::identity>
421 static const SetT &getOrCreateSet(std::optional<SetT> &Set,
422 const RangeT &Range, ProjT Proj = ProjT()) {
423 if (!Set) {
424 Set.emplace();
425 Set->reserve(Range.size());
426 for (const auto &Item : Range)
427 Set->insert(Proj(Item));
428 }
429 return *Set;
430 }
431};
432
434 const uint8_t *Start = nullptr;
435 size_t Size = 0;
436
437public:
438 LazySampleProfileNameTable(const uint8_t *Start, size_t Size)
439 : Start(Start), Size(Size) {}
440
441 size_t size() const override { return Size; }
442
443 FunctionId operator[](size_t Idx) const override {
444 assert(Idx < Size && "Index out of bounds");
445 using namespace support;
447 Start + Idx * sizeof(uint64_t), endianness::little));
448 }
449
450 bool contains(uint64_t GUID) const override {
452 reinterpret_cast<const support::ulittle64_t *>(Start), Size);
453 return getOrCreateSet(GUIDSet, Table).contains(GUID);
454 }
455};
456
458 std::vector<FunctionId> Vec;
459 mutable std::optional<DenseSet<StringRef>> NameSet;
460
461public:
462 explicit StringSampleProfileNameTable(std::vector<FunctionId> &&Vec)
463 : Vec(std::move(Vec)) {}
464 explicit StringSampleProfileNameTable(const std::vector<FunctionId> &Vec)
465 : Vec(Vec) {}
466
467 size_t size() const override { return Vec.size(); }
468
469 FunctionId operator[](size_t Idx) const override {
470 assert(Idx < Vec.size() && "Index out of bounds");
471 return Vec[Idx];
472 }
473
474 bool contains(StringRef Key) const override {
475 return getOrCreateSet(NameSet, Vec, GetFunctionIdString).contains(Key);
476 }
477};
478
480 std::vector<FunctionId> Vec;
481
482public:
483 explicit MD5SampleProfileNameTable(std::vector<FunctionId> &&Vec)
484 : Vec(std::move(Vec)) {}
485 explicit MD5SampleProfileNameTable(const std::vector<FunctionId> &Vec)
486 : Vec(Vec) {}
487
488 size_t size() const override { return Vec.size(); }
489
490 FunctionId operator[](size_t Idx) const override {
491 assert(Idx < Vec.size() && "Index out of bounds");
492 return Vec[Idx];
493 }
494};
495
498 std::array<EytzingerTableSpan<support::ulittle64_t>,
499 static_cast<size_t>(EytzingerSpan::NumSpans)>
500 Spans;
501
502public:
504 size_t NumCS, size_t NumFlat,
505 size_t NumInlinees)
506 : Array(Data, NumCS + NumFlat + NumInlinees),
507 Spans{{{Data, NumCS},
508 {Data + NumCS, NumFlat},
509 {Data + NumCS + NumFlat, NumInlinees}}} {}
510
511 size_t size() const override { return Array.size(); }
512
513 FunctionId operator[](size_t Idx) const override {
514 return FunctionId(Array[Idx]);
515 }
516
517 bool contains(uint64_t GUID) const override {
518 return llvm::any_of(Spans,
519 [&](const auto &Span) { return Span.contains(GUID); });
520 }
521};
522
524public:
525 SampleProfileReader(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
527 : Profiles(), Ctx(C), Buffer(std::move(B)), Format(Format) {}
528
529 virtual ~SampleProfileReader() = default;
530
531 /// Read and validate the file header.
532 virtual std::error_code readHeader() = 0;
533
534 /// Set the bits for FS discriminators. Parameter Pass specify the sequence
535 /// number, Pass == i is for the i-th round of adding FS discriminators.
536 /// Pass == 0 is for using base discriminators.
540
541 /// Get the bitmask the discriminators: For FS profiles, return the bit
542 /// mask for this pass. For non FS profiles, return (unsigned) -1.
544 if (!ProfileIsFS)
545 return 0xFFFFFFFF;
546 assert((MaskedBitFrom != 0) && "MaskedBitFrom is not set properly");
547 return getN1Bits(MaskedBitFrom);
548 }
549
550 /// The interface to read sample profiles from the associated file.
551 std::error_code read() {
552 if (std::error_code EC = readImpl())
553 return EC;
554 if (Remapper)
555 Remapper->applyRemapping(Ctx);
558 }
559
560 /// Read sample profiles for the given functions.
561 std::error_code read(const DenseSet<StringRef> &FuncsToUse) {
563 for (StringRef F : FuncsToUse)
564 if (Profiles.find(FunctionId(F)) == Profiles.end())
565 S.insert(F);
566 if (std::error_code EC = read(S, Profiles))
567 return EC;
569 }
570
571 /// The implementaion to read sample profiles from the associated file.
572 virtual std::error_code readImpl() = 0;
573
574 /// Print the profile for \p FunctionSamples on stream \p OS.
576 raw_ostream &OS = dbgs());
577
578 /// Collect functions with definitions in Module M. For reader which
579 /// support loading function profiles on demand, return true when the
580 /// reader has been given a module. Always return false for reader
581 /// which doesn't support loading function profiles on demand.
582 virtual bool collectFuncsFromModule() { return false; }
583
584 /// Print all the profiles on stream \p OS.
585 LLVM_ABI void dump(raw_ostream &OS = dbgs());
586
587 /// Print all the profiles on stream \p OS in the JSON format.
588 LLVM_ABI void dumpJson(raw_ostream &OS = dbgs());
589
590 /// Return the format version of the profile. For tests only.
592
593 /// Return the samples collected for function \p F.
595 // The function name may have been updated by adding suffix. Call
596 // a helper to (optionally) strip off suffixes so that we can
597 // match against the original function name in the profile.
599 return getSamplesFor(CanonName);
600 }
601
602 /// Return the samples collected for function \p F.
604 auto It = Profiles.find(FunctionId(Fname));
605 if (It != Profiles.end())
606 return &It->second;
607
609 auto R = FuncNameToProfNameMap->find(FunctionId(Fname));
610 if (R != FuncNameToProfNameMap->end()) {
611 Fname = R->second.stringRef();
612 auto It = Profiles.find(FunctionId(Fname));
613 if (It != Profiles.end())
614 return &It->second;
615 }
616 }
617
618 if (Remapper) {
619 if (auto NameInProfile = Remapper->lookUpNameInProfile(Fname)) {
620 auto It = Profiles.find(FunctionId(*NameInProfile));
621 if (It != Profiles.end())
622 return &It->second;
623 }
624 }
625 return nullptr;
626 }
627
628 /// Return all the profiles.
630
631 /// Report a parse error message.
632 void reportError(int64_t LineNumber, const Twine &Msg) const {
633 Ctx.diagnose(DiagnosticInfoSampleProfile(Buffer->getBufferIdentifier(),
634 LineNumber, Msg));
635 }
636
637 /// Create a sample profile reader appropriate to the file format.
638 /// Create a remapper underlying if RemapFilename is not empty.
639 /// Parameter P specifies the FSDiscriminatorPass.
643 StringRef RemapFilename = "");
644
645 /// Create a sample profile reader from the supplied memory buffer.
646 /// Create a remapper underlying if RemapFilename is not empty.
647 /// Parameter P specifies the FSDiscriminatorPass.
649 create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C, vfs::FileSystem &FS,
651 StringRef RemapFilename = "");
652
653 /// Return the profile summary.
654 ProfileSummary &getSummary() const { return *Summary; }
655
656 MemoryBuffer *getBuffer() const { return Buffer.get(); }
657
658 /// \brief Return the profile format.
660
661 /// Whether input profile is based on pseudo probes.
663
664 /// Whether input profile is fully context-sensitive.
665 bool profileIsCS() const { return ProfileIsCS; }
666
667 /// Whether input profile contains ShouldBeInlined contexts.
669
670 /// Whether input profile is flow-sensitive.
671 bool profileIsFS() const { return ProfileIsFS; }
672
673 virtual std::unique_ptr<ProfileSymbolList> getProfileSymbolList() {
674 return nullptr;
675 };
676
677 /// It includes all the names that have samples either in outline instance
678 /// or inline instance.
684 virtual bool dumpSectionInfo(raw_ostream &OS = dbgs()) { return false; };
685 virtual bool contains(StringRef Key) const { return false; }
686 virtual bool contains(uint64_t GUID) const { return false; }
687
688 /// Return whether names in the profile are all MD5 numbers.
689 bool useMD5() const { return ProfileIsMD5; }
690
691 /// Force the profile to use MD5 in Sample contexts, even if function names
692 /// are present.
693 virtual void setProfileUseMD5() { ProfileIsMD5 = true; }
694
695 /// Don't read profile without context if the flag is set.
696 void setSkipFlatProf(bool Skip) { SkipFlatProf = Skip; }
697
698 /// Return whether any name in the profile contains ".__uniq." suffix.
699 virtual bool hasUniqSuffix() { return false; }
700
702
703 void setModule(const Module *Mod) { M = Mod; }
704
709
710protected:
711 /// Map every function to its associated profile.
712 ///
713 /// The profile of every function executed at runtime is collected
714 /// in the structure FunctionSamples. This maps function objects
715 /// to their corresponding profiles.
717
718 /// LLVM context used to emit diagnostics.
720
721 /// Memory buffer holding the profile file.
722 std::unique_ptr<MemoryBuffer> Buffer;
723
724 /// Profile summary information.
725 std::unique_ptr<ProfileSummary> Summary;
726
727 /// Take ownership of the summary of this reader.
728 static std::unique_ptr<ProfileSummary>
730 return std::move(Reader.Summary);
731 }
732
733 /// Compute summary for this profile.
735
736 /// Read sample profiles for the given functions and write them to the given
737 /// profile map. Currently it's only used for extended binary format to load
738 /// the profiles on-demand.
739 virtual std::error_code read(const DenseSet<StringRef> &FuncsToUse,
742 }
743
744 std::unique_ptr<SampleProfileReaderItaniumRemapper> Remapper;
745
746 // A map pointer to the FuncNameToProfNameMap in SampleProfileLoader,
747 // which maps the function name to the matched profile name. This is used
748 // for sample loader to look up profile using the new name.
750 nullptr;
751
752 // A map from a function's context hash to its meta data section range, used
753 // for on-demand read function profile metadata.
756
757 std::pair<const uint8_t *, const uint8_t *> ProfileSecRange;
758
759 /// Whether the profile has attribute metadata.
761
762 /// \brief Whether samples are collected based on pseudo probes.
764
765 /// Whether function profiles are context-sensitive flat profiles.
766 bool ProfileIsCS = false;
767
768 /// Whether function profile contains ShouldBeInlined contexts.
770
771 /// Number of context-sensitive profiles.
773
774 /// Whether the function profiles use FS discriminators.
775 bool ProfileIsFS = false;
776
777 /// Format version of the profile.
779
780 /// If true, the profile has vtable profiles and reader should decode them
781 /// to parse profiles correctly.
782 bool ReadVTableProf = false;
783
784 /// \brief The format of sample.
786
787 /// \brief The current module being compiled if SampleProfileReader
788 /// is used by compiler. If SampleProfileReader is used by other
789 /// tools which are not compiler, M is usually nullptr.
790 const Module *M = nullptr;
791
792 /// Zero out the discriminator bits higher than bit MaskedBitFrom (0 based).
793 /// The default is to keep all the bits.
795
796 /// Whether the profile uses MD5 for Sample Contexts and function names. This
797 /// can be one-way overriden by the user to force use MD5.
798 bool ProfileIsMD5 = false;
799
800 /// If SkipFlatProf is true, skip functions marked with !Flat in text mode or
801 /// sections with SecFlagFlat flag in ExtBinary mode.
802 bool SkipFlatProf = false;
803};
804
806public:
807 SampleProfileReaderText(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
809
810 /// Read and validate the file header.
811 std::error_code readHeader() override { return sampleprof_error::success; }
812
813 /// Read sample profiles from the associated file.
814 std::error_code readImpl() override;
815
816 /// Return true if \p Buffer is in the format supported by this class.
817 static bool hasFormat(const MemoryBuffer &Buffer);
818
819 /// Text format sample profile does not support MD5 for now.
820 void setProfileUseMD5() override {}
821
822private:
823 /// CSNameTable is used to save full context vectors. This serves as an
824 /// underlying immutable buffer for all clients.
825 std::list<SampleContextFrameVector> CSNameTable;
826};
827
829public:
833
834 /// Read and validate the file header.
835 std::error_code readHeader() override;
836
837 /// Read sample profiles from the associated file.
838 std::error_code readImpl() override;
839
840 /// It includes all the names that have samples either in outline instance
841 /// or inline instance.
843 getNameTable() const override {
844 if (!NameTable)
847 return {NameTable->begin(), NameTable->end()};
848 }
849
850 bool contains(StringRef Key) const override {
851 assert(NameTable && "NameTable should be populated before querying");
852 return NameTable->contains(Key);
853 }
854
855 bool contains(uint64_t GUID) const override {
856 assert(NameTable && "NameTable should be populated before querying");
857 return NameTable->contains(GUID);
858 }
859
860protected:
861 /// Read a numeric value of type T from the profile.
862 ///
863 /// If an error occurs during decoding, a diagnostic message is emitted and
864 /// EC is set.
865 ///
866 /// \returns the read value.
867 template <typename T> ErrorOr<T> readNumber();
868
869 /// Read a numeric value of type T from the profile. The value is saved
870 /// without encoded.
871 template <typename T> ErrorOr<T> readUnencodedNumber();
872
873 /// Read a string from the profile.
874 ///
875 /// If an error occurs during decoding, a diagnostic message is emitted and
876 /// EC is set.
877 ///
878 /// \returns the read value.
880
881 /// Read the string index and check whether it overflows the table.
882 template <typename T> inline ErrorOr<size_t> readStringIndex(T &Table);
883
884 /// Read the next function profile instance.
885 std::error_code readFuncProfile(const uint8_t *Start);
886 std::error_code readFuncProfile(const uint8_t *Start,
887 SampleProfileMap &Profiles);
888
889 /// Read the contents of the given profile instance.
890 std::error_code readProfile(FunctionSamples &FProfile);
891
892 /// Read the contents of Magic number and Version number.
893 std::error_code readMagicIdent();
894
895 /// Read profile summary.
896 std::error_code readSummary();
897
898 /// Read the whole name table.
899 std::error_code readNameTable();
900
901 /// Read a string indirectly via the name table. Optionally return the index.
902 ErrorOr<FunctionId> readStringFromTable(size_t *RetIdx = nullptr);
903
904 /// Read a context indirectly via the CSNameTable. Optionally return the
905 /// index.
906 ErrorOr<SampleContextFrames> readContextFromTable(size_t *RetIdx = nullptr);
907
908 /// Read a context indirectly via the CSNameTable if the profile has context,
909 /// otherwise same as readStringFromTable, also return its hash value.
910 ErrorOr<std::pair<SampleContext, uint64_t>> readSampleContextFromTable();
911
912 /// Read all virtual functions' vtable access counts for \p FProfile.
913 std::error_code readCallsiteVTableProf(FunctionSamples &FProfile);
914
915 /// Read bytes from the input buffer pointed by `Data` and decode them into
916 /// \p M. `Data` will be advanced to the end of the read bytes when this
917 /// function returns. Returns error if any.
918 std::error_code readVTableTypeCountMap(TypeCountMap &M);
919
920 /// Points to the current location in the buffer.
921 const uint8_t *Data = nullptr;
922
923 /// Points to the end of the buffer.
924 const uint8_t *End = nullptr;
925
926 /// Function name table.
927 std::unique_ptr<SampleProfileNameTable> NameTable;
928
929 /// CSNameTable is used to save full context vectors. It is the backing buffer
930 /// for SampleContextFrames.
931 std::vector<SampleContextFrameVector> CSNameTable;
932
933 /// Table to cache MD5 values of sample contexts corresponding to
934 /// readSampleContextFromTable(), used to index into Profiles or
935 /// FuncOffsetTable.
936 std::vector<uint64_t> MD5SampleContextTable;
937
938 /// The starting address of the table of MD5 values of sample contexts. For
939 /// fixed length MD5 non-CS profile it is same as MD5NameMemStart because
940 /// hashes of non-CS contexts are already in the profile. Otherwise it points
941 /// to the start of MD5SampleContextTable.
943
944private:
945 std::error_code readSummaryEntry(std::vector<ProfileSummaryEntry> &Entries);
946 virtual std::error_code verifySPMagic(uint64_t Magic) = 0;
947};
948
950private:
951 std::error_code verifySPMagic(uint64_t Magic) override;
952
953public:
957
958 /// \brief Return true if \p Buffer is in the format supported by this class.
959 static bool hasFormat(const MemoryBuffer &Buffer);
960};
961
962/// Trait class for reading the on-disk function offset hash table mapping
963/// function name GUIDs to their offsets in the SecLBRProfile section.
965public:
968 using data_type = uint32_t; // Offset
974
976 return static_cast<hash_value_type>(Key);
977 }
978
980 return LHS == RHS;
981 }
982
985
986 static std::pair<offset_type, offset_type>
987 ReadKeyDataLength(const unsigned char *&D) {
988 // Implicit lengths: do NOT read or advance pointer D.
989 return {sizeof(key_type), sizeof(data_type)};
990 }
991
992 static key_type ReadKey(const unsigned char *D, offset_type Len) {
993 assert(Len == sizeof(key_type) && "Key length mismatch");
995 }
996
997 static data_type ReadData(key_type_ref K, const unsigned char *D,
998 offset_type Len) {
999 assert(Len == sizeof(data_type) && "Data length mismatch");
1001 }
1002};
1003
1004/// Tags to select the initialization mode of SampleProfileFuncOffsetTable.
1006struct OnDiskModeT {};
1007inline constexpr InMemoryModeT InMemoryMode{};
1008inline constexpr OnDiskModeT OnDiskMode{};
1009
1010/// A unified wrapper representing the function offset table.
1011///
1012/// This class abstracts away the physical representation of the offset table,
1013/// which can either be:
1014///
1015/// - An llvm::DenseMap mapping function GUIDs (or context hashes) to their
1016/// profile offsets, populated when reading the array of offsets in
1017/// context-sensitive (CS) profiles or version 103 profiles.
1018///
1019/// - An OnDiskIterableChainedHashTable providing the same mapping directly from
1020/// the file in (non-context-sensitive) version 104 profiles.
1021///
1022/// It exposes a single, type-agnostic lookup interface, shielding the reader
1023/// from the underlying container types. To prevent hybrid-state corruption, the
1024/// table's mode is locked at construction time, and assertions prevent
1025/// modification in on-disk mode.
1027public:
1030
1038
1040 size_t InitialCapacity = 0) {
1041 InMemoryTable.reserve(InitialCapacity);
1042 }
1043
1044 /// Insert a function GUID and its profile offset into the in-memory map.
1045 /// Enforces that the on-disk table must not have been set first.
1047 assert(!OnDiskTable &&
1048 "Cannot insert in-memory elements after on-disk table has been set");
1049 InMemoryTable[GUID] = Offset;
1050 }
1051
1052 /// Instantiate the on-disk chained hash table using raw stream pointers.
1054 const uint8_t *Payload, const uint8_t *Base) {
1055 OnDiskTable.reset(OnDiskTableType::Create(Buckets, Payload, Base));
1056 }
1057
1058 /// Query the offset table for the profile offset associated with the given
1059 /// GUID. Returns the offset if found, or std::nullopt if the key is missing.
1060 std::optional<uint64_t> lookup(uint64_t GUID) const {
1061 if (OnDiskTable) {
1062 auto Iter = OnDiskTable->find(GUID);
1063 if (Iter != OnDiskTable->end())
1064 return *Iter;
1065 } else {
1066 auto Iter = InMemoryTable.find(GUID);
1067 if (Iter != InMemoryTable.end())
1068 return Iter->second;
1069 }
1070 return std::nullopt;
1071 }
1072
1073private:
1075 std::unique_ptr<OnDiskTableType> OnDiskTable;
1076};
1077
1078/// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase defines
1079/// the basic structure of the extensible binary format.
1080/// The format is organized in sections except the magic and version number
1081/// at the beginning. There is a section table before all the sections, and
1082/// each entry in the table describes the entry type, start, size and
1083/// attributes. The format in each section is defined by the section itself.
1084///
1085/// It is easy to add a new section while maintaining the backward
1086/// compatibility of the profile. Nothing extra needs to be done. If we want
1087/// to extend an existing section, like add cache misses information in
1088/// addition to the sample count in the profile body, we can add a new section
1089/// with the extension and retire the existing section, and we could choose
1090/// to keep the parser of the old section if we want the reader to be able
1091/// to read both new and old format profile.
1092///
1093/// SampleProfileReaderExtBinary/SampleProfileWriterExtBinary define the
1094/// commonly used sections of a profile in extensible binary format. It is
1095/// possible to define other types of profile inherited from
1096/// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase.
1098 : public SampleProfileReaderBinary {
1099private:
1100 std::error_code decompressSection(const uint8_t *SecStart,
1101 const uint64_t SecSize,
1102 const uint8_t *&DecompressBuf,
1103 uint64_t &DecompressBufSize);
1104
1105 BumpPtrAllocator Allocator;
1106
1107protected:
1108 std::vector<SecHdrTableEntry> SecHdrTable;
1109 std::error_code readSecHdrTableEntry(uint64_t Idx);
1110 std::error_code readSecHdrTable();
1111
1113 std::error_code readFuncMetadata();
1114 std::error_code readFuncMetadata(FunctionSamples *FProfile);
1115 std::error_code readFuncOffsetTable();
1116 std::error_code readFuncProfiles();
1117 std::error_code readFuncProfiles(const DenseSet<StringRef> &FuncsToUse,
1119 std::error_code readNameTableSec(bool IsMD5, bool FixedLengthMD5,
1120 bool IsEytzinger = false);
1121 std::error_code readNameTableSecEytzinger(bool IsMD5, bool FixedLengthMD5);
1122 std::error_code readNameTableSecLegacy(bool IsMD5, bool FixedLengthMD5);
1123 std::error_code readCSNameTableSec();
1124 std::error_code readProfileSymbolList(bool IsMD5);
1125 std::error_code readStringBasedProfileSymbolList();
1126 std::error_code readMD5ProfileSymbolList();
1127
1128 std::error_code readHeader() override;
1129 std::error_code verifySPMagic(uint64_t Magic) override = 0;
1130 virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size,
1131 const SecHdrTableEntry &Entry);
1132 // placeholder for subclasses to dispatch their own section readers.
1133 virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry) = 0;
1134
1135 /// Determine which container readFuncOffsetTable() should populate, the list
1136 /// FuncOffsetList or the map FuncOffsetTable.
1137 bool useFuncOffsetList() const;
1138
1139 std::unique_ptr<ProfileSymbolList> ProfSymList;
1140
1141 /// The table mapping from a function context's MD5 to the offset of its
1142 /// FunctionSample towards file start.
1143 /// At most one of FuncOffsetTable and FuncOffsetList is populated.
1144 std::optional<SampleProfileFuncOffsetTable> FuncOffsetTable;
1145
1146 /// The list version of FuncOffsetTable. This is used if every entry is
1147 /// being accessed.
1148 std::vector<std::pair<SampleContext, uint64_t>> FuncOffsetList;
1149
1150 /// The set containing the functions to use when compiling a module.
1152
1153public:
1159
1160 /// Read sample profiles in extensible format from the associated file.
1161 std::error_code readImpl() override;
1162
1163 /// Get the total size of all \p Type sections.
1164 uint64_t getSectionSize(SecType Type);
1165 /// Get the total size of header and all sections.
1166 uint64_t getFileSize();
1167 bool dumpSectionInfo(raw_ostream &OS = dbgs()) override;
1168
1169 /// Collect functions with definitions in Module M. Return true if
1170 /// the reader has been given a module.
1171 bool collectFuncsFromModule() override;
1172
1173 std::unique_ptr<ProfileSymbolList> getProfileSymbolList() override {
1174 return std::move(ProfSymList);
1175 };
1176
1177private:
1178 /// Read the profiles on-demand for the given functions. This is used after
1179 /// stale call graph matching finds new functions whose profiles aren't loaded
1180 /// at the beginning and we need to loaded the profiles explicitly for
1181 /// potential matching.
1182 std::error_code read(const DenseSet<StringRef> &FuncsToUse,
1183 SampleProfileMap &Profiles) override;
1184};
1185
1188private:
1189 std::error_code verifySPMagic(uint64_t Magic) override;
1190 std::error_code readCustomSection(const SecHdrTableEntry &Entry) override {
1191 // Update the data reader pointer to the end of the section.
1192 Data = End;
1194 };
1195
1196public:
1200
1201 /// \brief Return true if \p Buffer is in the format supported by this class.
1202 static bool hasFormat(const MemoryBuffer &Buffer);
1203};
1204
1206
1207// Supported histogram types in GCC. Currently, we only need support for
1208// call target histograms.
1219
1221public:
1222 SampleProfileReaderGCC(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
1224 GcovBuffer(Buffer.get()) {}
1225
1226 /// Read and validate the file header.
1227 std::error_code readHeader() override;
1228
1229 /// Read sample profiles from the associated file.
1230 std::error_code readImpl() override;
1231
1232 /// Return true if \p Buffer is in the format supported by this class.
1233 static bool hasFormat(const MemoryBuffer &Buffer);
1234
1235protected:
1236 std::error_code readNameTable();
1237 std::error_code readOneFunctionProfile(const InlineCallStack &InlineStack,
1238 bool Update, uint32_t Offset);
1239 std::error_code readFunctionProfiles();
1240 std::error_code skipNextWord();
1241 template <typename T> ErrorOr<T> readNumber();
1243
1244 /// Read the section tag and check that it's the same as \p Expected.
1245 std::error_code readSectionTag(uint32_t Expected);
1246
1247 /// GCOV buffer containing the profile.
1249
1250 /// Function names in this profile.
1251 std::vector<std::string> Names;
1252
1253 /// GCOV tags used to separate sections in the profile file.
1254 static const uint32_t GCOVTagAFDOFileNames = 0xaa000000;
1255 static const uint32_t GCOVTagAFDOFunction = 0xac000000;
1256};
1257
1258} // end namespace sampleprof
1259
1260} // end namespace llvm
1261
1262#endif // LLVM_PROFILEDATA_SAMPLEPROFREADER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
Provides ErrorOr<T> smart pointer.
This file defines the EytzingerTableSpan class, a non-owning view of a buffer formatted as a complete...
#define F(x, y, z)
Definition MD5.cpp:54
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static Error readString(StringRef Buffer, const char *&Src, size_t MaxSize, StringRef &Val, Twine Desc)
Read a null-terminated string at the position Src from Buffer, with maximum byte size of MaxSize (inc...
static constexpr StringLiteral Filename
Defines facilities for reading and writing on-disk hash tables.
#define P(N)
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
This file contains library features backported from future STL versions.
This file defines the SmallVector class.
StringSet - A set-like wrapper for the StringMap.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Diagnostic information for the sample profiler.
Represents either an error or a value T.
Definition ErrorOr.h:56
Tagged union holding either a T or a Error.
Definition Error.h:485
GCOVBuffer - A wrapper around MemoryBuffer to provide GCOV specific read operations.
Definition GCOV.h:74
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This interface provides simple read-only access to a block of memory, and provides simple methods for...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Provides lookup and iteration over an on disk hash table.
static OnDiskIterableChainedHashTable * Create(const unsigned char *Buckets, const unsigned char *const Payload, const unsigned char *const Base, const FuncOffsetHashTableInfo &InfoObj=FuncOffsetHashTableInfo())
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
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
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
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
FunctionId operator[](size_t Idx) const override
EytzingerSampleProfileNameTable(const support::ulittle64_t *Data, size_t NumCS, size_t NumFlat, size_t NumInlinees)
bool contains(uint64_t GUID) const override
Trait class for reading the on-disk function offset hash table mapping function name GUIDs to their o...
static key_type GetInternalKey(key_type_ref Key)
static std::pair< offset_type, offset_type > ReadKeyDataLength(const unsigned char *&D)
static external_key_type GetExternalKey(internal_key_type Key)
static bool EqualKey(key_type_ref LHS, key_type_ref RHS)
static hash_value_type ComputeHash(key_type_ref Key)
static key_type ReadKey(const unsigned char *D, offset_type Len)
static data_type ReadData(key_type_ref K, const unsigned char *D, offset_type Len)
This class represents a function that is read from a sample profile.
Definition FunctionId.h:36
Representation of the samples collected for a function.
Definition SampleProf.h:816
static LLVM_ABI std::atomic< bool > UseMD5
Whether the profile uses MD5 to represent string.
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
This class is a wrapper to associative container MapT<KeyT, ValueT> using the hash value of the origi...
Definition HashKeyMap.h:52
LazySampleProfileNameTable(const uint8_t *Start, size_t Size)
FunctionId operator[](size_t Idx) const override
bool contains(uint64_t GUID) const override
FunctionId operator[](size_t Idx) const override
MD5SampleProfileNameTable(const std::vector< FunctionId > &Vec)
MD5SampleProfileNameTable(std::vector< FunctionId > &&Vec)
std::optional< uint64_t > lookup(uint64_t GUID) const
Query the offset table for the profile offset associated with the given GUID.
SampleProfileFuncOffsetTable & operator=(SampleProfileFuncOffsetTable &&)=delete
void insert(uint64_t GUID, uint64_t Offset)
Insert a function GUID and its profile offset into the in-memory map.
SampleProfileFuncOffsetTable(InMemoryModeT, size_t InitialCapacity=0)
llvm::OnDiskIterableChainedHashTable< FuncOffsetHashTableInfo > OnDiskTableType
SampleProfileFuncOffsetTable(const SampleProfileFuncOffsetTable &)=delete
SampleProfileFuncOffsetTable & operator=(const SampleProfileFuncOffsetTable &)=delete
SampleProfileFuncOffsetTable(OnDiskModeT, const uint8_t *Buckets, const uint8_t *Payload, const uint8_t *Base)
Instantiate the on-disk chained hash table using raw stream pointers.
SampleProfileFuncOffsetTable(SampleProfileFuncOffsetTable &&)=delete
This class provides operator overloads to the map container using MD5 as the key type,...
iterator(const SampleProfileNameTable *Table, size_t Idx)
SampleProfileNameTable(SampleProfileNameTable &&)=delete
SampleProfileNameTable(const SampleProfileNameTable &)=delete
static const SetT & getOrCreateSet(std::optional< SetT > &Set, const RangeT &Range, ProjT Proj=ProjT())
std::optional< DenseSet< uint64_t > > GUIDSet
virtual bool contains(StringRef Key) const
SampleProfileNameTable & operator=(const SampleProfileNameTable &)=delete
virtual FunctionId operator[](size_t Idx) const =0
virtual bool contains(uint64_t GUID) const
SampleProfileNameTable & operator=(SampleProfileNameTable &&)=delete
const uint8_t * Data
Points to the current location in the buffer.
std::unique_ptr< SampleProfileNameTable > NameTable
Function name table.
const uint64_t * MD5SampleContextStart
The starting address of the table of MD5 values of sample contexts.
bool contains(StringRef Key) const override
std::vector< SampleContextFrameVector > CSNameTable
CSNameTable is used to save full context vectors.
bool contains(uint64_t GUID) const override
SampleProfileReaderBinary(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_None)
std::vector< uint64_t > MD5SampleContextTable
Table to cache MD5 values of sample contexts corresponding to readSampleContextFromTable(),...
llvm::iterator_range< SampleProfileNameTable::iterator > getNameTable() const override
It includes all the names that have samples either in outline instance or inline instance.
const uint8_t * End
Points to the end of the buffer.
std::error_code readNameTableSecEytzinger(bool IsMD5, bool FixedLengthMD5)
virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry)=0
std::error_code readFuncMetadata(DenseSet< FunctionSamples * > &Profiles)
std::vector< std::pair< SampleContext, uint64_t > > FuncOffsetList
The list version of FuncOffsetTable.
DenseSet< StringRef > FuncsToUse
The set containing the functions to use when compiling a module.
std::unique_ptr< ProfileSymbolList > ProfSymList
std::optional< SampleProfileFuncOffsetTable > FuncOffsetTable
The table mapping from a function context's MD5 to the offset of its FunctionSample towards file star...
std::error_code readNameTableSec(bool IsMD5, bool FixedLengthMD5, bool IsEytzinger=false)
bool useFuncOffsetList() const
Determine which container readFuncOffsetTable() should populate, the list FuncOffsetList or the map F...
std::unique_ptr< ProfileSymbolList > getProfileSymbolList() override
virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry)
std::error_code verifySPMagic(uint64_t Magic) override=0
SampleProfileReaderExtBinaryBase(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format)
std::error_code readNameTableSecLegacy(bool IsMD5, bool FixedLengthMD5)
std::error_code readHeader() override
Read and validate the file header.
SampleProfileReaderExtBinary(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_Ext_Binary)
GCOVBuffer GcovBuffer
GCOV buffer containing the profile.
std::vector< std::string > Names
Function names in this profile.
SampleProfileReaderGCC(std::unique_ptr< MemoryBuffer > B, LLVMContext &C)
static const uint32_t GCOVTagAFDOFileNames
GCOV tags used to separate sections in the profile file.
SampleProfileReaderItaniumRemapper remaps the profile data from a sample profile data reader,...
bool exist(StringRef FunctionName)
Query whether there is equivalent in the remapper which has been inserted.
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReaderItaniumRemapper > > create(StringRef Filename, vfs::FileSystem &FS, SampleProfileReader &Reader, LLVMContext &C)
Create a remapper from the given remapping file.
LLVM_ABI void applyRemapping(LLVMContext &Ctx)
Apply remappings to the profile read by Reader.
SampleProfileReaderItaniumRemapper(std::unique_ptr< MemoryBuffer > B, std::unique_ptr< SymbolRemappingReader > SRR, SampleProfileReader &R)
void insert(StringRef FunctionName)
Insert function name into remapper.
LLVM_ABI std::optional< StringRef > lookUpNameInProfile(StringRef FunctionName)
Return the equivalent name in the profile for FunctionName if it exists.
SampleProfileReaderRawBinary(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_Binary)
SampleProfileReaderText(std::unique_ptr< MemoryBuffer > B, LLVMContext &C)
void setProfileUseMD5() override
Text format sample profile does not support MD5 for now.
std::error_code readHeader() override
Read and validate the file header.
uint32_t MaskedBitFrom
Zero out the discriminator bits higher than bit MaskedBitFrom (0 based).
std::pair< const uint8_t *, const uint8_t * > ProfileSecRange
bool ReadVTableProf
If true, the profile has vtable profiles and reader should decode them to parse profiles correctly.
bool ProfileIsPreInlined
Whether function profile contains ShouldBeInlined contexts.
DenseMap< uint64_t, std::pair< const uint8_t *, const uint8_t * > > FuncMetadataIndex
SampleProfileMap & getProfiles()
Return all the profiles.
uint32_t CSProfileCount
Number of context-sensitive profiles.
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReader > > create(StringRef Filename, LLVMContext &C, vfs::FileSystem &FS, FSDiscriminatorPass P=FSDiscriminatorPass::Base, StringRef RemapFilename="")
Create a sample profile reader appropriate to the file format.
bool profileIsProbeBased() const
Whether input profile is based on pseudo probes.
FunctionSamples * getSamplesFor(const Function &F)
Return the samples collected for function F.
LLVM_ABI void dump(raw_ostream &OS=dbgs())
Print all the profiles on stream OS.
bool useMD5() const
Return whether names in the profile are all MD5 numbers.
const Module * M
The current module being compiled if SampleProfileReader is used by compiler.
std::unique_ptr< MemoryBuffer > Buffer
Memory buffer holding the profile file.
std::unique_ptr< SampleProfileReaderItaniumRemapper > Remapper
bool ProfileHasAttribute
Whether the profile has attribute metadata.
void setFuncNameToProfNameMap(const HashKeyMap< DenseMap, FunctionId, FunctionId > &FPMap)
bool SkipFlatProf
If SkipFlatProf is true, skip functions marked with !Flat in text mode or sections with SecFlagFlat f...
bool profileIsPreInlined() const
Whether input profile contains ShouldBeInlined contexts.
std::error_code read()
The interface to read sample profiles from the associated file.
bool profileIsFS() const
Whether input profile is flow-sensitive.
SampleProfileReaderItaniumRemapper * getRemapper()
bool ProfileIsCS
Whether function profiles are context-sensitive flat profiles.
std::error_code read(const DenseSet< StringRef > &FuncsToUse)
Read sample profiles for the given functions.
bool ProfileIsMD5
Whether the profile uses MD5 for Sample Contexts and function names.
virtual bool contains(StringRef Key) const
static std::unique_ptr< ProfileSummary > takeSummary(SampleProfileReader &Reader)
Take ownership of the summary of this reader.
virtual llvm::iterator_range< SampleProfileNameTable::iterator > getNameTable() const
It includes all the names that have samples either in outline instance or inline instance.
ProfileSummary & getSummary() const
Return the profile summary.
const HashKeyMap< DenseMap, FunctionId, FunctionId > * FuncNameToProfNameMap
SampleProfileFormat Format
The format of sample.
SampleProfileReader(std::unique_ptr< MemoryBuffer > B, LLVMContext &C, SampleProfileFormat Format=SPF_None)
std::unique_ptr< ProfileSummary > Summary
Profile summary information.
virtual bool hasUniqSuffix()
Return whether any name in the profile contains ".__uniq." suffix.
LLVM_ABI void computeSummary()
Compute summary for this profile.
uint32_t getDiscriminatorMask() const
Get the bitmask the discriminators: For FS profiles, return the bit mask for this pass.
uint64_t getFormatVersion() const
Return the format version of the profile. For tests only.
virtual bool dumpSectionInfo(raw_ostream &OS=dbgs())
SampleProfileFormat getFormat() const
Return the profile format.
virtual void setProfileUseMD5()
Force the profile to use MD5 in Sample contexts, even if function names are present.
void setDiscriminatorMaskedBitFrom(FSDiscriminatorPass P)
Set the bits for FS discriminators.
virtual std::error_code read(const DenseSet< StringRef > &FuncsToUse, SampleProfileMap &Profiles)
Read sample profiles for the given functions and write them to the given profile map.
bool profileIsCS() const
Whether input profile is fully context-sensitive.
bool ProfileIsFS
Whether the function profiles use FS discriminators.
virtual bool collectFuncsFromModule()
Collect functions with definitions in Module M.
FunctionSamples * getSamplesFor(StringRef Fname)
Return the samples collected for function F.
virtual bool contains(uint64_t GUID) const
LLVM_ABI void dumpJson(raw_ostream &OS=dbgs())
Print all the profiles on stream OS in the JSON format.
SampleProfileMap Profiles
Map every function to its associated profile.
uint64_t FormatVersion
Format version of the profile.
virtual std::error_code readHeader()=0
Read and validate the file header.
void setSkipFlatProf(bool Skip)
Don't read profile without context if the flag is set.
LLVM_ABI void dumpFunctionProfile(const FunctionSamples &FS, raw_ostream &OS=dbgs())
Print the profile for FunctionSamples on stream OS.
bool ProfileIsProbeBased
Whether samples are collected based on pseudo probes.
void reportError(int64_t LineNumber, const Twine &Msg) const
Report a parse error message.
virtual std::unique_ptr< ProfileSymbolList > getProfileSymbolList()
LLVMContext & Ctx
LLVM context used to emit diagnostics.
virtual std::error_code readImpl()=0
The implementaion to read sample profiles from the associated file.
bool contains(StringRef Key) const override
StringSampleProfileNameTable(const std::vector< FunctionId > &Vec)
StringSampleProfileNameTable(std::vector< FunctionId > &&Vec)
FunctionId operator[](size_t Idx) const override
The virtual file system interface.
constexpr OnDiskModeT OnDiskMode
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:370
constexpr InMemoryModeT InMemoryMode
SmallVector< FunctionSamples *, 10 > InlineCallStack
uint64_t read64le(const void *P)
Definition Endian.h:435
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition Endian.h:60
uint32_t read32le(const void *P)
Definition Endian.h:432
detail::packed_endian_specific_integral< uint64_t, llvm::endianness::little, unaligned > ulittle64_t
Definition Endian.h:293
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
static unsigned getFSPassBitEnd(sampleprof::FSDiscriminatorPass P)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
static unsigned getN1Bits(int N)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
Tags to select the initialization mode of SampleProfileFuncOffsetTable.