SampleProfReader.h 35 KB

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