xref: /freebsd/contrib/llvm-project/llvm/include/llvm/ProfileData/SampleProfReader.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
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/SmallVector.h"
229 #include "llvm/ADT/StringRef.h"
230 #include "llvm/IR/DiagnosticInfo.h"
231 #include "llvm/IR/LLVMContext.h"
232 #include "llvm/IR/ProfileSummary.h"
233 #include "llvm/ProfileData/GCOV.h"
234 #include "llvm/ProfileData/SampleProf.h"
235 #include "llvm/ProfileData/SymbolRemappingReader.h"
236 #include "llvm/Support/Compiler.h"
237 #include "llvm/Support/Debug.h"
238 #include "llvm/Support/Discriminator.h"
239 #include "llvm/Support/ErrorOr.h"
240 #include "llvm/Support/MemoryBuffer.h"
241 #include <cstdint>
242 #include <list>
243 #include <memory>
244 #include <optional>
245 #include <string>
246 #include <system_error>
247 #include <unordered_set>
248 #include <vector>
249 
250 namespace llvm {
251 
252 class raw_ostream;
253 class Twine;
254 
255 namespace vfs {
256 class FileSystem;
257 } // namespace vfs
258 
259 namespace sampleprof {
260 
261 class SampleProfileReader;
262 
263 /// SampleProfileReaderItaniumRemapper remaps the profile data from a
264 /// sample profile data reader, by applying a provided set of equivalences
265 /// between components of the symbol names in the profile.
266 class SampleProfileReaderItaniumRemapper {
267 public:
SampleProfileReaderItaniumRemapper(std::unique_ptr<MemoryBuffer> B,std::unique_ptr<SymbolRemappingReader> SRR,SampleProfileReader & R)268   SampleProfileReaderItaniumRemapper(std::unique_ptr<MemoryBuffer> B,
269                                      std::unique_ptr<SymbolRemappingReader> SRR,
270                                      SampleProfileReader &R)
271       : Buffer(std::move(B)), Remappings(std::move(SRR)), Reader(R) {
272     assert(Remappings && "Remappings cannot be nullptr");
273   }
274 
275   /// Create a remapper from the given remapping file. The remapper will
276   /// be used for profile read in by Reader.
277   LLVM_ABI static ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
278   create(StringRef Filename, vfs::FileSystem &FS, SampleProfileReader &Reader,
279          LLVMContext &C);
280 
281   /// Create a remapper from the given Buffer. The remapper will
282   /// be used for profile read in by Reader.
283   LLVM_ABI static ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
284   create(std::unique_ptr<MemoryBuffer> &B, SampleProfileReader &Reader,
285          LLVMContext &C);
286 
287   /// Apply remappings to the profile read by Reader.
288   LLVM_ABI void applyRemapping(LLVMContext &Ctx);
289 
hasApplied()290   bool hasApplied() { return RemappingApplied; }
291 
292   /// Insert function name into remapper.
insert(StringRef FunctionName)293   void insert(StringRef FunctionName) { Remappings->insert(FunctionName); }
294 
295   /// Query whether there is equivalent in the remapper which has been
296   /// inserted.
exist(StringRef FunctionName)297   bool exist(StringRef FunctionName) {
298     return Remappings->lookup(FunctionName);
299   }
300 
301   /// Return the equivalent name in the profile for \p FunctionName if
302   /// it exists.
303   LLVM_ABI std::optional<StringRef> lookUpNameInProfile(StringRef FunctionName);
304 
305 private:
306   // The buffer holding the content read from remapping file.
307   std::unique_ptr<MemoryBuffer> Buffer;
308   std::unique_ptr<SymbolRemappingReader> Remappings;
309   // Map remapping key to the name in the profile. By looking up the
310   // key in the remapper, a given new name can be mapped to the
311   // cannonical name using the NameMap.
312   DenseMap<SymbolRemappingReader::Key, StringRef> NameMap;
313   // The Reader the remapper is servicing.
314   SampleProfileReader &Reader;
315   // Indicate whether remapping has been applied to the profile read
316   // by Reader -- by calling applyRemapping.
317   bool RemappingApplied = false;
318 };
319 
320 /// Sample-based profile reader.
321 ///
322 /// Each profile contains sample counts for all the functions
323 /// executed. Inside each function, statements are annotated with the
324 /// collected samples on all the instructions associated with that
325 /// statement.
326 ///
327 /// For this to produce meaningful data, the program needs to be
328 /// compiled with some debug information (at minimum, line numbers:
329 /// -gline-tables-only). Otherwise, it will be impossible to match IR
330 /// instructions to the line numbers collected by the profiler.
331 ///
332 /// From the profile file, we are interested in collecting the
333 /// following information:
334 ///
335 /// * A list of functions included in the profile (mangled names).
336 ///
337 /// * For each function F:
338 ///   1. The total number of samples collected in F.
339 ///
340 ///   2. The samples collected at each line in F. To provide some
341 ///      protection against source code shuffling, line numbers should
342 ///      be relative to the start of the function.
343 ///
344 /// The reader supports two file formats: text and binary. The text format
345 /// is useful for debugging and testing, while the binary format is more
346 /// compact and I/O efficient. They can both be used interchangeably.
347 class SampleProfileReader {
348 public:
349   SampleProfileReader(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
350                       SampleProfileFormat Format = SPF_None)
Profiles()351       : Profiles(), Ctx(C), Buffer(std::move(B)), Format(Format) {}
352 
353   virtual ~SampleProfileReader() = default;
354 
355   /// Read and validate the file header.
356   virtual std::error_code readHeader() = 0;
357 
358   /// Set the bits for FS discriminators. Parameter Pass specify the sequence
359   /// number, Pass == i is for the i-th round of adding FS discriminators.
360   /// Pass == 0 is for using base discriminators.
setDiscriminatorMaskedBitFrom(FSDiscriminatorPass P)361   void setDiscriminatorMaskedBitFrom(FSDiscriminatorPass P) {
362     MaskedBitFrom = getFSPassBitEnd(P);
363   }
364 
365   /// Get the bitmask the discriminators: For FS profiles, return the bit
366   /// mask for this pass. For non FS profiles, return (unsigned) -1.
getDiscriminatorMask()367   uint32_t getDiscriminatorMask() const {
368     if (!ProfileIsFS)
369       return 0xFFFFFFFF;
370     assert((MaskedBitFrom != 0) && "MaskedBitFrom is not set properly");
371     return getN1Bits(MaskedBitFrom);
372   }
373 
374   /// The interface to read sample profiles from the associated file.
read()375   std::error_code read() {
376     if (std::error_code EC = readImpl())
377       return EC;
378     if (Remapper)
379       Remapper->applyRemapping(Ctx);
380     FunctionSamples::UseMD5 = useMD5();
381     return sampleprof_error::success;
382   }
383 
384   /// Read sample profiles for the given functions.
read(const DenseSet<StringRef> & FuncsToUse)385   std::error_code read(const DenseSet<StringRef> &FuncsToUse) {
386     DenseSet<StringRef> S;
387     for (StringRef F : FuncsToUse)
388       if (Profiles.find(FunctionId(F)) == Profiles.end())
389         S.insert(F);
390     if (std::error_code EC = read(S, Profiles))
391       return EC;
392     return sampleprof_error::success;
393   }
394 
395   /// The implementaion to read sample profiles from the associated file.
396   virtual std::error_code readImpl() = 0;
397 
398   /// Print the profile for \p FunctionSamples on stream \p OS.
399   LLVM_ABI void dumpFunctionProfile(const FunctionSamples &FS,
400                                     raw_ostream &OS = dbgs());
401 
402   /// Collect functions with definitions in Module M. For reader which
403   /// support loading function profiles on demand, return true when the
404   /// reader has been given a module. Always return false for reader
405   /// which doesn't support loading function profiles on demand.
collectFuncsFromModule()406   virtual bool collectFuncsFromModule() { return false; }
407 
408   /// Print all the profiles on stream \p OS.
409   LLVM_ABI void dump(raw_ostream &OS = dbgs());
410 
411   /// Print all the profiles on stream \p OS in the JSON format.
412   LLVM_ABI void dumpJson(raw_ostream &OS = dbgs());
413 
414   /// Return the samples collected for function \p F.
getSamplesFor(const Function & F)415   FunctionSamples *getSamplesFor(const Function &F) {
416     // The function name may have been updated by adding suffix. Call
417     // a helper to (optionally) strip off suffixes so that we can
418     // match against the original function name in the profile.
419     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
420     return getSamplesFor(CanonName);
421   }
422 
423   /// Return the samples collected for function \p F.
getSamplesFor(StringRef Fname)424   FunctionSamples *getSamplesFor(StringRef Fname) {
425     auto It = Profiles.find(FunctionId(Fname));
426     if (It != Profiles.end())
427       return &It->second;
428 
429     if (FuncNameToProfNameMap && !FuncNameToProfNameMap->empty()) {
430       auto R = FuncNameToProfNameMap->find(FunctionId(Fname));
431       if (R != FuncNameToProfNameMap->end()) {
432         Fname = R->second.stringRef();
433         auto It = Profiles.find(FunctionId(Fname));
434         if (It != Profiles.end())
435           return &It->second;
436       }
437     }
438 
439     if (Remapper) {
440       if (auto NameInProfile = Remapper->lookUpNameInProfile(Fname)) {
441         auto It = Profiles.find(FunctionId(*NameInProfile));
442         if (It != Profiles.end())
443           return &It->second;
444       }
445     }
446     return nullptr;
447   }
448 
449   /// Return all the profiles.
getProfiles()450   SampleProfileMap &getProfiles() { return Profiles; }
451 
452   /// Report a parse error message.
reportError(int64_t LineNumber,const Twine & Msg)453   void reportError(int64_t LineNumber, const Twine &Msg) const {
454     Ctx.diagnose(DiagnosticInfoSampleProfile(Buffer->getBufferIdentifier(),
455                                              LineNumber, Msg));
456   }
457 
458   /// Create a sample profile reader appropriate to the file format.
459   /// Create a remapper underlying if RemapFilename is not empty.
460   /// Parameter P specifies the FSDiscriminatorPass.
461   LLVM_ABI static ErrorOr<std::unique_ptr<SampleProfileReader>>
462   create(StringRef Filename, LLVMContext &C, vfs::FileSystem &FS,
463          FSDiscriminatorPass P = FSDiscriminatorPass::Base,
464          StringRef RemapFilename = "");
465 
466   /// Create a sample profile reader from the supplied memory buffer.
467   /// Create a remapper underlying if RemapFilename is not empty.
468   /// Parameter P specifies the FSDiscriminatorPass.
469   LLVM_ABI static ErrorOr<std::unique_ptr<SampleProfileReader>>
470   create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C, vfs::FileSystem &FS,
471          FSDiscriminatorPass P = FSDiscriminatorPass::Base,
472          StringRef RemapFilename = "");
473 
474   /// Return the profile summary.
getSummary()475   ProfileSummary &getSummary() const { return *Summary; }
476 
getBuffer()477   MemoryBuffer *getBuffer() const { return Buffer.get(); }
478 
479   /// \brief Return the profile format.
getFormat()480   SampleProfileFormat getFormat() const { return Format; }
481 
482   /// Whether input profile is based on pseudo probes.
profileIsProbeBased()483   bool profileIsProbeBased() const { return ProfileIsProbeBased; }
484 
485   /// Whether input profile is fully context-sensitive.
profileIsCS()486   bool profileIsCS() const { return ProfileIsCS; }
487 
488   /// Whether input profile contains ShouldBeInlined contexts.
profileIsPreInlined()489   bool profileIsPreInlined() const { return ProfileIsPreInlined; }
490 
491   /// Whether input profile is flow-sensitive.
profileIsFS()492   bool profileIsFS() const { return ProfileIsFS; }
493 
getProfileSymbolList()494   virtual std::unique_ptr<ProfileSymbolList> getProfileSymbolList() {
495     return nullptr;
496   };
497 
498   /// It includes all the names that have samples either in outline instance
499   /// or inline instance.
getNameTable()500   virtual std::vector<FunctionId> *getNameTable() { return nullptr; }
501   virtual bool dumpSectionInfo(raw_ostream &OS = dbgs()) { return false; };
502 
503   /// Return whether names in the profile are all MD5 numbers.
useMD5()504   bool useMD5() const { return ProfileIsMD5; }
505 
506   /// Force the profile to use MD5 in Sample contexts, even if function names
507   /// are present.
setProfileUseMD5()508   virtual void setProfileUseMD5() { ProfileIsMD5 = true; }
509 
510   /// Don't read profile without context if the flag is set.
setSkipFlatProf(bool Skip)511   void setSkipFlatProf(bool Skip) { SkipFlatProf = Skip; }
512 
513   /// Return whether any name in the profile contains ".__uniq." suffix.
hasUniqSuffix()514   virtual bool hasUniqSuffix() { return false; }
515 
getRemapper()516   SampleProfileReaderItaniumRemapper *getRemapper() { return Remapper.get(); }
517 
setModule(const Module * Mod)518   void setModule(const Module *Mod) { M = Mod; }
519 
setFuncNameToProfNameMap(const HashKeyMap<std::unordered_map,FunctionId,FunctionId> & FPMap)520   void setFuncNameToProfNameMap(
521       const HashKeyMap<std::unordered_map, FunctionId, FunctionId> &FPMap) {
522     FuncNameToProfNameMap = &FPMap;
523   }
524 
525 protected:
526   /// Map every function to its associated profile.
527   ///
528   /// The profile of every function executed at runtime is collected
529   /// in the structure FunctionSamples. This maps function objects
530   /// to their corresponding profiles.
531   SampleProfileMap Profiles;
532 
533   /// LLVM context used to emit diagnostics.
534   LLVMContext &Ctx;
535 
536   /// Memory buffer holding the profile file.
537   std::unique_ptr<MemoryBuffer> Buffer;
538 
539   /// Profile summary information.
540   std::unique_ptr<ProfileSummary> Summary;
541 
542   /// Take ownership of the summary of this reader.
543   static std::unique_ptr<ProfileSummary>
takeSummary(SampleProfileReader & Reader)544   takeSummary(SampleProfileReader &Reader) {
545     return std::move(Reader.Summary);
546   }
547 
548   /// Compute summary for this profile.
549   LLVM_ABI void computeSummary();
550 
551   /// Read sample profiles for the given functions and write them to the given
552   /// profile map. Currently it's only used for extended binary format to load
553   /// the profiles on-demand.
read(const DenseSet<StringRef> & FuncsToUse,SampleProfileMap & Profiles)554   virtual std::error_code read(const DenseSet<StringRef> &FuncsToUse,
555                                SampleProfileMap &Profiles) {
556     return sampleprof_error::not_implemented;
557   }
558 
559   std::unique_ptr<SampleProfileReaderItaniumRemapper> Remapper;
560 
561   // A map pointer to the FuncNameToProfNameMap in SampleProfileLoader,
562   // which maps the function name to the matched profile name. This is used
563   // for sample loader to look up profile using the new name.
564   const HashKeyMap<std::unordered_map, FunctionId, FunctionId>
565       *FuncNameToProfNameMap = nullptr;
566 
567   // A map from a function's context hash to its meta data section range, used
568   // for on-demand read function profile metadata.
569   std::unordered_map<uint64_t, std::pair<const uint8_t *, const uint8_t *>>
570       FuncMetadataIndex;
571 
572   std::pair<const uint8_t *, const uint8_t *> ProfileSecRange;
573 
574   /// Whether the profile has attribute metadata.
575   bool ProfileHasAttribute = false;
576 
577   /// \brief Whether samples are collected based on pseudo probes.
578   bool ProfileIsProbeBased = false;
579 
580   /// Whether function profiles are context-sensitive flat profiles.
581   bool ProfileIsCS = false;
582 
583   /// Whether function profile contains ShouldBeInlined contexts.
584   bool ProfileIsPreInlined = false;
585 
586   /// Number of context-sensitive profiles.
587   uint32_t CSProfileCount = 0;
588 
589   /// Whether the function profiles use FS discriminators.
590   bool ProfileIsFS = false;
591 
592   /// \brief The format of sample.
593   SampleProfileFormat Format = SPF_None;
594 
595   /// \brief The current module being compiled if SampleProfileReader
596   /// is used by compiler. If SampleProfileReader is used by other
597   /// tools which are not compiler, M is usually nullptr.
598   const Module *M = nullptr;
599 
600   /// Zero out the discriminator bits higher than bit MaskedBitFrom (0 based).
601   /// The default is to keep all the bits.
602   uint32_t MaskedBitFrom = 31;
603 
604   /// Whether the profile uses MD5 for Sample Contexts and function names. This
605   /// can be one-way overriden by the user to force use MD5.
606   bool ProfileIsMD5 = false;
607 
608   /// If SkipFlatProf is true, skip functions marked with !Flat in text mode or
609   /// sections with SecFlagFlat flag in ExtBinary mode.
610   bool SkipFlatProf = false;
611 };
612 
613 class LLVM_ABI SampleProfileReaderText : public SampleProfileReader {
614 public:
SampleProfileReaderText(std::unique_ptr<MemoryBuffer> B,LLVMContext & C)615   SampleProfileReaderText(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
616       : SampleProfileReader(std::move(B), C, SPF_Text) {}
617 
618   /// Read and validate the file header.
readHeader()619   std::error_code readHeader() override { return sampleprof_error::success; }
620 
621   /// Read sample profiles from the associated file.
622   std::error_code readImpl() override;
623 
624   /// Return true if \p Buffer is in the format supported by this class.
625   static bool hasFormat(const MemoryBuffer &Buffer);
626 
627   /// Text format sample profile does not support MD5 for now.
setProfileUseMD5()628   void setProfileUseMD5() override {}
629 
630 private:
631   /// CSNameTable is used to save full context vectors. This serves as an
632   /// underlying immutable buffer for all clients.
633   std::list<SampleContextFrameVector> CSNameTable;
634 };
635 
636 class LLVM_ABI SampleProfileReaderBinary : public SampleProfileReader {
637 public:
638   SampleProfileReaderBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
639                             SampleProfileFormat Format = SPF_None)
SampleProfileReader(std::move (B),C,Format)640       : SampleProfileReader(std::move(B), C, Format) {}
641 
642   /// Read and validate the file header.
643   std::error_code readHeader() override;
644 
645   /// Read sample profiles from the associated file.
646   std::error_code readImpl() override;
647 
648   /// It includes all the names that have samples either in outline instance
649   /// or inline instance.
getNameTable()650   std::vector<FunctionId> *getNameTable() override {
651     return &NameTable;
652   }
653 
654 protected:
655   /// Read a numeric value of type T from the profile.
656   ///
657   /// If an error occurs during decoding, a diagnostic message is emitted and
658   /// EC is set.
659   ///
660   /// \returns the read value.
661   template <typename T> ErrorOr<T> readNumber();
662 
663   /// Read a numeric value of type T from the profile. The value is saved
664   /// without encoded.
665   template <typename T> ErrorOr<T> readUnencodedNumber();
666 
667   /// Read a string from the profile.
668   ///
669   /// If an error occurs during decoding, a diagnostic message is emitted and
670   /// EC is set.
671   ///
672   /// \returns the read value.
673   ErrorOr<StringRef> readString();
674 
675   /// Read the string index and check whether it overflows the table.
676   template <typename T> inline ErrorOr<size_t> readStringIndex(T &Table);
677 
678   /// Read the next function profile instance.
679   std::error_code readFuncProfile(const uint8_t *Start);
680   std::error_code readFuncProfile(const uint8_t *Start,
681                                   SampleProfileMap &Profiles);
682 
683   /// Read the contents of the given profile instance.
684   std::error_code readProfile(FunctionSamples &FProfile);
685 
686   /// Read the contents of Magic number and Version number.
687   std::error_code readMagicIdent();
688 
689   /// Read profile summary.
690   std::error_code readSummary();
691 
692   /// Read the whole name table.
693   std::error_code readNameTable();
694 
695   /// Read a string indirectly via the name table. Optionally return the index.
696   ErrorOr<FunctionId> readStringFromTable(size_t *RetIdx = nullptr);
697 
698   /// Read a context indirectly via the CSNameTable. Optionally return the
699   /// index.
700   ErrorOr<SampleContextFrames> readContextFromTable(size_t *RetIdx = nullptr);
701 
702   /// Read a context indirectly via the CSNameTable if the profile has context,
703   /// otherwise same as readStringFromTable, also return its hash value.
704   ErrorOr<std::pair<SampleContext, uint64_t>> readSampleContextFromTable();
705 
706   /// Points to the current location in the buffer.
707   const uint8_t *Data = nullptr;
708 
709   /// Points to the end of the buffer.
710   const uint8_t *End = nullptr;
711 
712   /// Function name table.
713   std::vector<FunctionId> NameTable;
714 
715   /// CSNameTable is used to save full context vectors. It is the backing buffer
716   /// for SampleContextFrames.
717   std::vector<SampleContextFrameVector> CSNameTable;
718 
719   /// Table to cache MD5 values of sample contexts corresponding to
720   /// readSampleContextFromTable(), used to index into Profiles or
721   /// FuncOffsetTable.
722   std::vector<uint64_t> MD5SampleContextTable;
723 
724   /// The starting address of the table of MD5 values of sample contexts. For
725   /// fixed length MD5 non-CS profile it is same as MD5NameMemStart because
726   /// hashes of non-CS contexts are already in the profile. Otherwise it points
727   /// to the start of MD5SampleContextTable.
728   const uint64_t *MD5SampleContextStart = nullptr;
729 
730 private:
731   std::error_code readSummaryEntry(std::vector<ProfileSummaryEntry> &Entries);
732   virtual std::error_code verifySPMagic(uint64_t Magic) = 0;
733 };
734 
735 class LLVM_ABI SampleProfileReaderRawBinary : public SampleProfileReaderBinary {
736 private:
737   std::error_code verifySPMagic(uint64_t Magic) override;
738 
739 public:
740   SampleProfileReaderRawBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
741                                SampleProfileFormat Format = SPF_Binary)
SampleProfileReaderBinary(std::move (B),C,Format)742       : SampleProfileReaderBinary(std::move(B), C, Format) {}
743 
744   /// \brief Return true if \p Buffer is in the format supported by this class.
745   static bool hasFormat(const MemoryBuffer &Buffer);
746 };
747 
748 /// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase defines
749 /// the basic structure of the extensible binary format.
750 /// The format is organized in sections except the magic and version number
751 /// at the beginning. There is a section table before all the sections, and
752 /// each entry in the table describes the entry type, start, size and
753 /// attributes. The format in each section is defined by the section itself.
754 ///
755 /// It is easy to add a new section while maintaining the backward
756 /// compatibility of the profile. Nothing extra needs to be done. If we want
757 /// to extend an existing section, like add cache misses information in
758 /// addition to the sample count in the profile body, we can add a new section
759 /// with the extension and retire the existing section, and we could choose
760 /// to keep the parser of the old section if we want the reader to be able
761 /// to read both new and old format profile.
762 ///
763 /// SampleProfileReaderExtBinary/SampleProfileWriterExtBinary define the
764 /// commonly used sections of a profile in extensible binary format. It is
765 /// possible to define other types of profile inherited from
766 /// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase.
767 class LLVM_ABI SampleProfileReaderExtBinaryBase
768     : public SampleProfileReaderBinary {
769 private:
770   std::error_code decompressSection(const uint8_t *SecStart,
771                                     const uint64_t SecSize,
772                                     const uint8_t *&DecompressBuf,
773                                     uint64_t &DecompressBufSize);
774 
775   BumpPtrAllocator Allocator;
776 
777 protected:
778   std::vector<SecHdrTableEntry> SecHdrTable;
779   std::error_code readSecHdrTableEntry(uint64_t Idx);
780   std::error_code readSecHdrTable();
781 
782   std::error_code readFuncMetadata(bool ProfileHasAttribute,
783                                    DenseSet<FunctionSamples *> &Profiles);
784   std::error_code readFuncMetadata(bool ProfileHasAttribute);
785   std::error_code readFuncMetadata(bool ProfileHasAttribute,
786                                    FunctionSamples *FProfile);
787   std::error_code readFuncOffsetTable();
788   std::error_code readFuncProfiles();
789   std::error_code readFuncProfiles(const DenseSet<StringRef> &FuncsToUse,
790                                    SampleProfileMap &Profiles);
791   std::error_code readNameTableSec(bool IsMD5, bool FixedLengthMD5);
792   std::error_code readCSNameTableSec();
793   std::error_code readProfileSymbolList();
794 
795   std::error_code readHeader() override;
796   std::error_code verifySPMagic(uint64_t Magic) override = 0;
797   virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size,
798                                          const SecHdrTableEntry &Entry);
799   // placeholder for subclasses to dispatch their own section readers.
800   virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry) = 0;
801 
802   /// Determine which container readFuncOffsetTable() should populate, the list
803   /// FuncOffsetList or the map FuncOffsetTable.
804   bool useFuncOffsetList() const;
805 
806   std::unique_ptr<ProfileSymbolList> ProfSymList;
807 
808   /// The table mapping from a function context's MD5 to the offset of its
809   /// FunctionSample towards file start.
810   /// At most one of FuncOffsetTable and FuncOffsetList is populated.
811   DenseMap<hash_code, uint64_t> FuncOffsetTable;
812 
813   /// The list version of FuncOffsetTable. This is used if every entry is
814   /// being accessed.
815   std::vector<std::pair<SampleContext, uint64_t>> FuncOffsetList;
816 
817   /// The set containing the functions to use when compiling a module.
818   DenseSet<StringRef> FuncsToUse;
819 
820 public:
SampleProfileReaderExtBinaryBase(std::unique_ptr<MemoryBuffer> B,LLVMContext & C,SampleProfileFormat Format)821   SampleProfileReaderExtBinaryBase(std::unique_ptr<MemoryBuffer> B,
822                                    LLVMContext &C, SampleProfileFormat Format)
823       : SampleProfileReaderBinary(std::move(B), C, Format) {}
824 
825   /// Read sample profiles in extensible format from the associated file.
826   std::error_code readImpl() override;
827 
828   /// Get the total size of all \p Type sections.
829   uint64_t getSectionSize(SecType Type);
830   /// Get the total size of header and all sections.
831   uint64_t getFileSize();
832   bool dumpSectionInfo(raw_ostream &OS = dbgs()) override;
833 
834   /// Collect functions with definitions in Module M. Return true if
835   /// the reader has been given a module.
836   bool collectFuncsFromModule() override;
837 
getProfileSymbolList()838   std::unique_ptr<ProfileSymbolList> getProfileSymbolList() override {
839     return std::move(ProfSymList);
840   };
841 
842 private:
843   /// Read the profiles on-demand for the given functions. This is used after
844   /// stale call graph matching finds new functions whose profiles aren't loaded
845   /// at the beginning and we need to loaded the profiles explicitly for
846   /// potential matching.
847   std::error_code read(const DenseSet<StringRef> &FuncsToUse,
848                        SampleProfileMap &Profiles) override;
849 };
850 
851 class LLVM_ABI SampleProfileReaderExtBinary
852     : public SampleProfileReaderExtBinaryBase {
853 private:
854   std::error_code verifySPMagic(uint64_t Magic) override;
readCustomSection(const SecHdrTableEntry & Entry)855   std::error_code readCustomSection(const SecHdrTableEntry &Entry) override {
856     // Update the data reader pointer to the end of the section.
857     Data = End;
858     return sampleprof_error::success;
859   };
860 
861 public:
862   SampleProfileReaderExtBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
863                                SampleProfileFormat Format = SPF_Ext_Binary)
SampleProfileReaderExtBinaryBase(std::move (B),C,Format)864       : SampleProfileReaderExtBinaryBase(std::move(B), C, Format) {}
865 
866   /// \brief Return true if \p Buffer is in the format supported by this class.
867   static bool hasFormat(const MemoryBuffer &Buffer);
868 };
869 
870 using InlineCallStack = SmallVector<FunctionSamples *, 10>;
871 
872 // Supported histogram types in GCC.  Currently, we only need support for
873 // call target histograms.
874 enum HistType {
875   HIST_TYPE_INTERVAL,
876   HIST_TYPE_POW2,
877   HIST_TYPE_SINGLE_VALUE,
878   HIST_TYPE_CONST_DELTA,
879   HIST_TYPE_INDIR_CALL,
880   HIST_TYPE_AVERAGE,
881   HIST_TYPE_IOR,
882   HIST_TYPE_INDIR_CALL_TOPN
883 };
884 
885 class LLVM_ABI SampleProfileReaderGCC : public SampleProfileReader {
886 public:
SampleProfileReaderGCC(std::unique_ptr<MemoryBuffer> B,LLVMContext & C)887   SampleProfileReaderGCC(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
888       : SampleProfileReader(std::move(B), C, SPF_GCC),
889         GcovBuffer(Buffer.get()) {}
890 
891   /// Read and validate the file header.
892   std::error_code readHeader() override;
893 
894   /// Read sample profiles from the associated file.
895   std::error_code readImpl() override;
896 
897   /// Return true if \p Buffer is in the format supported by this class.
898   static bool hasFormat(const MemoryBuffer &Buffer);
899 
900 protected:
901   std::error_code readNameTable();
902   std::error_code readOneFunctionProfile(const InlineCallStack &InlineStack,
903                                          bool Update, uint32_t Offset);
904   std::error_code readFunctionProfiles();
905   std::error_code skipNextWord();
906   template <typename T> ErrorOr<T> readNumber();
907   ErrorOr<StringRef> readString();
908 
909   /// Read the section tag and check that it's the same as \p Expected.
910   std::error_code readSectionTag(uint32_t Expected);
911 
912   /// GCOV buffer containing the profile.
913   GCOVBuffer GcovBuffer;
914 
915   /// Function names in this profile.
916   std::vector<std::string> Names;
917 
918   /// GCOV tags used to separate sections in the profile file.
919   static const uint32_t GCOVTagAFDOFileNames = 0xaa000000;
920   static const uint32_t GCOVTagAFDOFunction = 0xac000000;
921 };
922 
923 } // end namespace sampleprof
924 
925 } // end namespace llvm
926 
927 #endif // LLVM_PROFILEDATA_SAMPLEPROFREADER_H
928