SampleProfReader.h 35 KB

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