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 SampleProfileMap &ProfileMap); 56 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 70 virtual void setProfileSymbolList(ProfileSymbolList *PSL) {} 71 virtual void setToCompressAllSections() {} 72 virtual void setUseMD5() {} 73 virtual void setPartialProfile() {} 74 virtual void resetSecLayout(SectionLayout SL) {} 75 76 protected: 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 writeHeader(const SampleProfileMap &ProfileMap) = 0; 82 83 // Write function profiles to the profile file. 84 virtual std::error_code writeFuncProfiles(const SampleProfileMap &ProfileMap); 85 86 /// Output stream where to emit the profile to. 87 std::unique_ptr<raw_ostream> OutputStream; 88 89 /// Profile summary. 90 std::unique_ptr<ProfileSummary> Summary; 91 92 /// Compute summary for this profile. 93 void computeSummary(const SampleProfileMap &ProfileMap); 94 95 /// Profile format. 96 SampleProfileFormat Format = SPF_None; 97 }; 98 99 /// Sample-based profile writer (text format). 100 class SampleProfileWriterText : public SampleProfileWriter { 101 public: 102 std::error_code writeSample(const FunctionSamples &S) override; 103 104 protected: 105 SampleProfileWriterText(std::unique_ptr<raw_ostream> &OS) 106 : SampleProfileWriter(OS), Indent(0) {} 107 108 std::error_code writeHeader(const SampleProfileMap &ProfileMap) override { 109 return sampleprof_error::success; 110 } 111 112 private: 113 /// Indent level to use when writing. 114 /// 115 /// This is used when printing inlined callees. 116 unsigned Indent; 117 118 friend ErrorOr<std::unique_ptr<SampleProfileWriter>> 119 SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS, 120 SampleProfileFormat Format); 121 }; 122 123 /// Sample-based profile writer (binary format). 124 class SampleProfileWriterBinary : public SampleProfileWriter { 125 public: 126 SampleProfileWriterBinary(std::unique_ptr<raw_ostream> &OS) 127 : SampleProfileWriter(OS) {} 128 129 virtual std::error_code writeSample(const FunctionSamples &S) override; 130 131 protected: 132 virtual MapVector<StringRef, uint32_t> &getNameTable() { return NameTable; } 133 virtual std::error_code writeMagicIdent(SampleProfileFormat Format); 134 virtual std::error_code writeNameTable(); 135 virtual std::error_code 136 writeHeader(const SampleProfileMap &ProfileMap) override; 137 std::error_code writeSummary(); 138 virtual std::error_code writeContextIdx(const SampleContext &Context); 139 std::error_code writeNameIdx(StringRef FName); 140 std::error_code writeBody(const FunctionSamples &S); 141 inline void stablizeNameTable(MapVector<StringRef, uint32_t> &NameTable, 142 std::set<StringRef> &V); 143 144 MapVector<StringRef, uint32_t> NameTable; 145 146 void addName(StringRef FName); 147 virtual void addContext(const SampleContext &Context); 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 {SecCSNameTable, 0, 0, 0, 0}, 172 {SecFuncOffsetTable, 0, 0, 0, 0}, 173 {SecLBRProfile, 0, 0, 0, 0}, 174 {SecProfileSymbolList, 0, 0, 0, 0}, 175 {SecFuncMetadata, 0, 0, 0, 0}}), 176 // CtxSplitLayout 177 SmallVector<SecHdrTableEntry, 8>({{SecProfSummary, 0, 0, 0, 0}, 178 {SecNameTable, 0, 0, 0, 0}, 179 // profile with context 180 // for next two sections 181 {SecFuncOffsetTable, 0, 0, 0, 0}, 182 {SecLBRProfile, 0, 0, 0, 0}, 183 // profile without context 184 // for next two sections 185 {SecFuncOffsetTable, 0, 0, 0, 0}, 186 {SecLBRProfile, 0, 0, 0, 0}, 187 {SecProfileSymbolList, 0, 0, 0, 0}, 188 {SecFuncMetadata, 0, 0, 0, 0}}), 189 }; 190 191 class SampleProfileWriterExtBinaryBase : public SampleProfileWriterBinary { 192 using SampleProfileWriterBinary::SampleProfileWriterBinary; 193 public: 194 virtual std::error_code write(const SampleProfileMap &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. 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. 212 virtual void setPartialProfile() override { 213 addSectionFlag(SecProfSummary, SecProfSummaryFlags::SecFlagPartial); 214 } 215 216 virtual void setProfileSymbolList(ProfileSymbolList *PSL) override { 217 ProfSymList = PSL; 218 }; 219 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> 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> 245 void addSectionFlag(uint32_t SectionIdx, SecFlagType Flag) { 246 addSecFlag(SectionHdrLayout[SectionIdx], Flag); 247 } 248 249 virtual void addContext(const SampleContext &Context) override; 250 251 // placeholder for subclasses to dispatch their own section writers. 252 virtual std::error_code writeCustomSection(SecType Type) = 0; 253 // Verify the SecLayout is supported by the format. 254 virtual void verifySecLayout(SectionLayout SL) = 0; 255 256 // specify the order to write sections. 257 virtual std::error_code writeSections(const SampleProfileMap &ProfileMap) = 0; 258 259 // Dispatch section writer for each section. \p LayoutIdx is the sequence 260 // number indicating where the section is located in SectionHdrLayout. 261 virtual std::error_code writeOneSection(SecType Type, uint32_t LayoutIdx, 262 const SampleProfileMap &ProfileMap); 263 264 // Helper function to write name table. 265 virtual std::error_code writeNameTable() override; 266 virtual std::error_code 267 writeContextIdx(const SampleContext &Context) override; 268 std::error_code writeCSNameIdx(const SampleContext &Context); 269 std::error_code writeCSNameTableSection(); 270 271 std::error_code writeFuncMetadata(const SampleProfileMap &Profiles); 272 273 // Functions to write various kinds of sections. 274 std::error_code writeNameTableSection(const SampleProfileMap &ProfileMap); 275 std::error_code writeFuncOffsetTable(); 276 std::error_code writeProfileSymbolListSection(); 277 278 SectionLayout SecLayout = DefaultLayout; 279 // Specifiy the order of sections in section header table. Note 280 // the order of sections in SecHdrTable may be different that the 281 // order in SectionHdrLayout. sample Reader will follow the order 282 // in SectionHdrLayout to read each section. 283 SmallVector<SecHdrTableEntry, 8> SectionHdrLayout = 284 ExtBinaryHdrLayoutTable[DefaultLayout]; 285 286 // Save the start of SecLBRProfile so we can compute the offset to the 287 // start of SecLBRProfile for each Function's Profile and will keep it 288 // in FuncOffsetTable. 289 uint64_t SecLBRProfileStart = 0; 290 291 private: 292 void allocSecHdrTable(); 293 std::error_code writeSecHdrTable(); 294 virtual std::error_code 295 writeHeader(const SampleProfileMap &ProfileMap) override; 296 std::error_code compressAndOutput(); 297 298 // We will swap the raw_ostream held by LocalBufStream and that 299 // held by OutputStream if we try to add a section which needs 300 // compression. After the swap, all the data written to output 301 // will be temporarily buffered into the underlying raw_string_ostream 302 // originally held by LocalBufStream. After the data writing for the 303 // section is completed, compress the data in the local buffer, 304 // swap the raw_ostream back and write the compressed data to the 305 // real output. 306 std::unique_ptr<raw_ostream> LocalBufStream; 307 // The location where the output stream starts. 308 uint64_t FileStart; 309 // The location in the output stream where the SecHdrTable should be 310 // written to. 311 uint64_t SecHdrTableOffset; 312 // The table contains SecHdrTableEntry entries in order of how they are 313 // populated in the writer. It may be different from the order in 314 // SectionHdrLayout which specifies the sequence in which sections will 315 // be read. 316 std::vector<SecHdrTableEntry> SecHdrTable; 317 318 // FuncOffsetTable maps function context to its profile offset in 319 // SecLBRProfile section. It is used to load function profile on demand. 320 MapVector<SampleContext, uint64_t> FuncOffsetTable; 321 // Whether to use MD5 to represent string. 322 bool UseMD5 = false; 323 324 /// CSNameTable maps function context to its offset in SecCSNameTable section. 325 /// The offset will be used everywhere where the context is referenced. 326 MapVector<SampleContext, uint32_t> CSNameTable; 327 328 ProfileSymbolList *ProfSymList = nullptr; 329 }; 330 331 class SampleProfileWriterExtBinary : public SampleProfileWriterExtBinaryBase { 332 public: 333 SampleProfileWriterExtBinary(std::unique_ptr<raw_ostream> &OS) 334 : SampleProfileWriterExtBinaryBase(OS) {} 335 336 private: 337 std::error_code writeDefaultLayout(const SampleProfileMap &ProfileMap); 338 std::error_code writeCtxSplitLayout(const SampleProfileMap &ProfileMap); 339 340 virtual std::error_code 341 writeSections(const SampleProfileMap &ProfileMap) override; 342 343 virtual std::error_code writeCustomSection(SecType Type) override { 344 return sampleprof_error::success; 345 }; 346 347 virtual void verifySecLayout(SectionLayout SL) override { 348 assert((SL == DefaultLayout || SL == CtxSplitLayout) && 349 "Unsupported layout"); 350 } 351 }; 352 353 // CompactBinary is a compact format of binary profile which both reduces 354 // the profile size and the load time needed when compiling. It has two 355 // major difference with Binary format. 356 // 1. It represents all the strings in name table using md5 hash. 357 // 2. It saves a function offset table which maps function name index to 358 // the offset of its function profile to the start of the binary profile, 359 // so by using the function offset table, for those function profiles which 360 // will not be needed when compiling a module, the profile reader does't 361 // have to read them and it saves compile time if the profile size is huge. 362 // The layout of the compact format is shown as follows: 363 // 364 // Part1: Profile header, the same as binary format, containing magic 365 // number, version, summary, name table... 366 // Part2: Function Offset Table Offset, which saves the position of 367 // Part4. 368 // Part3: Function profile collection 369 // function1 profile start 370 // .... 371 // function2 profile start 372 // .... 373 // function3 profile start 374 // .... 375 // ...... 376 // Part4: Function Offset Table 377 // function1 name index --> function1 profile start 378 // function2 name index --> function2 profile start 379 // function3 name index --> function3 profile start 380 // 381 // We need Part2 because profile reader can use it to find out and read 382 // function offset table without reading Part3 first. 383 class SampleProfileWriterCompactBinary : public SampleProfileWriterBinary { 384 using SampleProfileWriterBinary::SampleProfileWriterBinary; 385 386 public: 387 virtual std::error_code writeSample(const FunctionSamples &S) override; 388 virtual std::error_code write(const SampleProfileMap &ProfileMap) override; 389 390 protected: 391 /// The table mapping from function name to the offset of its FunctionSample 392 /// towards profile start. 393 MapVector<StringRef, uint64_t> FuncOffsetTable; 394 /// The offset of the slot to be filled with the offset of FuncOffsetTable 395 /// towards profile start. 396 uint64_t TableOffset; 397 virtual std::error_code writeNameTable() override; 398 virtual std::error_code 399 writeHeader(const SampleProfileMap &ProfileMap) override; 400 std::error_code writeFuncOffsetTable(); 401 }; 402 403 } // end namespace sampleprof 404 } // end namespace llvm 405 406 #endif // LLVM_PROFILEDATA_SAMPLEPROFWRITER_H 407