SampleProfReader.h 32 KB

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