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