SampleProfWriter.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- SampleProfWriter.h - Write 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 writing sample profiles.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_PROFILEDATA_SAMPLEPROFWRITER_H
  18. #define LLVM_PROFILEDATA_SAMPLEPROFWRITER_H
  19. #include "llvm/ADT/MapVector.h"
  20. #include "llvm/ADT/StringMap.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/StringSet.h"
  23. #include "llvm/IR/ProfileSummary.h"
  24. #include "llvm/ProfileData/SampleProf.h"
  25. #include "llvm/Support/ErrorOr.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm>
  28. #include <cstdint>
  29. #include <memory>
  30. #include <set>
  31. #include <system_error>
  32. namespace llvm {
  33. namespace sampleprof {
  34. enum SectionLayout {
  35. DefaultLayout,
  36. // The layout splits profile with context information from profile without
  37. // context information. When Thinlto is enabled, ThinLTO postlink phase only
  38. // has to load profile with context information and can skip the other part.
  39. CtxSplitLayout,
  40. NumOfLayout,
  41. };
  42. /// Sample-based profile writer. Base class.
  43. class SampleProfileWriter {
  44. public:
  45. virtual ~SampleProfileWriter() = default;
  46. /// Write sample profiles in \p S.
  47. ///
  48. /// \returns status code of the file update operation.
  49. virtual std::error_code writeSample(const FunctionSamples &S) = 0;
  50. /// Write all the sample profiles in the given map of samples.
  51. ///
  52. /// \returns status code of the file update operation.
  53. virtual std::error_code write(const StringMap<FunctionSamples> &ProfileMap);
  54. raw_ostream &getOutputStream() { return *OutputStream; }
  55. /// Profile writer factory.
  56. ///
  57. /// Create a new file writer based on the value of \p Format.
  58. static ErrorOr<std::unique_ptr<SampleProfileWriter>>
  59. create(StringRef Filename, SampleProfileFormat Format);
  60. /// Create a new stream writer based on the value of \p Format.
  61. /// For testing.
  62. static ErrorOr<std::unique_ptr<SampleProfileWriter>>
  63. create(std::unique_ptr<raw_ostream> &OS, SampleProfileFormat Format);
  64. virtual void setProfileSymbolList(ProfileSymbolList *PSL) {}
  65. virtual void setToCompressAllSections() {}
  66. virtual void setUseMD5() {}
  67. virtual void setPartialProfile() {}
  68. virtual void resetSecLayout(SectionLayout SL) {}
  69. protected:
  70. SampleProfileWriter(std::unique_ptr<raw_ostream> &OS)
  71. : OutputStream(std::move(OS)) {}
  72. /// Write a file header for the profile file.
  73. virtual std::error_code
  74. writeHeader(const StringMap<FunctionSamples> &ProfileMap) = 0;
  75. // Write function profiles to the profile file.
  76. virtual std::error_code
  77. writeFuncProfiles(const StringMap<FunctionSamples> &ProfileMap);
  78. /// Output stream where to emit the profile to.
  79. std::unique_ptr<raw_ostream> OutputStream;
  80. /// Profile summary.
  81. std::unique_ptr<ProfileSummary> Summary;
  82. /// Compute summary for this profile.
  83. void computeSummary(const StringMap<FunctionSamples> &ProfileMap);
  84. /// Profile format.
  85. SampleProfileFormat Format = SPF_None;
  86. };
  87. /// Sample-based profile writer (text format).
  88. class SampleProfileWriterText : public SampleProfileWriter {
  89. public:
  90. std::error_code writeSample(const FunctionSamples &S) override;
  91. protected:
  92. SampleProfileWriterText(std::unique_ptr<raw_ostream> &OS)
  93. : SampleProfileWriter(OS), Indent(0) {}
  94. std::error_code
  95. writeHeader(const StringMap<FunctionSamples> &ProfileMap) override {
  96. return sampleprof_error::success;
  97. }
  98. private:
  99. /// Indent level to use when writing.
  100. ///
  101. /// This is used when printing inlined callees.
  102. unsigned Indent;
  103. friend ErrorOr<std::unique_ptr<SampleProfileWriter>>
  104. SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
  105. SampleProfileFormat Format);
  106. };
  107. /// Sample-based profile writer (binary format).
  108. class SampleProfileWriterBinary : public SampleProfileWriter {
  109. public:
  110. SampleProfileWriterBinary(std::unique_ptr<raw_ostream> &OS)
  111. : SampleProfileWriter(OS) {}
  112. virtual std::error_code writeSample(const FunctionSamples &S) override;
  113. protected:
  114. virtual std::error_code writeMagicIdent(SampleProfileFormat Format);
  115. virtual std::error_code writeNameTable();
  116. virtual std::error_code
  117. writeHeader(const StringMap<FunctionSamples> &ProfileMap) override;
  118. std::error_code writeSummary();
  119. std::error_code writeNameIdx(StringRef FName);
  120. std::error_code writeBody(const FunctionSamples &S);
  121. inline void stablizeNameTable(std::set<StringRef> &V);
  122. MapVector<StringRef, uint32_t> NameTable;
  123. void addName(StringRef FName);
  124. void addNames(const FunctionSamples &S);
  125. private:
  126. friend ErrorOr<std::unique_ptr<SampleProfileWriter>>
  127. SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
  128. SampleProfileFormat Format);
  129. };
  130. class SampleProfileWriterRawBinary : public SampleProfileWriterBinary {
  131. using SampleProfileWriterBinary::SampleProfileWriterBinary;
  132. };
  133. const std::array<SmallVector<SecHdrTableEntry, 8>, NumOfLayout>
  134. ExtBinaryHdrLayoutTable = {
  135. // Note that SecFuncOffsetTable section is written after SecLBRProfile
  136. // in the profile, but is put before SecLBRProfile in SectionHdrLayout.
  137. // This is because sample reader follows the order in SectionHdrLayout
  138. // to read each section. To read function profiles on demand, sample
  139. // reader need to get the offset of each function profile first.
  140. //
  141. // DefaultLayout
  142. SmallVector<SecHdrTableEntry, 8>({{SecProfSummary, 0, 0, 0, 0},
  143. {SecNameTable, 0, 0, 0, 0},
  144. {SecFuncOffsetTable, 0, 0, 0, 0},
  145. {SecLBRProfile, 0, 0, 0, 0},
  146. {SecProfileSymbolList, 0, 0, 0, 0},
  147. {SecFuncMetadata, 0, 0, 0, 0}}),
  148. // CtxSplitLayout
  149. SmallVector<SecHdrTableEntry, 8>({{SecProfSummary, 0, 0, 0, 0},
  150. {SecNameTable, 0, 0, 0, 0},
  151. // profile with context
  152. // for next two sections
  153. {SecFuncOffsetTable, 0, 0, 0, 0},
  154. {SecLBRProfile, 0, 0, 0, 0},
  155. // profile without context
  156. // for next two sections
  157. {SecFuncOffsetTable, 0, 0, 0, 0},
  158. {SecLBRProfile, 0, 0, 0, 0},
  159. {SecProfileSymbolList, 0, 0, 0, 0},
  160. {SecFuncMetadata, 0, 0, 0, 0}}),
  161. };
  162. class SampleProfileWriterExtBinaryBase : public SampleProfileWriterBinary {
  163. using SampleProfileWriterBinary::SampleProfileWriterBinary;
  164. public:
  165. virtual std::error_code
  166. write(const StringMap<FunctionSamples> &ProfileMap) override;
  167. virtual void setToCompressAllSections() override;
  168. void setToCompressSection(SecType Type);
  169. virtual std::error_code writeSample(const FunctionSamples &S) override;
  170. // Set to use MD5 to represent string in NameTable.
  171. virtual void setUseMD5() override {
  172. UseMD5 = true;
  173. addSectionFlag(SecNameTable, SecNameTableFlags::SecFlagMD5Name);
  174. // MD5 will be stored as plain uint64_t instead of variable-length
  175. // quantity format in NameTable section.
  176. addSectionFlag(SecNameTable, SecNameTableFlags::SecFlagFixedLengthMD5);
  177. }
  178. // Set the profile to be partial. It means the profile is for
  179. // common/shared code. The common profile is usually merged from
  180. // profiles collected from running other targets.
  181. virtual void setPartialProfile() override {
  182. addSectionFlag(SecProfSummary, SecProfSummaryFlags::SecFlagPartial);
  183. }
  184. virtual void setProfileSymbolList(ProfileSymbolList *PSL) override {
  185. ProfSymList = PSL;
  186. };
  187. virtual void resetSecLayout(SectionLayout SL) override {
  188. verifySecLayout(SL);
  189. #ifndef NDEBUG
  190. // Make sure resetSecLayout is called before any flag setting.
  191. for (auto &Entry : SectionHdrLayout) {
  192. assert(Entry.Flags == 0 &&
  193. "resetSecLayout has to be called before any flag setting");
  194. }
  195. #endif
  196. SecLayout = SL;
  197. SectionHdrLayout = ExtBinaryHdrLayoutTable[SL];
  198. }
  199. protected:
  200. uint64_t markSectionStart(SecType Type, uint32_t LayoutIdx);
  201. std::error_code addNewSection(SecType Sec, uint32_t LayoutIdx,
  202. uint64_t SectionStart);
  203. template <class SecFlagType>
  204. void addSectionFlag(SecType Type, SecFlagType Flag) {
  205. for (auto &Entry : SectionHdrLayout) {
  206. if (Entry.Type == Type)
  207. addSecFlag(Entry, Flag);
  208. }
  209. }
  210. template <class SecFlagType>
  211. void addSectionFlag(uint32_t SectionIdx, SecFlagType Flag) {
  212. addSecFlag(SectionHdrLayout[SectionIdx], Flag);
  213. }
  214. // placeholder for subclasses to dispatch their own section writers.
  215. virtual std::error_code writeCustomSection(SecType Type) = 0;
  216. // Verify the SecLayout is supported by the format.
  217. virtual void verifySecLayout(SectionLayout SL) = 0;
  218. // specify the order to write sections.
  219. virtual std::error_code
  220. writeSections(const StringMap<FunctionSamples> &ProfileMap) = 0;
  221. // Dispatch section writer for each section. \p LayoutIdx is the sequence
  222. // number indicating where the section is located in SectionHdrLayout.
  223. virtual std::error_code
  224. writeOneSection(SecType Type, uint32_t LayoutIdx,
  225. const StringMap<FunctionSamples> &ProfileMap);
  226. // Helper function to write name table.
  227. virtual std::error_code writeNameTable() override;
  228. std::error_code writeFuncMetadata(const StringMap<FunctionSamples> &Profiles);
  229. // Functions to write various kinds of sections.
  230. std::error_code
  231. writeNameTableSection(const StringMap<FunctionSamples> &ProfileMap);
  232. std::error_code writeFuncOffsetTable();
  233. std::error_code writeProfileSymbolListSection();
  234. SectionLayout SecLayout = DefaultLayout;
  235. // Specifiy the order of sections in section header table. Note
  236. // the order of sections in SecHdrTable may be different that the
  237. // order in SectionHdrLayout. sample Reader will follow the order
  238. // in SectionHdrLayout to read each section.
  239. SmallVector<SecHdrTableEntry, 8> SectionHdrLayout =
  240. ExtBinaryHdrLayoutTable[DefaultLayout];
  241. // Save the start of SecLBRProfile so we can compute the offset to the
  242. // start of SecLBRProfile for each Function's Profile and will keep it
  243. // in FuncOffsetTable.
  244. uint64_t SecLBRProfileStart = 0;
  245. private:
  246. void allocSecHdrTable();
  247. std::error_code writeSecHdrTable();
  248. virtual std::error_code
  249. writeHeader(const StringMap<FunctionSamples> &ProfileMap) override;
  250. std::error_code compressAndOutput();
  251. // We will swap the raw_ostream held by LocalBufStream and that
  252. // held by OutputStream if we try to add a section which needs
  253. // compression. After the swap, all the data written to output
  254. // will be temporarily buffered into the underlying raw_string_ostream
  255. // originally held by LocalBufStream. After the data writing for the
  256. // section is completed, compress the data in the local buffer,
  257. // swap the raw_ostream back and write the compressed data to the
  258. // real output.
  259. std::unique_ptr<raw_ostream> LocalBufStream;
  260. // The location where the output stream starts.
  261. uint64_t FileStart;
  262. // The location in the output stream where the SecHdrTable should be
  263. // written to.
  264. uint64_t SecHdrTableOffset;
  265. // The table contains SecHdrTableEntry entries in order of how they are
  266. // populated in the writer. It may be different from the order in
  267. // SectionHdrLayout which specifies the sequence in which sections will
  268. // be read.
  269. std::vector<SecHdrTableEntry> SecHdrTable;
  270. // FuncOffsetTable maps function name to its profile offset in SecLBRProfile
  271. // section. It is used to load function profile on demand.
  272. MapVector<StringRef, uint64_t> FuncOffsetTable;
  273. // Whether to use MD5 to represent string.
  274. bool UseMD5 = false;
  275. ProfileSymbolList *ProfSymList = nullptr;
  276. };
  277. class SampleProfileWriterExtBinary : public SampleProfileWriterExtBinaryBase {
  278. public:
  279. SampleProfileWriterExtBinary(std::unique_ptr<raw_ostream> &OS)
  280. : SampleProfileWriterExtBinaryBase(OS) {}
  281. private:
  282. std::error_code
  283. writeDefaultLayout(const StringMap<FunctionSamples> &ProfileMap);
  284. std::error_code
  285. writeCtxSplitLayout(const StringMap<FunctionSamples> &ProfileMap);
  286. virtual std::error_code
  287. writeSections(const StringMap<FunctionSamples> &ProfileMap) override;
  288. virtual std::error_code writeCustomSection(SecType Type) override {
  289. return sampleprof_error::success;
  290. };
  291. virtual void verifySecLayout(SectionLayout SL) override {
  292. assert((SL == DefaultLayout || SL == CtxSplitLayout) &&
  293. "Unsupported layout");
  294. }
  295. };
  296. // CompactBinary is a compact format of binary profile which both reduces
  297. // the profile size and the load time needed when compiling. It has two
  298. // major difference with Binary format.
  299. // 1. It represents all the strings in name table using md5 hash.
  300. // 2. It saves a function offset table which maps function name index to
  301. // the offset of its function profile to the start of the binary profile,
  302. // so by using the function offset table, for those function profiles which
  303. // will not be needed when compiling a module, the profile reader does't
  304. // have to read them and it saves compile time if the profile size is huge.
  305. // The layout of the compact format is shown as follows:
  306. //
  307. // Part1: Profile header, the same as binary format, containing magic
  308. // number, version, summary, name table...
  309. // Part2: Function Offset Table Offset, which saves the position of
  310. // Part4.
  311. // Part3: Function profile collection
  312. // function1 profile start
  313. // ....
  314. // function2 profile start
  315. // ....
  316. // function3 profile start
  317. // ....
  318. // ......
  319. // Part4: Function Offset Table
  320. // function1 name index --> function1 profile start
  321. // function2 name index --> function2 profile start
  322. // function3 name index --> function3 profile start
  323. //
  324. // We need Part2 because profile reader can use it to find out and read
  325. // function offset table without reading Part3 first.
  326. class SampleProfileWriterCompactBinary : public SampleProfileWriterBinary {
  327. using SampleProfileWriterBinary::SampleProfileWriterBinary;
  328. public:
  329. virtual std::error_code writeSample(const FunctionSamples &S) override;
  330. virtual std::error_code
  331. write(const StringMap<FunctionSamples> &ProfileMap) override;
  332. protected:
  333. /// The table mapping from function name to the offset of its FunctionSample
  334. /// towards profile start.
  335. MapVector<StringRef, uint64_t> FuncOffsetTable;
  336. /// The offset of the slot to be filled with the offset of FuncOffsetTable
  337. /// towards profile start.
  338. uint64_t TableOffset;
  339. virtual std::error_code writeNameTable() override;
  340. virtual std::error_code
  341. writeHeader(const StringMap<FunctionSamples> &ProfileMap) override;
  342. std::error_code writeFuncOffsetTable();
  343. };
  344. } // end namespace sampleprof
  345. } // end namespace llvm
  346. #endif // LLVM_PROFILEDATA_SAMPLEPROFWRITER_H
  347. #ifdef __GNUC__
  348. #pragma GCC diagnostic pop
  349. #endif