SampleProfReader.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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 (uint32_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 (uint32_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 (uint32_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. #ifndef LLVM_PROFILEDATA_SAMPLEPROFREADER_H
  225. #define LLVM_PROFILEDATA_SAMPLEPROFREADER_H
  226. #include "llvm/ADT/Optional.h"
  227. #include "llvm/ADT/SmallVector.h"
  228. #include "llvm/ADT/StringMap.h"
  229. #include "llvm/ADT/StringRef.h"
  230. #include "llvm/IR/DiagnosticInfo.h"
  231. #include "llvm/IR/Function.h"
  232. #include "llvm/IR/LLVMContext.h"
  233. #include "llvm/IR/ProfileSummary.h"
  234. #include "llvm/ProfileData/GCOV.h"
  235. #include "llvm/ProfileData/SampleProf.h"
  236. #include "llvm/Support/Debug.h"
  237. #include "llvm/Support/ErrorOr.h"
  238. #include "llvm/Support/MemoryBuffer.h"
  239. #include "llvm/Support/SymbolRemappingReader.h"
  240. #include <algorithm>
  241. #include <cstdint>
  242. #include <memory>
  243. #include <string>
  244. #include <system_error>
  245. #include <vector>
  246. namespace llvm {
  247. class raw_ostream;
  248. class Twine;
  249. namespace sampleprof {
  250. class SampleProfileReader;
  251. /// SampleProfileReaderItaniumRemapper remaps the profile data from a
  252. /// sample profile data reader, by applying a provided set of equivalences
  253. /// between components of the symbol names in the profile.
  254. class SampleProfileReaderItaniumRemapper {
  255. public:
  256. SampleProfileReaderItaniumRemapper(std::unique_ptr<MemoryBuffer> B,
  257. std::unique_ptr<SymbolRemappingReader> SRR,
  258. SampleProfileReader &R)
  259. : Buffer(std::move(B)), Remappings(std::move(SRR)), Reader(R) {
  260. assert(Remappings && "Remappings cannot be nullptr");
  261. }
  262. /// Create a remapper from the given remapping file. The remapper will
  263. /// be used for profile read in by Reader.
  264. static ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
  265. create(const std::string Filename, SampleProfileReader &Reader,
  266. LLVMContext &C);
  267. /// Create a remapper from the given Buffer. The remapper will
  268. /// be used for profile read in by Reader.
  269. static ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
  270. create(std::unique_ptr<MemoryBuffer> &B, SampleProfileReader &Reader,
  271. LLVMContext &C);
  272. /// Apply remappings to the profile read by Reader.
  273. void applyRemapping(LLVMContext &Ctx);
  274. bool hasApplied() { return RemappingApplied; }
  275. /// Insert function name into remapper.
  276. void insert(StringRef FunctionName) { Remappings->insert(FunctionName); }
  277. /// Query whether there is equivalent in the remapper which has been
  278. /// inserted.
  279. bool exist(StringRef FunctionName) {
  280. return Remappings->lookup(FunctionName);
  281. }
  282. /// Return the equivalent name in the profile for \p FunctionName if
  283. /// it exists.
  284. Optional<StringRef> lookUpNameInProfile(StringRef FunctionName);
  285. private:
  286. // The buffer holding the content read from remapping file.
  287. std::unique_ptr<MemoryBuffer> Buffer;
  288. std::unique_ptr<SymbolRemappingReader> Remappings;
  289. // Map remapping key to the name in the profile. By looking up the
  290. // key in the remapper, a given new name can be mapped to the
  291. // cannonical name using the NameMap.
  292. DenseMap<SymbolRemappingReader::Key, StringRef> NameMap;
  293. // The Reader the remapper is servicing.
  294. SampleProfileReader &Reader;
  295. // Indicate whether remapping has been applied to the profile read
  296. // by Reader -- by calling applyRemapping.
  297. bool RemappingApplied = false;
  298. };
  299. /// Sample-based profile reader.
  300. ///
  301. /// Each profile contains sample counts for all the functions
  302. /// executed. Inside each function, statements are annotated with the
  303. /// collected samples on all the instructions associated with that
  304. /// statement.
  305. ///
  306. /// For this to produce meaningful data, the program needs to be
  307. /// compiled with some debug information (at minimum, line numbers:
  308. /// -gline-tables-only). Otherwise, it will be impossible to match IR
  309. /// instructions to the line numbers collected by the profiler.
  310. ///
  311. /// From the profile file, we are interested in collecting the
  312. /// following information:
  313. ///
  314. /// * A list of functions included in the profile (mangled names).
  315. ///
  316. /// * For each function F:
  317. /// 1. The total number of samples collected in F.
  318. ///
  319. /// 2. The samples collected at each line in F. To provide some
  320. /// protection against source code shuffling, line numbers should
  321. /// be relative to the start of the function.
  322. ///
  323. /// The reader supports two file formats: text and binary. The text format
  324. /// is useful for debugging and testing, while the binary format is more
  325. /// compact and I/O efficient. They can both be used interchangeably.
  326. class SampleProfileReader {
  327. public:
  328. SampleProfileReader(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
  329. SampleProfileFormat Format = SPF_None)
  330. : Profiles(0), Ctx(C), Buffer(std::move(B)), Format(Format) {}
  331. virtual ~SampleProfileReader() = default;
  332. /// Read and validate the file header.
  333. virtual std::error_code readHeader() = 0;
  334. /// The interface to read sample profiles from the associated file.
  335. std::error_code read() {
  336. if (std::error_code EC = readImpl())
  337. return EC;
  338. if (Remapper)
  339. Remapper->applyRemapping(Ctx);
  340. FunctionSamples::UseMD5 = useMD5();
  341. return sampleprof_error::success;
  342. }
  343. /// The implementaion to read sample profiles from the associated file.
  344. virtual std::error_code readImpl() = 0;
  345. /// Print the profile for \p FName on stream \p OS.
  346. void dumpFunctionProfile(StringRef FName, raw_ostream &OS = dbgs());
  347. /// Collect functions with definitions in Module M. For reader which
  348. /// support loading function profiles on demand, return true when the
  349. /// reader has been given a module. Always return false for reader
  350. /// which doesn't support loading function profiles on demand.
  351. virtual bool collectFuncsFromModule() { return false; }
  352. /// Print all the profiles on stream \p OS.
  353. void dump(raw_ostream &OS = dbgs());
  354. /// Return the samples collected for function \p F.
  355. FunctionSamples *getSamplesFor(const Function &F) {
  356. // The function name may have been updated by adding suffix. Call
  357. // a helper to (optionally) strip off suffixes so that we can
  358. // match against the original function name in the profile.
  359. StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
  360. return getSamplesFor(CanonName);
  361. }
  362. /// Return the samples collected for function \p F, create empty
  363. /// FunctionSamples if it doesn't exist.
  364. FunctionSamples *getOrCreateSamplesFor(const Function &F) {
  365. std::string FGUID;
  366. StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
  367. CanonName = getRepInFormat(CanonName, useMD5(), FGUID);
  368. return &Profiles[CanonName];
  369. }
  370. /// Return the samples collected for function \p F.
  371. virtual FunctionSamples *getSamplesFor(StringRef Fname) {
  372. std::string FGUID;
  373. Fname = getRepInFormat(Fname, useMD5(), FGUID);
  374. auto It = Profiles.find(Fname);
  375. if (It != Profiles.end())
  376. return &It->second;
  377. if (Remapper) {
  378. if (auto NameInProfile = Remapper->lookUpNameInProfile(Fname)) {
  379. auto It = Profiles.find(*NameInProfile);
  380. if (It != Profiles.end())
  381. return &It->second;
  382. }
  383. }
  384. return nullptr;
  385. }
  386. /// Return all the profiles.
  387. StringMap<FunctionSamples> &getProfiles() { return Profiles; }
  388. /// Report a parse error message.
  389. void reportError(int64_t LineNumber, const Twine &Msg) const {
  390. Ctx.diagnose(DiagnosticInfoSampleProfile(Buffer->getBufferIdentifier(),
  391. LineNumber, Msg));
  392. }
  393. /// Create a sample profile reader appropriate to the file format.
  394. /// Create a remapper underlying if RemapFilename is not empty.
  395. static ErrorOr<std::unique_ptr<SampleProfileReader>>
  396. create(const std::string Filename, LLVMContext &C,
  397. const std::string RemapFilename = "");
  398. /// Create a sample profile reader from the supplied memory buffer.
  399. /// Create a remapper underlying if RemapFilename is not empty.
  400. static ErrorOr<std::unique_ptr<SampleProfileReader>>
  401. create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
  402. const std::string RemapFilename = "");
  403. /// Return the profile summary.
  404. ProfileSummary &getSummary() const { return *(Summary.get()); }
  405. MemoryBuffer *getBuffer() const { return Buffer.get(); }
  406. /// \brief Return the profile format.
  407. SampleProfileFormat getFormat() const { return Format; }
  408. /// Whether input profile is based on pseudo probes.
  409. bool profileIsProbeBased() const { return ProfileIsProbeBased; }
  410. /// Whether input profile is fully context-sensitive
  411. bool profileIsCS() const { return ProfileIsCS; }
  412. virtual std::unique_ptr<ProfileSymbolList> getProfileSymbolList() {
  413. return nullptr;
  414. };
  415. /// It includes all the names that have samples either in outline instance
  416. /// or inline instance.
  417. virtual std::vector<StringRef> *getNameTable() { return nullptr; }
  418. virtual bool dumpSectionInfo(raw_ostream &OS = dbgs()) { return false; };
  419. /// Return whether names in the profile are all MD5 numbers.
  420. virtual bool useMD5() { return false; }
  421. /// Don't read profile without context if the flag is set. This is only meaningful
  422. /// for ExtBinary format.
  423. virtual void setSkipFlatProf(bool Skip) {}
  424. /// Return whether any name in the profile contains ".__uniq." suffix.
  425. virtual bool hasUniqSuffix() { return false; }
  426. SampleProfileReaderItaniumRemapper *getRemapper() { return Remapper.get(); }
  427. void setModule(const Module *Mod) { M = Mod; }
  428. protected:
  429. /// Map every function to its associated profile.
  430. ///
  431. /// The profile of every function executed at runtime is collected
  432. /// in the structure FunctionSamples. This maps function objects
  433. /// to their corresponding profiles.
  434. StringMap<FunctionSamples> Profiles;
  435. /// LLVM context used to emit diagnostics.
  436. LLVMContext &Ctx;
  437. /// Memory buffer holding the profile file.
  438. std::unique_ptr<MemoryBuffer> Buffer;
  439. /// Profile summary information.
  440. std::unique_ptr<ProfileSummary> Summary;
  441. /// Take ownership of the summary of this reader.
  442. static std::unique_ptr<ProfileSummary>
  443. takeSummary(SampleProfileReader &Reader) {
  444. return std::move(Reader.Summary);
  445. }
  446. /// Compute summary for this profile.
  447. void computeSummary();
  448. std::unique_ptr<SampleProfileReaderItaniumRemapper> Remapper;
  449. /// \brief Whether samples are collected based on pseudo probes.
  450. bool ProfileIsProbeBased = false;
  451. /// Whether function profiles are context-sensitive.
  452. bool ProfileIsCS = false;
  453. /// Number of context-sensitive profiles.
  454. uint32_t CSProfileCount = 0;
  455. /// \brief The format of sample.
  456. SampleProfileFormat Format = SPF_None;
  457. /// \brief The current module being compiled if SampleProfileReader
  458. /// is used by compiler. If SampleProfileReader is used by other
  459. /// tools which are not compiler, M is usually nullptr.
  460. const Module *M = nullptr;
  461. };
  462. class SampleProfileReaderText : public SampleProfileReader {
  463. public:
  464. SampleProfileReaderText(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
  465. : SampleProfileReader(std::move(B), C, SPF_Text) {}
  466. /// Read and validate the file header.
  467. std::error_code readHeader() override { return sampleprof_error::success; }
  468. /// Read sample profiles from the associated file.
  469. std::error_code readImpl() override;
  470. /// Return true if \p Buffer is in the format supported by this class.
  471. static bool hasFormat(const MemoryBuffer &Buffer);
  472. };
  473. class SampleProfileReaderBinary : public SampleProfileReader {
  474. public:
  475. SampleProfileReaderBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
  476. SampleProfileFormat Format = SPF_None)
  477. : SampleProfileReader(std::move(B), C, Format) {}
  478. /// Read and validate the file header.
  479. virtual std::error_code readHeader() override;
  480. /// Read sample profiles from the associated file.
  481. std::error_code readImpl() override;
  482. /// It includes all the names that have samples either in outline instance
  483. /// or inline instance.
  484. virtual std::vector<StringRef> *getNameTable() override { return &NameTable; }
  485. protected:
  486. /// Read a numeric value of type T from the profile.
  487. ///
  488. /// If an error occurs during decoding, a diagnostic message is emitted and
  489. /// EC is set.
  490. ///
  491. /// \returns the read value.
  492. template <typename T> ErrorOr<T> readNumber();
  493. /// Read a numeric value of type T from the profile. The value is saved
  494. /// without encoded.
  495. template <typename T> ErrorOr<T> readUnencodedNumber();
  496. /// Read a string from the profile.
  497. ///
  498. /// If an error occurs during decoding, a diagnostic message is emitted and
  499. /// EC is set.
  500. ///
  501. /// \returns the read value.
  502. ErrorOr<StringRef> readString();
  503. /// Read the string index and check whether it overflows the table.
  504. template <typename T> inline ErrorOr<uint32_t> readStringIndex(T &Table);
  505. /// Return true if we've reached the end of file.
  506. bool at_eof() const { return Data >= End; }
  507. /// Read the next function profile instance.
  508. std::error_code readFuncProfile(const uint8_t *Start);
  509. /// Read the contents of the given profile instance.
  510. std::error_code readProfile(FunctionSamples &FProfile);
  511. /// Read the contents of Magic number and Version number.
  512. std::error_code readMagicIdent();
  513. /// Read profile summary.
  514. std::error_code readSummary();
  515. /// Read the whole name table.
  516. virtual std::error_code readNameTable();
  517. /// Points to the current location in the buffer.
  518. const uint8_t *Data = nullptr;
  519. /// Points to the end of the buffer.
  520. const uint8_t *End = nullptr;
  521. /// Function name table.
  522. std::vector<StringRef> NameTable;
  523. /// Read a string indirectly via the name table.
  524. virtual ErrorOr<StringRef> readStringFromTable();
  525. private:
  526. std::error_code readSummaryEntry(std::vector<ProfileSummaryEntry> &Entries);
  527. virtual std::error_code verifySPMagic(uint64_t Magic) = 0;
  528. };
  529. class SampleProfileReaderRawBinary : public SampleProfileReaderBinary {
  530. private:
  531. virtual std::error_code verifySPMagic(uint64_t Magic) override;
  532. public:
  533. SampleProfileReaderRawBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
  534. SampleProfileFormat Format = SPF_Binary)
  535. : SampleProfileReaderBinary(std::move(B), C, Format) {}
  536. /// \brief Return true if \p Buffer is in the format supported by this class.
  537. static bool hasFormat(const MemoryBuffer &Buffer);
  538. };
  539. /// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase defines
  540. /// the basic structure of the extensible binary format.
  541. /// The format is organized in sections except the magic and version number
  542. /// at the beginning. There is a section table before all the sections, and
  543. /// each entry in the table describes the entry type, start, size and
  544. /// attributes. The format in each section is defined by the section itself.
  545. ///
  546. /// It is easy to add a new section while maintaining the backward
  547. /// compatibility of the profile. Nothing extra needs to be done. If we want
  548. /// to extend an existing section, like add cache misses information in
  549. /// addition to the sample count in the profile body, we can add a new section
  550. /// with the extension and retire the existing section, and we could choose
  551. /// to keep the parser of the old section if we want the reader to be able
  552. /// to read both new and old format profile.
  553. ///
  554. /// SampleProfileReaderExtBinary/SampleProfileWriterExtBinary define the
  555. /// commonly used sections of a profile in extensible binary format. It is
  556. /// possible to define other types of profile inherited from
  557. /// SampleProfileReaderExtBinaryBase/SampleProfileWriterExtBinaryBase.
  558. class SampleProfileReaderExtBinaryBase : public SampleProfileReaderBinary {
  559. private:
  560. std::error_code decompressSection(const uint8_t *SecStart,
  561. const uint64_t SecSize,
  562. const uint8_t *&DecompressBuf,
  563. uint64_t &DecompressBufSize);
  564. BumpPtrAllocator Allocator;
  565. protected:
  566. std::vector<SecHdrTableEntry> SecHdrTable;
  567. std::error_code readSecHdrTableEntry(uint32_t Idx);
  568. std::error_code readSecHdrTable();
  569. std::error_code readFuncMetadata(bool ProfileHasAttribute);
  570. std::error_code readFuncOffsetTable();
  571. std::error_code readFuncProfiles();
  572. std::error_code readMD5NameTable();
  573. std::error_code readNameTableSec(bool IsMD5);
  574. std::error_code readProfileSymbolList();
  575. virtual std::error_code readHeader() override;
  576. virtual std::error_code verifySPMagic(uint64_t Magic) override = 0;
  577. virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size,
  578. const SecHdrTableEntry &Entry);
  579. // placeholder for subclasses to dispatch their own section readers.
  580. virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry) = 0;
  581. virtual ErrorOr<StringRef> readStringFromTable() override;
  582. std::unique_ptr<ProfileSymbolList> ProfSymList;
  583. /// The table mapping from function name to the offset of its FunctionSample
  584. /// towards file start.
  585. DenseMap<StringRef, uint64_t> FuncOffsetTable;
  586. /// The set containing the functions to use when compiling a module.
  587. DenseSet<StringRef> FuncsToUse;
  588. /// Use fixed length MD5 instead of ULEB128 encoding so NameTable doesn't
  589. /// need to be read in up front and can be directly accessed using index.
  590. bool FixedLengthMD5 = false;
  591. /// The starting address of NameTable containing fixed length MD5.
  592. const uint8_t *MD5NameMemStart = nullptr;
  593. /// If MD5 is used in NameTable section, the section saves uint64_t data.
  594. /// The uint64_t data has to be converted to a string and then the string
  595. /// will be used to initialize StringRef in NameTable.
  596. /// Note NameTable contains StringRef so it needs another buffer to own
  597. /// the string data. MD5StringBuf serves as the string buffer that is
  598. /// referenced by NameTable (vector of StringRef). We make sure
  599. /// the lifetime of MD5StringBuf is not shorter than that of NameTable.
  600. std::unique_ptr<std::vector<std::string>> MD5StringBuf;
  601. /// If SkipFlatProf is true, skip the sections with
  602. /// SecFlagFlat flag.
  603. bool SkipFlatProf = false;
  604. public:
  605. SampleProfileReaderExtBinaryBase(std::unique_ptr<MemoryBuffer> B,
  606. LLVMContext &C, SampleProfileFormat Format)
  607. : SampleProfileReaderBinary(std::move(B), C, Format) {}
  608. /// Read sample profiles in extensible format from the associated file.
  609. std::error_code readImpl() override;
  610. /// Get the total size of all \p Type sections.
  611. uint64_t getSectionSize(SecType Type);
  612. /// Get the total size of header and all sections.
  613. uint64_t getFileSize();
  614. virtual bool dumpSectionInfo(raw_ostream &OS = dbgs()) override;
  615. /// Collect functions with definitions in Module M. Return true if
  616. /// the reader has been given a module.
  617. bool collectFuncsFromModule() override;
  618. /// Return whether names in the profile are all MD5 numbers.
  619. virtual bool useMD5() override { return MD5StringBuf.get(); }
  620. virtual std::unique_ptr<ProfileSymbolList> getProfileSymbolList() override {
  621. return std::move(ProfSymList);
  622. };
  623. virtual void setSkipFlatProf(bool Skip) override { SkipFlatProf = Skip; }
  624. };
  625. class SampleProfileReaderExtBinary : public SampleProfileReaderExtBinaryBase {
  626. private:
  627. virtual std::error_code verifySPMagic(uint64_t Magic) override;
  628. virtual std::error_code
  629. readCustomSection(const SecHdrTableEntry &Entry) override {
  630. return sampleprof_error::success;
  631. };
  632. public:
  633. SampleProfileReaderExtBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C,
  634. SampleProfileFormat Format = SPF_Ext_Binary)
  635. : SampleProfileReaderExtBinaryBase(std::move(B), C, Format) {}
  636. /// \brief Return true if \p Buffer is in the format supported by this class.
  637. static bool hasFormat(const MemoryBuffer &Buffer);
  638. };
  639. class SampleProfileReaderCompactBinary : public SampleProfileReaderBinary {
  640. private:
  641. /// Function name table.
  642. std::vector<std::string> NameTable;
  643. /// The table mapping from function name to the offset of its FunctionSample
  644. /// towards file start.
  645. DenseMap<StringRef, uint64_t> FuncOffsetTable;
  646. /// The set containing the functions to use when compiling a module.
  647. DenseSet<StringRef> FuncsToUse;
  648. virtual std::error_code verifySPMagic(uint64_t Magic) override;
  649. virtual std::error_code readNameTable() override;
  650. /// Read a string indirectly via the name table.
  651. virtual ErrorOr<StringRef> readStringFromTable() override;
  652. virtual std::error_code readHeader() override;
  653. std::error_code readFuncOffsetTable();
  654. public:
  655. SampleProfileReaderCompactBinary(std::unique_ptr<MemoryBuffer> B,
  656. LLVMContext &C)
  657. : SampleProfileReaderBinary(std::move(B), C, SPF_Compact_Binary) {}
  658. /// \brief Return true if \p Buffer is in the format supported by this class.
  659. static bool hasFormat(const MemoryBuffer &Buffer);
  660. /// Read samples only for functions to use.
  661. std::error_code readImpl() override;
  662. /// Collect functions with definitions in Module M. Return true if
  663. /// the reader has been given a module.
  664. bool collectFuncsFromModule() override;
  665. /// Return whether names in the profile are all MD5 numbers.
  666. virtual bool useMD5() override { return true; }
  667. };
  668. using InlineCallStack = SmallVector<FunctionSamples *, 10>;
  669. // Supported histogram types in GCC. Currently, we only need support for
  670. // call target histograms.
  671. enum HistType {
  672. HIST_TYPE_INTERVAL,
  673. HIST_TYPE_POW2,
  674. HIST_TYPE_SINGLE_VALUE,
  675. HIST_TYPE_CONST_DELTA,
  676. HIST_TYPE_INDIR_CALL,
  677. HIST_TYPE_AVERAGE,
  678. HIST_TYPE_IOR,
  679. HIST_TYPE_INDIR_CALL_TOPN
  680. };
  681. class SampleProfileReaderGCC : public SampleProfileReader {
  682. public:
  683. SampleProfileReaderGCC(std::unique_ptr<MemoryBuffer> B, LLVMContext &C)
  684. : SampleProfileReader(std::move(B), C, SPF_GCC),
  685. GcovBuffer(Buffer.get()) {}
  686. /// Read and validate the file header.
  687. std::error_code readHeader() override;
  688. /// Read sample profiles from the associated file.
  689. std::error_code readImpl() override;
  690. /// Return true if \p Buffer is in the format supported by this class.
  691. static bool hasFormat(const MemoryBuffer &Buffer);
  692. protected:
  693. std::error_code readNameTable();
  694. std::error_code readOneFunctionProfile(const InlineCallStack &InlineStack,
  695. bool Update, uint32_t Offset);
  696. std::error_code readFunctionProfiles();
  697. std::error_code skipNextWord();
  698. template <typename T> ErrorOr<T> readNumber();
  699. ErrorOr<StringRef> readString();
  700. /// Read the section tag and check that it's the same as \p Expected.
  701. std::error_code readSectionTag(uint32_t Expected);
  702. /// GCOV buffer containing the profile.
  703. GCOVBuffer GcovBuffer;
  704. /// Function names in this profile.
  705. std::vector<std::string> Names;
  706. /// GCOV tags used to separate sections in the profile file.
  707. static const uint32_t GCOVTagAFDOFileNames = 0xaa000000;
  708. static const uint32_t GCOVTagAFDOFunction = 0xac000000;
  709. };
  710. } // end namespace sampleprof
  711. } // end namespace llvm
  712. #endif // LLVM_PROFILEDATA_SAMPLEPROFREADER_H