xref: /freebsd-src/contrib/llvm-project/llvm/include/llvm/ProfileData/SampleProfReader.h (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
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 //
32 // This is a nested tree in which the indentation represents the nesting level
33 // of the inline stack. There are no blank lines in the file. And the spacing
34 // within a single line is fixed. Additional spaces will result in an error
35 // while reading the file.
36 //
37 // Any line starting with the '#' character is completely ignored.
38 //
39 // Inlined calls are represented with indentation. The Inline stack is a
40 // stack of source locations in which the top of the stack represents the
41 // leaf function, and the bottom of the stack represents the actual
42 // symbol to which the instruction belongs.
43 //
44 // Function names must be mangled in order for the profile loader to
45 // match them in the current translation unit. The two numbers in the
46 // function header specify how many total samples were accumulated in the
47 // function (first number), and the total number of samples accumulated
48 // in the prologue of the function (second number). This head sample
49 // count provides an indicator of how frequently the function is invoked.
50 //
51 // There are three types of lines in the function body.
52 //
53 // * Sampled line represents the profile information of a source location.
54 // * Callsite line represents the profile information of a callsite.
55 // * Metadata line represents extra metadata of the function.
56 //
57 // Each sampled line may contain several items. Some are optional (marked
58 // below):
59 //
60 // a. Source line offset. This number represents the line number
61 //    in the function where the sample was collected. The line number is
62 //    always relative to the line where symbol of the function is
63 //    defined. So, if the function has its header at line 280, the offset
64 //    13 is at line 293 in the file.
65 //
66 //    Note that this offset should never be a negative number. This could
67 //    happen in cases like macros. The debug machinery will register the
68 //    line number at the point of macro expansion. So, if the macro was
69 //    expanded in a line before the start of the function, the profile
70 //    converter should emit a 0 as the offset (this means that the optimizers
71 //    will not be able to associate a meaningful weight to the instructions
72 //    in the macro).
73 //
74 // b. [OPTIONAL] Discriminator. This is used if the sampled program
75 //    was compiled with DWARF discriminator support
76 //    (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
77 //    DWARF discriminators are unsigned integer values that allow the
78 //    compiler to distinguish between multiple execution paths on the
79 //    same source line location.
80 //
81 //    For example, consider the line of code ``if (cond) foo(); else bar();``.
82 //    If the predicate ``cond`` is true 80% of the time, then the edge
83 //    into function ``foo`` should be considered to be taken most of the
84 //    time. But both calls to ``foo`` and ``bar`` are at the same source
85 //    line, so a sample count at that line is not sufficient. The
86 //    compiler needs to know which part of that line is taken more
87 //    frequently.
88 //
89 //    This is what discriminators provide. In this case, the calls to
90 //    ``foo`` and ``bar`` will be at the same line, but will have
91 //    different discriminator values. This allows the compiler to correctly
92 //    set edge weights into ``foo`` and ``bar``.
93 //
94 // c. Number of samples. This is an integer quantity representing the
95 //    number of samples collected by the profiler at this source
96 //    location.
97 //
98 // d. [OPTIONAL] Potential call targets and samples. If present, this
99 //    line contains a call instruction. This models both direct and
100 //    number of samples. For example,
101 //
102 //      130: 7  foo:3  bar:2  baz:7
103 //
104 //    The above means that at relative line offset 130 there is a call
105 //    instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
106 //    with ``baz()`` being the relatively more frequently called target.
107 //
108 // Each callsite line may contain several items. Some are optional.
109 //
110 // a. Source line offset. This number represents the line number of the
111 //    callsite that is inlined in the profiled binary.
112 //
113 // b. [OPTIONAL] Discriminator. Same as the discriminator for sampled line.
114 //
115 // c. Number of samples. This is an integer quantity representing the
116 //    total number of samples collected for the inlined instance at this
117 //    callsite
118 //
119 // Metadata line can occur in lines with one indent only, containing extra
120 // information for the top-level function. Furthermore, metadata can only
121 // occur after all the body samples and callsite samples.
122 // Each metadata line may contain a particular type of metadata, marked by
123 // the starting characters annotated with !. We process each metadata line
124 // independently, hence each metadata line has to form an independent piece
125 // of information that does not require cross-line reference.
126 // We support the following types of metadata:
127 //
128 // a. CFG Checksum (a.k.a. function hash):
129 //   !CFGChecksum: 12345
130 //
131 //
132 // Binary format
133 // -------------
134 //
135 // This is a more compact encoding. Numbers are encoded as ULEB128 values
136 // and all strings are encoded in a name table. The file is organized in
137 // the following sections:
138 //
139 // MAGIC (uint64_t)
140 //    File identifier computed by function SPMagic() (0x5350524f463432ff)
141 //
142 // VERSION (uint32_t)
143 //    File format version number computed by SPVersion()
144 //
145 // SUMMARY
146 //    TOTAL_COUNT (uint64_t)
147 //        Total number of samples in the profile.
148 //    MAX_COUNT (uint64_t)
149 //        Maximum value of samples on a line.
150 //    MAX_FUNCTION_COUNT (uint64_t)
151 //        Maximum number of samples at function entry (head samples).
152 //    NUM_COUNTS (uint64_t)
153 //        Number of lines with samples.
154 //    NUM_FUNCTIONS (uint64_t)
155 //        Number of functions with samples.
156 //    NUM_DETAILED_SUMMARY_ENTRIES (size_t)
157 //        Number of entries in detailed summary
158 //    DETAILED_SUMMARY
159 //        A list of detailed summary entry. Each entry consists of
160 //        CUTOFF (uint32_t)
161 //            Required percentile of total sample count expressed as a fraction
162 //            multiplied by 1000000.
163 //        MIN_COUNT (uint64_t)
164 //            The minimum number of samples required to reach the target
165 //            CUTOFF.
166 //        NUM_COUNTS (uint64_t)
167 //            Number of samples to get to the desrired percentile.
168 //
169 // NAME TABLE
170 //    SIZE (uint32_t)
171 //        Number of entries in the name table.
172 //    NAMES
173 //        A NUL-separated list of SIZE strings.
174 //
175 // FUNCTION BODY (one for each uninlined function body present in the profile)
176 //    HEAD_SAMPLES (uint64_t) [only for top-level functions]
177 //        Total number of samples collected at the head (prologue) of the
178 //        function.
179 //        NOTE: This field should only be present for top-level functions
180 //              (i.e., not inlined into any caller). Inlined function calls
181 //              have no prologue, so they don't need this.
182 //    NAME_IDX (uint32_t)
183 //        Index into the name table indicating the function name.
184 //    SAMPLES (uint64_t)
185 //        Total number of samples collected in this function.
186 //    NRECS (uint32_t)
187 //        Total number of sampling records this function's profile.
188 //    BODY RECORDS
189 //        A list of NRECS entries. Each entry contains:
190 //          OFFSET (uint32_t)
191 //            Line offset from the start of the function.
192 //          DISCRIMINATOR (uint32_t)
193 //            Discriminator value (see description of discriminators
194 //            in the text format documentation above).
195 //          SAMPLES (uint64_t)
196 //            Number of samples collected at this location.
197 //          NUM_CALLS (uint32_t)
198 //            Number of non-inlined function calls made at this location. In the
199 //            case of direct calls, this number will always be 1. For indirect
200 //            calls (virtual functions and function pointers) this will
201 //            represent all the actual functions called at runtime.
202 //          CALL_TARGETS
203 //            A list of NUM_CALLS entries for each called function:
204 //               NAME_IDX (uint32_t)
205 //                  Index into the name table with the callee name.
206 //               SAMPLES (uint64_t)
207 //                  Number of samples collected at the call site.
208 //    NUM_INLINED_FUNCTIONS (uint32_t)
209 //      Number of callees inlined into this function.
210 //    INLINED FUNCTION RECORDS
211 //      A list of NUM_INLINED_FUNCTIONS entries describing each of the inlined
212 //      callees.
213 //        OFFSET (uint32_t)
214 //          Line offset from the start of the function.
215 //        DISCRIMINATOR (uint32_t)
216 //          Discriminator value (see description of discriminators
217 //          in the text format documentation above).
218 //        FUNCTION BODY
219 //          A FUNCTION BODY entry describing the inlined function.
220 //===----------------------------------------------------------------------===//
221 
222 #ifndef LLVM_PROFILEDATA_SAMPLEPROFREADER_H
223 #define LLVM_PROFILEDATA_SAMPLEPROFREADER_H
224 
225 #include "llvm/ADT/Optional.h"
226 #include "llvm/ADT/SmallVector.h"
227 #include "llvm/ADT/StringMap.h"
228 #include "llvm/ADT/StringRef.h"
229 #include "llvm/IR/DiagnosticInfo.h"
230 #include "llvm/IR/Function.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/Support/Debug.h"
236 #include "llvm/Support/ErrorOr.h"
237 #include "llvm/Support/MemoryBuffer.h"
238 #include "llvm/Support/SymbolRemappingReader.h"
239 #include <algorithm>
240 #include <cstdint>
241 #include <memory>
242 #include <string>
243 #include <system_error>
244 #include <vector>
245 
246 namespace llvm {
247 
248 class raw_ostream;
249 class Twine;
250 
251 namespace sampleprof {
252 
253 class SampleProfileReader;
254 
255 /// SampleProfileReaderItaniumRemapper remaps the profile data from a
256 /// sample profile data reader, by applying a provided set of equivalences
257 /// between components of the symbol names in the profile.
258 class SampleProfileReaderItaniumRemapper {
259 public:
260   SampleProfileReaderItaniumRemapper(std::unique_ptr<MemoryBuffer> B,
261                                      std::unique_ptr<SymbolRemappingReader> SRR,
262                                      SampleProfileReader &R)
263       : Buffer(std::move(B)), Remappings(std::move(SRR)), Reader(R) {
264     assert(Remappings && "Remappings cannot be nullptr");
265   }
266 
267   /// Create a remapper from the given remapping file. The remapper will
268   /// be used for profile read in by Reader.
269   static ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
270   create(const std::string Filename, SampleProfileReader &Reader,
271          LLVMContext &C);
272 
273   /// Create a remapper from the given Buffer. The remapper will
274   /// be used for profile read in by Reader.
275   static ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
276   create(std::unique_ptr<MemoryBuffer> &B, SampleProfileReader &Reader,
277          LLVMContext &C);
278 
279   /// Apply remappings to the profile read by Reader.
280   void applyRemapping(LLVMContext &Ctx);
281 
282   bool hasApplied() { return RemappingApplied; }
283 
284   /// Insert function name into remapper.
285   void insert(StringRef FunctionName) { Remappings->insert(FunctionName); }
286 
287   /// Query whether there is equivalent in the remapper which has been
288   /// inserted.
289   bool exist(StringRef FunctionName) {
290     return Remappings->lookup(FunctionName);
291   }
292 
293   /// Return the equivalent name in the profile for \p FunctionName if
294   /// it exists.
295   Optional<StringRef> lookUpNameInProfile(StringRef FunctionName);
296 
297 private:
298   // The buffer holding the content read from remapping file.
299   std::unique_ptr<MemoryBuffer> Buffer;
300   std::unique_ptr<SymbolRemappingReader> Remappings;
301   // Map remapping key to the name in the profile. By looking up the
302   // key in the remapper, a given new name can be mapped to the
303   // cannonical name using the NameMap.
304   DenseMap<SymbolRemappingReader::Key, StringRef> NameMap;
305   // The Reader the remapper is servicing.
306   SampleProfileReader &Reader;
307   // Indicate whether remapping has been applied to the profile read
308   // by Reader -- by calling applyRemapping.
309   bool RemappingApplied = false;
310 };
311 
312 /// Sample-based profile reader.
313 ///
314 /// Each profile contains sample counts for all the functions
315 /// executed. Inside each function, statements are annotated with the
316 /// collected samples on all the instructions associated with that
317 /// statement.
318 ///
319 /// For this to produce meaningful data, the program needs to be
320 /// compiled with some debug information (at minimum, line numbers:
321 /// -gline-tables-only). Otherwise, it will be impossible to match IR
322 /// instructions to the line numbers collected by the profiler.
323 ///
324 /// From the profile file, we are interested in collecting the
325 /// following information:
326 ///
327 /// * A list of functions included in the profile (mangled names).
328 ///
329 /// * For each function F:
330 ///   1. The total number of samples collected in F.
331 ///
332 ///   2. The samples collected at each line in F. To provide some
333 ///      protection against source code shuffling, line numbers should
334 ///      be relative to the start of the function.
335 ///
336 /// The reader supports two file formats: text and binary. The text format
337 /// is useful for debugging and testing, while the binary format is more
338 /// compact and I/O efficient. They can both be used interchangeably.
339 class SampleProfileReader {
340 public:
341   SampleProfileReader(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
342                       SampleProfileFormat Format = SPF_None)
343       : Profiles(0), Ctx(C), Buffer(std::move(B)), Format(Format) {}
344 
345   virtual ~SampleProfileReader() = default;
346 
347   /// Read and validate the file header.
348   virtual std::error_code readHeader() = 0;
349 
350   /// The interface to read sample profiles from the associated file.
351   std::error_code read() {
352     if (std::error_code EC = readImpl())
353       return EC;
354     if (Remapper)
355       Remapper->applyRemapping(Ctx);
356     FunctionSamples::UseMD5 = useMD5();
357     return sampleprof_error::success;
358   }
359 
360   /// The implementaion to read sample profiles from the associated file.
361   virtual std::error_code readImpl() = 0;
362 
363   /// Print the profile for \p FName on stream \p OS.
364   void dumpFunctionProfile(StringRef FName, raw_ostream &OS = dbgs());
365 
366   virtual void collectFuncsFrom(const Module &M) {}
367 
368   /// Print all the profiles on stream \p OS.
369   void dump(raw_ostream &OS = dbgs());
370 
371   /// Return the samples collected for function \p F.
372   FunctionSamples *getSamplesFor(const Function &F) {
373     // The function name may have been updated by adding suffix. Call
374     // a helper to (optionally) strip off suffixes so that we can
375     // match against the original function name in the profile.
376     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
377     return getSamplesFor(CanonName);
378   }
379 
380   /// Return the samples collected for function \p F, create empty
381   /// FunctionSamples if it doesn't exist.
382   FunctionSamples *getOrCreateSamplesFor(const Function &F) {
383     std::string FGUID;
384     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
385     CanonName = getRepInFormat(CanonName, useMD5(), FGUID);
386     return &Profiles[CanonName];
387   }
388 
389   /// Return the samples collected for function \p F.
390   virtual FunctionSamples *getSamplesFor(StringRef Fname) {
391     std::string FGUID;
392     Fname = getRepInFormat(Fname, useMD5(), FGUID);
393     auto It = Profiles.find(Fname);
394     if (It != Profiles.end())
395       return &It->second;
396 
397     if (Remapper) {
398       if (auto NameInProfile = Remapper->lookUpNameInProfile(Fname)) {
399         auto It = Profiles.find(*NameInProfile);
400         if (It != Profiles.end())
401           return &It->second;
402       }
403     }
404     return nullptr;
405   }
406 
407   /// Return all the profiles.
408   StringMap<FunctionSamples> &getProfiles() { return Profiles; }
409 
410   /// Report a parse error message.
411   void reportError(int64_t LineNumber, const Twine &Msg) const {
412     Ctx.diagnose(DiagnosticInfoSampleProfile(Buffer->getBufferIdentifier(),
413                                              LineNumber, Msg));
414   }
415 
416   /// Create a sample profile reader appropriate to the file format.
417   /// Create a remapper underlying if RemapFilename is not empty.
418   static ErrorOr<std::unique_ptr<SampleProfileReader>>
419   create(const std::string Filename, LLVMContext &C,
420          const std::string RemapFilename = "");
421 
422   /// Create a sample profile reader from the supplied memory buffer.
423   /// Create a remapper underlying if RemapFilename is not empty.
424   static ErrorOr<std::unique_ptr<SampleProfileReader>>
425   create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
426          const std::string RemapFilename = "");
427 
428   /// Return the profile summary.
429   ProfileSummary &getSummary() const { return *(Summary.get()); }
430 
431   MemoryBuffer *getBuffer() const { return Buffer.get(); }
432 
433   /// \brief Return the profile format.
434   SampleProfileFormat getFormat() const { return Format; }
435 
436   /// Whether input profile is based on pseudo probes.
437   bool profileIsProbeBased() const { return ProfileIsProbeBased; }
438 
439   /// Whether input profile is fully context-sensitive
440   bool profileIsCS() const { return ProfileIsCS; }
441 
442   virtual std::unique_ptr<ProfileSymbolList> getProfileSymbolList() {
443     return nullptr;
444   };
445 
446   /// It includes all the names that have samples either in outline instance
447   /// or inline instance.
448   virtual std::vector<StringRef> *getNameTable() { return nullptr; }
449   virtual bool dumpSectionInfo(raw_ostream &OS = dbgs()) { return false; };
450 
451   /// Return whether names in the profile are all MD5 numbers.
452   virtual bool useMD5() { return false; }
453 
454   /// Don't read profile without context if the flag is set. This is only meaningful
455   /// for ExtBinary format.
456   virtual void setSkipFlatProf(bool Skip) {}
457 
458   SampleProfileReaderItaniumRemapper *getRemapper() { return Remapper.get(); }
459 
460 protected:
461   /// Map every function to its associated profile.
462   ///
463   /// The profile of every function executed at runtime is collected
464   /// in the structure FunctionSamples. This maps function objects
465   /// to their corresponding profiles.
466   StringMap<FunctionSamples> Profiles;
467 
468   /// LLVM context used to emit diagnostics.
469   LLVMContext &Ctx;
470 
471   /// Memory buffer holding the profile file.
472   std::unique_ptr<MemoryBuffer> Buffer;
473 
474   /// Profile summary information.
475   std::unique_ptr<ProfileSummary> Summary;
476 
477   /// Take ownership of the summary of this reader.
478   static std::unique_ptr<ProfileSummary>
479   takeSummary(SampleProfileReader &Reader) {
480     return std::move(Reader.Summary);
481   }
482 
483   /// Compute summary for this profile.
484   void computeSummary();
485 
486   std::unique_ptr<SampleProfileReaderItaniumRemapper> Remapper;
487 
488   /// \brief Whether samples are collected based on pseudo probes.
489   bool ProfileIsProbeBased = false;
490 
491   bool ProfileIsCS = false;
492 
493   /// \brief The format of sample.
494   SampleProfileFormat Format = SPF_None;
495 };
496 
497 class SampleProfileReaderText : public SampleProfileReader {
498 public:
499   SampleProfileReaderText(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
500       : SampleProfileReader(std::move(B), C, SPF_Text) {}
501 
502   /// Read and validate the file header.
503   std::error_code readHeader() override { return sampleprof_error::success; }
504 
505   /// Read sample profiles from the associated file.
506   std::error_code readImpl() override;
507 
508   /// Return true if \p Buffer is in the format supported by this class.
509   static bool hasFormat(const MemoryBuffer &Buffer);
510 };
511 
512 class SampleProfileReaderBinary : public SampleProfileReader {
513 public:
514   SampleProfileReaderBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
515                             SampleProfileFormat Format = SPF_None)
516       : SampleProfileReader(std::move(B), C, Format) {}
517 
518   /// Read and validate the file header.
519   virtual std::error_code readHeader() override;
520 
521   /// Read sample profiles from the associated file.
522   std::error_code readImpl() override;
523 
524   /// It includes all the names that have samples either in outline instance
525   /// or inline instance.
526   virtual std::vector<StringRef> *getNameTable() override { return &NameTable; }
527 
528 protected:
529   /// Read a numeric value of type T from the profile.
530   ///
531   /// If an error occurs during decoding, a diagnostic message is emitted and
532   /// EC is set.
533   ///
534   /// \returns the read value.
535   template <typename T> ErrorOr<T> readNumber();
536 
537   /// Read a numeric value of type T from the profile. The value is saved
538   /// without encoded.
539   template <typename T> ErrorOr<T> readUnencodedNumber();
540 
541   /// Read a string from the profile.
542   ///
543   /// If an error occurs during decoding, a diagnostic message is emitted and
544   /// EC is set.
545   ///
546   /// \returns the read value.
547   ErrorOr<StringRef> readString();
548 
549   /// Read the string index and check whether it overflows the table.
550   template <typename T> inline ErrorOr<uint32_t> readStringIndex(T &Table);
551 
552   /// Return true if we've reached the end of file.
553   bool at_eof() const { return Data >= End; }
554 
555   /// Read the next function profile instance.
556   std::error_code readFuncProfile(const uint8_t *Start);
557 
558   /// Read the contents of the given profile instance.
559   std::error_code readProfile(FunctionSamples &FProfile);
560 
561   /// Read the contents of Magic number and Version number.
562   std::error_code readMagicIdent();
563 
564   /// Read profile summary.
565   std::error_code readSummary();
566 
567   /// Read the whole name table.
568   virtual std::error_code readNameTable();
569 
570   /// Points to the current location in the buffer.
571   const uint8_t *Data = nullptr;
572 
573   /// Points to the end of the buffer.
574   const uint8_t *End = nullptr;
575 
576   /// Function name table.
577   std::vector<StringRef> NameTable;
578 
579   /// Read a string indirectly via the name table.
580   virtual ErrorOr<StringRef> readStringFromTable();
581 
582 private:
583   std::error_code readSummaryEntry(std::vector<ProfileSummaryEntry> &Entries);
584   virtual std::error_code verifySPMagic(uint64_t Magic) = 0;
585 };
586 
587 class SampleProfileReaderRawBinary : public SampleProfileReaderBinary {
588 private:
589   virtual std::error_code verifySPMagic(uint64_t Magic) override;
590 
591 public:
592   SampleProfileReaderRawBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
593                                SampleProfileFormat Format = SPF_Binary)
594       : SampleProfileReaderBinary(std::move(B), C, Format) {}
595 
596   /// \brief Return true if \p Buffer is in the format supported by this class.
597   static bool hasFormat(const MemoryBuffer &Buffer);
598 };
599 
600 /// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase defines
601 /// the basic structure of the extensible binary format.
602 /// The format is organized in sections except the magic and version number
603 /// at the beginning. There is a section table before all the sections, and
604 /// each entry in the table describes the entry type, start, size and
605 /// attributes. The format in each section is defined by the section itself.
606 ///
607 /// It is easy to add a new section while maintaining the backward
608 /// compatibility of the profile. Nothing extra needs to be done. If we want
609 /// to extend an existing section, like add cache misses information in
610 /// addition to the sample count in the profile body, we can add a new section
611 /// with the extension and retire the existing section, and we could choose
612 /// to keep the parser of the old section if we want the reader to be able
613 /// to read both new and old format profile.
614 ///
615 /// SampleProfileReaderExtBinary/SampleProfileWriterExtBinary define the
616 /// commonly used sections of a profile in extensible binary format. It is
617 /// possible to define other types of profile inherited from
618 /// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase.
619 class SampleProfileReaderExtBinaryBase : public SampleProfileReaderBinary {
620 private:
621   std::error_code decompressSection(const uint8_t *SecStart,
622                                     const uint64_t SecSize,
623                                     const uint8_t *&DecompressBuf,
624                                     uint64_t &DecompressBufSize);
625 
626   BumpPtrAllocator Allocator;
627 
628 protected:
629   std::vector<SecHdrTableEntry> SecHdrTable;
630   std::error_code readSecHdrTableEntry(uint32_t Idx);
631   std::error_code readSecHdrTable();
632 
633   std::error_code readFuncMetadata();
634   std::error_code readFuncOffsetTable();
635   std::error_code readFuncProfiles();
636   std::error_code readMD5NameTable();
637   std::error_code readNameTableSec(bool IsMD5);
638   std::error_code readProfileSymbolList();
639 
640   virtual std::error_code readHeader() override;
641   virtual std::error_code verifySPMagic(uint64_t Magic) override = 0;
642   virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size,
643                                          const SecHdrTableEntry &Entry);
644   // placeholder for subclasses to dispatch their own section readers.
645   virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry) = 0;
646   virtual ErrorOr<StringRef> readStringFromTable() override;
647 
648   std::unique_ptr<ProfileSymbolList> ProfSymList;
649 
650   /// The table mapping from function name to the offset of its FunctionSample
651   /// towards file start.
652   DenseMap<StringRef, uint64_t> FuncOffsetTable;
653   /// The set containing the functions to use when compiling a module.
654   DenseSet<StringRef> FuncsToUse;
655   /// Use all functions from the input profile.
656   bool UseAllFuncs = true;
657 
658   /// Use fixed length MD5 instead of ULEB128 encoding so NameTable doesn't
659   /// need to be read in up front and can be directly accessed using index.
660   bool FixedLengthMD5 = false;
661   /// The starting address of NameTable containing fixed length MD5.
662   const uint8_t *MD5NameMemStart = nullptr;
663 
664   /// If MD5 is used in NameTable section, the section saves uint64_t data.
665   /// The uint64_t data has to be converted to a string and then the string
666   /// will be used to initialize StringRef in NameTable.
667   /// Note NameTable contains StringRef so it needs another buffer to own
668   /// the string data. MD5StringBuf serves as the string buffer that is
669   /// referenced by NameTable (vector of StringRef). We make sure
670   /// the lifetime of MD5StringBuf is not shorter than that of NameTable.
671   std::unique_ptr<std::vector<std::string>> MD5StringBuf;
672 
673   /// If SkipFlatProf is true, skip the sections with
674   /// SecFlagFlat flag.
675   bool SkipFlatProf = false;
676 
677 public:
678   SampleProfileReaderExtBinaryBase(std::unique_ptr<MemoryBuffer> B,
679                                    LLVMContext &C, SampleProfileFormat Format)
680       : SampleProfileReaderBinary(std::move(B), C, Format) {}
681 
682   /// Read sample profiles in extensible format from the associated file.
683   std::error_code readImpl() override;
684 
685   /// Get the total size of all \p Type sections.
686   uint64_t getSectionSize(SecType Type);
687   /// Get the total size of header and all sections.
688   uint64_t getFileSize();
689   virtual bool dumpSectionInfo(raw_ostream &OS = dbgs()) override;
690 
691   /// Collect functions with definitions in Module \p M.
692   void collectFuncsFrom(const Module &M) override;
693 
694   /// Return whether names in the profile are all MD5 numbers.
695   virtual bool useMD5() override { return MD5StringBuf.get(); }
696 
697   virtual std::unique_ptr<ProfileSymbolList> getProfileSymbolList() override {
698     return std::move(ProfSymList);
699   };
700 
701   virtual void setSkipFlatProf(bool Skip) override { SkipFlatProf = Skip; }
702 };
703 
704 class SampleProfileReaderExtBinary : public SampleProfileReaderExtBinaryBase {
705 private:
706   virtual std::error_code verifySPMagic(uint64_t Magic) override;
707   virtual std::error_code
708   readCustomSection(const SecHdrTableEntry &Entry) override {
709     return sampleprof_error::success;
710   };
711 
712 public:
713   SampleProfileReaderExtBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
714                                SampleProfileFormat Format = SPF_Ext_Binary)
715       : SampleProfileReaderExtBinaryBase(std::move(B), C, Format) {}
716 
717   /// \brief Return true if \p Buffer is in the format supported by this class.
718   static bool hasFormat(const MemoryBuffer &Buffer);
719 };
720 
721 class SampleProfileReaderCompactBinary : public SampleProfileReaderBinary {
722 private:
723   /// Function name table.
724   std::vector<std::string> NameTable;
725   /// The table mapping from function name to the offset of its FunctionSample
726   /// towards file start.
727   DenseMap<StringRef, uint64_t> FuncOffsetTable;
728   /// The set containing the functions to use when compiling a module.
729   DenseSet<StringRef> FuncsToUse;
730   /// Use all functions from the input profile.
731   bool UseAllFuncs = true;
732   virtual std::error_code verifySPMagic(uint64_t Magic) override;
733   virtual std::error_code readNameTable() override;
734   /// Read a string indirectly via the name table.
735   virtual ErrorOr<StringRef> readStringFromTable() override;
736   virtual std::error_code readHeader() override;
737   std::error_code readFuncOffsetTable();
738 
739 public:
740   SampleProfileReaderCompactBinary(std::unique_ptr<MemoryBuffer> B,
741                                    LLVMContext &C)
742       : SampleProfileReaderBinary(std::move(B), C, SPF_Compact_Binary) {}
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   /// Read samples only for functions to use.
748   std::error_code readImpl() override;
749 
750   /// Collect functions to be used when compiling Module \p M.
751   void collectFuncsFrom(const Module &M) override;
752 
753   /// Return whether names in the profile are all MD5 numbers.
754   virtual bool useMD5() override { return true; }
755 };
756 
757 using InlineCallStack = SmallVector<FunctionSamples *, 10>;
758 
759 // Supported histogram types in GCC.  Currently, we only need support for
760 // call target histograms.
761 enum HistType {
762   HIST_TYPE_INTERVAL,
763   HIST_TYPE_POW2,
764   HIST_TYPE_SINGLE_VALUE,
765   HIST_TYPE_CONST_DELTA,
766   HIST_TYPE_INDIR_CALL,
767   HIST_TYPE_AVERAGE,
768   HIST_TYPE_IOR,
769   HIST_TYPE_INDIR_CALL_TOPN
770 };
771 
772 class SampleProfileReaderGCC : public SampleProfileReader {
773 public:
774   SampleProfileReaderGCC(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
775       : SampleProfileReader(std::move(B), C, SPF_GCC),
776         GcovBuffer(Buffer.get()) {}
777 
778   /// Read and validate the file header.
779   std::error_code readHeader() override;
780 
781   /// Read sample profiles from the associated file.
782   std::error_code readImpl() override;
783 
784   /// Return true if \p Buffer is in the format supported by this class.
785   static bool hasFormat(const MemoryBuffer &Buffer);
786 
787 protected:
788   std::error_code readNameTable();
789   std::error_code readOneFunctionProfile(const InlineCallStack &InlineStack,
790                                          bool Update, uint32_t Offset);
791   std::error_code readFunctionProfiles();
792   std::error_code skipNextWord();
793   template <typename T> ErrorOr<T> readNumber();
794   ErrorOr<StringRef> readString();
795 
796   /// Read the section tag and check that it's the same as \p Expected.
797   std::error_code readSectionTag(uint32_t Expected);
798 
799   /// GCOV buffer containing the profile.
800   GCOVBuffer GcovBuffer;
801 
802   /// Function names in this profile.
803   std::vector<std::string> Names;
804 
805   /// GCOV tags used to separate sections in the profile file.
806   static const uint32_t GCOVTagAFDOFileNames = 0xaa000000;
807   static const uint32_t GCOVTagAFDOFunction = 0xac000000;
808 };
809 
810 } // end namespace sampleprof
811 
812 } // end namespace llvm
813 
814 #endif // LLVM_PROFILEDATA_SAMPLEPROFREADER_H
815