LLVM 22.0.0git
SampleProfWriter.cpp
Go to the documentation of this file.
1//===- SampleProfWriter.cpp - Write LLVM sample profile data --------------===//
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 implements the class that writes LLVM sample profiles. It
10// supports two file formats: text and binary. The textual representation
11// is useful for debugging and testing purposes. The binary representation
12// is more compact, resulting in smaller file sizes. However, they can
13// both be used interchangeably.
14//
15// See lib/ProfileData/SampleProfReader.cpp for documentation on each of the
16// supported formats.
17//
18//===----------------------------------------------------------------------===//
19
21#include "llvm/ADT/StringRef.h"
28#include "llvm/Support/LEB128.h"
29#include "llvm/Support/MD5.h"
31#include <cmath>
32#include <cstdint>
33#include <memory>
34#include <set>
35#include <system_error>
36#include <utility>
37#include <vector>
38
39#define DEBUG_TYPE "llvm-profdata"
40
41using namespace llvm;
42using namespace sampleprof;
43
44// To begin with, make this option off by default.
46 "extbinary-write-vtable-type-prof", cl::init(false), cl::Hidden,
47 cl::desc("Write vtable type profile in ext-binary sample profile writer"));
48
49namespace llvm {
50namespace support {
51namespace endian {
52namespace {
53
54// Adapter class to llvm::support::endian::Writer for pwrite().
55struct SeekableWriter {
57 endianness Endian;
58 SeekableWriter(raw_pwrite_stream &OS, endianness Endian)
59 : OS(OS), Endian(Endian) {}
60
61 template <typename ValueType>
62 void pwrite(ValueType Val, size_t Offset) {
63 std::string StringBuf;
64 raw_string_ostream SStream(StringBuf);
65 Writer(SStream, Endian).write(Val);
66 OS.pwrite(StringBuf.data(), StringBuf.size(), Offset);
67 }
68};
69
70} // namespace
71} // namespace endian
72} // namespace support
73} // namespace llvm
74
80
81void DefaultFunctionPruningStrategy::Erase(size_t CurrentOutputSize) {
82 double D = (double)OutputSizeLimit / CurrentOutputSize;
83 size_t NewSize = (size_t)round(ProfileMap.size() * D * D);
84 size_t NumToRemove = ProfileMap.size() - NewSize;
85 if (NumToRemove < 1)
86 NumToRemove = 1;
87
88 assert(NumToRemove <= SortedFunctions.size());
89 for (const NameFunctionSamples &E :
90 llvm::drop_begin(SortedFunctions, SortedFunctions.size() - NumToRemove))
91 ProfileMap.erase(E.first);
92 SortedFunctions.resize(SortedFunctions.size() - NumToRemove);
93}
94
96 SampleProfileMap &ProfileMap, size_t OutputSizeLimit,
97 FunctionPruningStrategy *Strategy) {
98 if (OutputSizeLimit == 0)
99 return write(ProfileMap);
100
101 size_t OriginalFunctionCount = ProfileMap.size();
102
103 std::unique_ptr<raw_ostream> OriginalOutputStream;
104 OutputStream.swap(OriginalOutputStream);
105
106 size_t IterationCount = 0;
107 size_t TotalSize;
108
109 SmallVector<char> StringBuffer;
110 do {
111 StringBuffer.clear();
112 OutputStream.reset(new raw_svector_ostream(StringBuffer));
113 if (std::error_code EC = write(ProfileMap))
114 return EC;
115
116 TotalSize = StringBuffer.size();
117 // On Windows every "\n" is actually written as "\r\n" to disk but not to
118 // memory buffer, this difference should be added when considering the total
119 // output size.
120#ifdef _WIN32
121 if (Format == SPF_Text)
122 TotalSize += LineCount;
123#endif
124 if (TotalSize <= OutputSizeLimit)
125 break;
126
127 Strategy->Erase(TotalSize);
128 IterationCount++;
129 } while (ProfileMap.size() != 0);
130
131 if (ProfileMap.size() == 0)
133
134 OutputStream.swap(OriginalOutputStream);
135 OutputStream->write(StringBuffer.data(), StringBuffer.size());
136 LLVM_DEBUG(dbgs() << "Profile originally has " << OriginalFunctionCount
137 << " functions, reduced to " << ProfileMap.size() << " in "
138 << IterationCount << " iterations\n");
139 // Silence warning on Release build.
140 (void)OriginalFunctionCount;
141 (void)IterationCount;
143}
144
145std::error_code
147 std::vector<NameFunctionSamples> V;
148 sortFuncProfiles(ProfileMap, V);
149 for (const auto &I : V) {
150 if (std::error_code EC = writeSample(*I.second))
151 return EC;
152 }
154}
155
156std::error_code SampleProfileWriter::write(const SampleProfileMap &ProfileMap) {
157 if (std::error_code EC = writeHeader(ProfileMap))
158 return EC;
159
160 if (std::error_code EC = writeFuncProfiles(ProfileMap))
161 return EC;
162
164}
165
166/// Return the current position and prepare to use it as the start
167/// position of a section given the section type \p Type and its position
168/// \p LayoutIdx in SectionHdrLayout.
171 uint32_t LayoutIdx) {
172 uint64_t SectionStart = OutputStream->tell();
173 assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range");
174 const auto &Entry = SectionHdrLayout[LayoutIdx];
175 assert(Entry.Type == Type && "Unexpected section type");
176 // Use LocalBuf as a temporary output for writting data.
178 LocalBufStream.swap(OutputStream);
179 return SectionStart;
180}
181
182std::error_code SampleProfileWriterExtBinaryBase::compressAndOutput() {
185 std::string &UncompressedStrings =
186 static_cast<raw_string_ostream *>(LocalBufStream.get())->str();
187 if (UncompressedStrings.size() == 0)
189 auto &OS = *OutputStream;
190 SmallVector<uint8_t, 128> CompressedStrings;
192 CompressedStrings,
194 encodeULEB128(UncompressedStrings.size(), OS);
195 encodeULEB128(CompressedStrings.size(), OS);
196 OS << toStringRef(CompressedStrings);
197 UncompressedStrings.clear();
199}
200
201/// Add a new section into section header table given the section type
202/// \p Type, its position \p LayoutIdx in SectionHdrLayout and the
203/// location \p SectionStart where the section should be written to.
205 SecType Type, uint32_t LayoutIdx, uint64_t SectionStart) {
206 assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range");
207 const auto &Entry = SectionHdrLayout[LayoutIdx];
208 assert(Entry.Type == Type && "Unexpected section type");
210 LocalBufStream.swap(OutputStream);
211 if (std::error_code EC = compressAndOutput())
212 return EC;
213 }
214 SecHdrTable.push_back({Type, Entry.Flags, SectionStart - FileStart,
215 OutputStream->tell() - SectionStart, LayoutIdx});
217}
218
219std::error_code
221 // When calling write on a different profile map, existing states should be
222 // cleared.
223 NameTable.clear();
224 CSNameTable.clear();
225 SecHdrTable.clear();
226
227 if (std::error_code EC = writeHeader(ProfileMap))
228 return EC;
229
230 std::string LocalBuf;
231 LocalBufStream = std::make_unique<raw_string_ostream>(LocalBuf);
232 if (std::error_code EC = writeSections(ProfileMap))
233 return EC;
234
235 if (std::error_code EC = writeSecHdrTable())
236 return EC;
237
239}
240
242 const SampleContext &Context) {
243 if (Context.hasContext())
244 return writeCSNameIdx(Context);
245 else
246 return SampleProfileWriterBinary::writeNameIdx(Context.getFunction());
247}
248
249std::error_code
251 const auto &Ret = CSNameTable.find(Context);
252 if (Ret == CSNameTable.end())
254 encodeULEB128(Ret->second, *OutputStream);
256}
257
258std::error_code
260 uint64_t Offset = OutputStream->tell();
261 auto &Context = S.getContext();
262 FuncOffsetTable[Context] = Offset - SecLBRProfileStart;
264 return writeBody(S);
265}
266
268 auto &OS = *OutputStream;
269
270 // Write out the table size.
271 encodeULEB128(FuncOffsetTable.size(), OS);
272
273 // Write out FuncOffsetTable.
274 auto WriteItem = [&](const SampleContext &Context, uint64_t Offset) {
275 if (std::error_code EC = writeContextIdx(Context))
276 return EC;
278 return (std::error_code)sampleprof_error::success;
279 };
280
282 // Sort the contexts before writing them out. This is to help fast load all
283 // context profiles for a function as well as their callee contexts which
284 // can help profile-guided importing for ThinLTO.
285 std::map<SampleContext, uint64_t> OrderedFuncOffsetTable(
286 FuncOffsetTable.begin(), FuncOffsetTable.end());
287 for (const auto &Entry : OrderedFuncOffsetTable) {
288 if (std::error_code EC = WriteItem(Entry.first, Entry.second))
289 return EC;
290 }
292 } else {
293 for (const auto &Entry : FuncOffsetTable) {
294 if (std::error_code EC = WriteItem(Entry.first, Entry.second))
295 return EC;
296 }
297 }
298
299 FuncOffsetTable.clear();
301}
302
304 const FunctionSamples &FunctionProfile) {
305 auto &OS = *OutputStream;
306 if (std::error_code EC = writeContextIdx(FunctionProfile.getContext()))
307 return EC;
308
310 encodeULEB128(FunctionProfile.getFunctionHash(), OS);
312 encodeULEB128(FunctionProfile.getContext().getAllAttributes(), OS);
313 }
314
316 // Recursively emit attributes for all callee samples.
317 uint64_t NumCallsites = 0;
318 for (const auto &J : FunctionProfile.getCallsiteSamples())
319 NumCallsites += J.second.size();
320 encodeULEB128(NumCallsites, OS);
321 for (const auto &J : FunctionProfile.getCallsiteSamples()) {
322 for (const auto &FS : J.second) {
323 LineLocation Loc = J.first;
324 encodeULEB128(Loc.LineOffset, OS);
325 encodeULEB128(Loc.Discriminator, OS);
326 if (std::error_code EC = writeFuncMetadata(FS.second))
327 return EC;
328 }
329 }
330 }
331
333}
334
336 const SampleProfileMap &Profiles) {
340 for (const auto &Entry : Profiles) {
341 if (std::error_code EC = writeFuncMetadata(Entry.second))
342 return EC;
343 }
345}
346
348 if (!UseMD5)
350
351 auto &OS = *OutputStream;
352 std::set<FunctionId> V;
354
355 // Write out the MD5 name table. We wrote unencoded MD5 so reader can
356 // retrieve the name using the name index without having to read the
357 // whole name table.
358 encodeULEB128(NameTable.size(), OS);
360 for (auto N : V)
361 Writer.write(N.getHashCode());
363}
364
366 const SampleProfileMap &ProfileMap) {
367 for (const auto &I : ProfileMap) {
368 addContext(I.second.getContext());
369 addNames(I.second);
370 }
371
372 // If NameTable contains ".__uniq." suffix, set SecFlagUniqSuffix flag
373 // so compiler won't strip the suffix during profile matching after
374 // seeing the flag in the profile.
375 // Original names are unavailable if using MD5, so this option has no use.
376 if (!UseMD5) {
377 for (const auto &I : NameTable) {
378 if (I.first.stringRef().contains(FunctionSamples::UniqSuffix)) {
380 break;
381 }
382 }
383 }
384
385 if (auto EC = writeNameTable())
386 return EC;
388}
389
391 // Sort the names to make CSNameTable deterministic.
392 std::set<SampleContext> OrderedContexts;
393 for (const auto &I : CSNameTable)
394 OrderedContexts.insert(I.first);
395 assert(OrderedContexts.size() == CSNameTable.size() &&
396 "Unmatched ordered and unordered contexts");
397 uint64_t I = 0;
398 for (auto &Context : OrderedContexts)
399 CSNameTable[Context] = I++;
400
401 auto &OS = *OutputStream;
402 encodeULEB128(OrderedContexts.size(), OS);
404 for (auto Context : OrderedContexts) {
405 auto Frames = Context.getContextFrames();
406 encodeULEB128(Frames.size(), OS);
407 for (auto &Callsite : Frames) {
408 if (std::error_code EC = writeNameIdx(Callsite.Func))
409 return EC;
410 encodeULEB128(Callsite.Location.LineOffset, OS);
411 encodeULEB128(Callsite.Location.Discriminator, OS);
412 }
413 }
414
416}
417
418std::error_code
420 if (ProfSymList && ProfSymList->size() > 0)
421 if (std::error_code EC = ProfSymList->write(*OutputStream))
422 return EC;
423
425}
426
428 SecType Type, uint32_t LayoutIdx, const SampleProfileMap &ProfileMap) {
429 // The setting of SecFlagCompress should happen before markSectionStart.
430 if (Type == SecProfileSymbolList && ProfSymList && ProfSymList->toCompress())
434 if (Type == SecFuncMetadata &&
446
447 uint64_t SectionStart = markSectionStart(Type, LayoutIdx);
448 switch (Type) {
449 case SecProfSummary:
450 computeSummary(ProfileMap);
451 if (auto EC = writeSummary())
452 return EC;
453 break;
454 case SecNameTable:
455 if (auto EC = writeNameTableSection(ProfileMap))
456 return EC;
457 break;
458 case SecCSNameTable:
459 if (auto EC = writeCSNameTableSection())
460 return EC;
461 break;
462 case SecLBRProfile:
464 if (std::error_code EC = writeFuncProfiles(ProfileMap))
465 return EC;
466 break;
468 if (auto EC = writeFuncOffsetTable())
469 return EC;
470 break;
471 case SecFuncMetadata:
472 if (std::error_code EC = writeFuncMetadata(ProfileMap))
473 return EC;
474 break;
476 if (auto EC = writeProfileSymbolListSection())
477 return EC;
478 break;
479 default:
480 if (auto EC = writeCustomSection(Type))
481 return EC;
482 break;
483 }
484 if (std::error_code EC = addNewSection(Type, LayoutIdx, SectionStart))
485 return EC;
487}
488
494
495std::error_code SampleProfileWriterExtBinary::writeDefaultLayout(
496 const SampleProfileMap &ProfileMap) {
497 // The const indices passed to writeOneSection below are specifying the
498 // positions of the sections in SectionHdrLayout. Look at
499 // initSectionHdrLayout to find out where each section is located in
500 // SectionHdrLayout.
501 if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
502 return EC;
503 if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
504 return EC;
505 if (auto EC = writeOneSection(SecCSNameTable, 2, ProfileMap))
506 return EC;
507 if (auto EC = writeOneSection(SecLBRProfile, 4, ProfileMap))
508 return EC;
509 if (auto EC = writeOneSection(SecProfileSymbolList, 5, ProfileMap))
510 return EC;
511 if (auto EC = writeOneSection(SecFuncOffsetTable, 3, ProfileMap))
512 return EC;
513 if (auto EC = writeOneSection(SecFuncMetadata, 6, ProfileMap))
514 return EC;
516}
517
518static void splitProfileMapToTwo(const SampleProfileMap &ProfileMap,
519 SampleProfileMap &ContextProfileMap,
520 SampleProfileMap &NoContextProfileMap) {
521 for (const auto &I : ProfileMap) {
522 if (I.second.getCallsiteSamples().size())
523 ContextProfileMap.insert({I.first, I.second});
524 else
525 NoContextProfileMap.insert({I.first, I.second});
526 }
527}
528
529std::error_code SampleProfileWriterExtBinary::writeCtxSplitLayout(
530 const SampleProfileMap &ProfileMap) {
531 SampleProfileMap ContextProfileMap, NoContextProfileMap;
532 splitProfileMapToTwo(ProfileMap, ContextProfileMap, NoContextProfileMap);
533
534 if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
535 return EC;
536 if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
537 return EC;
538 if (auto EC = writeOneSection(SecLBRProfile, 3, ContextProfileMap))
539 return EC;
540 if (auto EC = writeOneSection(SecFuncOffsetTable, 2, ContextProfileMap))
541 return EC;
542 // Mark the section to have no context. Note section flag needs to be set
543 // before writing the section.
545 if (auto EC = writeOneSection(SecLBRProfile, 5, NoContextProfileMap))
546 return EC;
547 // Mark the section to have no context. Note section flag needs to be set
548 // before writing the section.
550 if (auto EC = writeOneSection(SecFuncOffsetTable, 4, NoContextProfileMap))
551 return EC;
552 if (auto EC = writeOneSection(SecProfileSymbolList, 6, ProfileMap))
553 return EC;
554 if (auto EC = writeOneSection(SecFuncMetadata, 7, ProfileMap))
555 return EC;
556
558}
559
560std::error_code SampleProfileWriterExtBinary::writeSections(
561 const SampleProfileMap &ProfileMap) {
562 std::error_code EC;
564 EC = writeDefaultLayout(ProfileMap);
565 else if (SecLayout == CtxSplitLayout)
566 EC = writeCtxSplitLayout(ProfileMap);
567 else
568 llvm_unreachable("Unsupported layout");
569 return EC;
570}
571
572/// Write samples to a text file.
573///
574/// Note: it may be tempting to implement this in terms of
575/// FunctionSamples::print(). Please don't. The dump functionality is intended
576/// for debugging and has no specified form.
577///
578/// The format used here is more structured and deliberate because
579/// it needs to be parsed by the SampleProfileReaderText class.
581 auto &OS = *OutputStream;
583 OS << "[" << S.getContext().toString() << "]:" << S.getTotalSamples();
584 else
585 OS << S.getFunction() << ":" << S.getTotalSamples();
586
587 if (Indent == 0)
588 OS << ":" << S.getHeadSamples();
589 OS << "\n";
590 LineCount++;
591
593 for (const auto &I : SortedSamples.get()) {
594 LineLocation Loc = I->first;
595 const SampleRecord &Sample = I->second;
596 OS.indent(Indent + 1);
597 Loc.print(OS);
598 OS << ": " << Sample.getSamples();
599
600 for (const auto &J : Sample.getSortedCallTargets())
601 OS << " " << J.first << ":" << J.second;
602 OS << "\n";
603 LineCount++;
604
605 if (const TypeCountMap *Map = S.findCallsiteTypeSamplesAt(Loc);
606 Map && !Map->empty()) {
607 OS.indent(Indent + 1);
608 Loc.print(OS);
609 OS << ": ";
610 OS << kVTableProfPrefix;
611 for (const auto [TypeName, Count] : *Map) {
612 OS << TypeName << ":" << Count << " ";
613 }
614 OS << "\n";
615 LineCount++;
616 }
617 }
618
621 Indent += 1;
622 for (const auto *Element : SortedCallsiteSamples.get()) {
623 // Element is a pointer to a pair of LineLocation and FunctionSamplesMap.
624 const auto &[Loc, FunctionSamplesMap] = *Element;
625 for (const FunctionSamples &CalleeSamples :
627 OS.indent(Indent);
628 Loc.print(OS);
629 OS << ": ";
630 if (std::error_code EC = writeSample(CalleeSamples))
631 return EC;
632 }
633
634 if (const TypeCountMap *Map = S.findCallsiteTypeSamplesAt(Loc);
635 Map && !Map->empty()) {
636 OS.indent(Indent);
637 Loc.print(OS);
638 OS << ": ";
639 OS << kVTableProfPrefix;
640 for (const auto [TypeId, Count] : *Map) {
641 OS << TypeId << ":" << Count << " ";
642 }
643 OS << "\n";
644 LineCount++;
645 }
646 }
647
648 Indent -= 1;
649
651 OS.indent(Indent + 1);
652 OS << "!CFGChecksum: " << S.getFunctionHash() << "\n";
653 LineCount++;
654 }
655
656 if (S.getContext().getAllAttributes()) {
657 OS.indent(Indent + 1);
658 OS << "!Attributes: " << S.getContext().getAllAttributes() << "\n";
659 LineCount++;
660 }
661
662 if (Indent == 0 && MarkFlatProfiles && S.getCallsiteSamples().size() == 0)
663 OS << " !Flat\n";
664
666}
667
668std::error_code
670 assert(!Context.hasContext() && "cs profile is not supported");
671 return writeNameIdx(Context.getFunction());
672}
673
675 auto &NTable = getNameTable();
676 const auto &Ret = NTable.find(FName);
677 if (Ret == NTable.end())
679 encodeULEB128(Ret->second, *OutputStream);
681}
682
684 auto &NTable = getNameTable();
685 NTable.insert(std::make_pair(FName, 0));
686}
687
689 addName(Context.getFunction());
690}
691
693 // Add all the names in indirect call targets.
694 for (const auto &I : S.getBodySamples()) {
695 const SampleRecord &Sample = I.second;
696 for (const auto &J : Sample.getCallTargets())
697 addName(J.first);
698 }
699
700 // Recursively add all the names for inlined callsites.
701 for (const auto &J : S.getCallsiteSamples())
702 for (const auto &FS : J.second) {
703 const FunctionSamples &CalleeSamples = FS.second;
704 addName(CalleeSamples.getFunction());
705 addNames(CalleeSamples);
706 }
707
708 if (!WriteVTableProf)
709 return;
710 // Add all the vtable names to NameTable.
711 for (const auto &VTableAccessCountMap :
713 // Add type name to NameTable.
714 for (const auto Type : llvm::make_first_range(VTableAccessCountMap)) {
715 addName(Type);
716 }
717 }
718}
719
721 const SampleContext &Context) {
722 if (Context.hasContext()) {
723 for (auto &Callsite : Context.getContextFrames())
725 CSNameTable.insert(std::make_pair(Context, 0));
726 } else {
727 SampleProfileWriterBinary::addName(Context.getFunction());
728 }
729}
730
732 MapVector<FunctionId, uint32_t> &NameTable, std::set<FunctionId> &V) {
733 // Sort the names to make NameTable deterministic.
734 for (const auto &I : NameTable)
735 V.insert(I.first);
736 int i = 0;
737 for (const FunctionId &N : V)
738 NameTable[N] = i++;
739}
740
742 auto &OS = *OutputStream;
743 std::set<FunctionId> V;
745
746 // Write out the name table.
747 encodeULEB128(NameTable.size(), OS);
748 for (auto N : V) {
749 OS << N;
750 encodeULEB128(0, OS);
751 }
753}
754
755std::error_code
757 auto &OS = *OutputStream;
758 // Write file magic identifier.
762}
763
764std::error_code
766 // When calling write on a different profile map, existing names should be
767 // cleared.
768 NameTable.clear();
769
771
772 computeSummary(ProfileMap);
773 if (auto EC = writeSummary())
774 return EC;
775
776 // Generate the name table for all the functions referenced in the profile.
777 for (const auto &I : ProfileMap) {
778 addContext(I.second.getContext());
779 addNames(I.second);
780 }
781
784}
785
790
794
795void SampleProfileWriterExtBinaryBase::allocSecHdrTable() {
797
798 Writer.write(static_cast<uint64_t>(SectionHdrLayout.size()));
799 SecHdrTableOffset = OutputStream->tell();
800 for (uint32_t i = 0; i < SectionHdrLayout.size(); i++) {
801 Writer.write(static_cast<uint64_t>(-1));
802 Writer.write(static_cast<uint64_t>(-1));
803 Writer.write(static_cast<uint64_t>(-1));
804 Writer.write(static_cast<uint64_t>(-1));
805 }
806}
807
808std::error_code SampleProfileWriterExtBinaryBase::writeSecHdrTable() {
809 assert(SecHdrTable.size() == SectionHdrLayout.size() &&
810 "SecHdrTable entries doesn't match SectionHdrLayout");
811 SmallVector<uint32_t, 16> IndexMap(SecHdrTable.size(), -1);
812 for (uint32_t TableIdx = 0; TableIdx < SecHdrTable.size(); TableIdx++) {
813 IndexMap[SecHdrTable[TableIdx].LayoutIndex] = TableIdx;
814 }
815
816 // Write the section header table in the order specified in
817 // SectionHdrLayout. SectionHdrLayout specifies the sections
818 // order in which profile reader expect to read, so the section
819 // header table should be written in the order in SectionHdrLayout.
820 // Note that the section order in SecHdrTable may be different
821 // from the order in SectionHdrLayout, for example, SecFuncOffsetTable
822 // needs to be computed after SecLBRProfile (the order in SecHdrTable),
823 // but it needs to be read before SecLBRProfile (the order in
824 // SectionHdrLayout). So we use IndexMap above to switch the order.
825 support::endian::SeekableWriter Writer(
826 static_cast<raw_pwrite_stream &>(*OutputStream),
828 for (uint32_t LayoutIdx = 0; LayoutIdx < SectionHdrLayout.size();
829 LayoutIdx++) {
830 assert(IndexMap[LayoutIdx] < SecHdrTable.size() &&
831 "Incorrect LayoutIdx in SecHdrTable");
832 auto Entry = SecHdrTable[IndexMap[LayoutIdx]];
833 Writer.pwrite(static_cast<uint64_t>(Entry.Type),
834 SecHdrTableOffset + 4 * LayoutIdx * sizeof(uint64_t));
835 Writer.pwrite(static_cast<uint64_t>(Entry.Flags),
836 SecHdrTableOffset + (4 * LayoutIdx + 1) * sizeof(uint64_t));
837 Writer.pwrite(static_cast<uint64_t>(Entry.Offset),
838 SecHdrTableOffset + (4 * LayoutIdx + 2) * sizeof(uint64_t));
839 Writer.pwrite(static_cast<uint64_t>(Entry.Size),
840 SecHdrTableOffset + (4 * LayoutIdx + 3) * sizeof(uint64_t));
841 }
842
844}
845
846std::error_code SampleProfileWriterExtBinaryBase::writeHeader(
847 const SampleProfileMap &ProfileMap) {
848 auto &OS = *OutputStream;
849 FileStart = OS.tell();
851
852 allocSecHdrTable();
854}
855
859 "writeCallsiteVTableProf should not be called if WriteVTableProf is "
860 "false");
861
862 encodeULEB128(CallsiteTypeMap.size(), OS);
863 for (const auto &[Loc, TypeMap] : CallsiteTypeMap) {
864 Loc.serialize(OS);
865 if (std::error_code EC = serializeTypeMap(TypeMap, getNameTable(), OS))
866 return EC;
867 }
868
870}
871
873 auto &OS = *OutputStream;
874 encodeULEB128(Summary->getTotalCount(), OS);
875 encodeULEB128(Summary->getMaxCount(), OS);
876 encodeULEB128(Summary->getMaxFunctionCount(), OS);
877 encodeULEB128(Summary->getNumCounts(), OS);
878 encodeULEB128(Summary->getNumFunctions(), OS);
879 ArrayRef<ProfileSummaryEntry> Entries = Summary->getDetailedSummary();
880 encodeULEB128(Entries.size(), OS);
881 for (auto Entry : Entries) {
882 encodeULEB128(Entry.Cutoff, OS);
883 encodeULEB128(Entry.MinCount, OS);
884 encodeULEB128(Entry.NumCounts, OS);
885 }
887}
889 auto &OS = *OutputStream;
890 if (std::error_code EC = writeContextIdx(S.getContext()))
891 return EC;
892
894
895 // Emit all the body samples.
896 encodeULEB128(S.getBodySamples().size(), OS);
897 for (const auto &I : S.getBodySamples()) {
898 LineLocation Loc = I.first;
899 const SampleRecord &Sample = I.second;
900 Loc.serialize(OS);
901 Sample.serialize(OS, getNameTable());
902 }
903
904 // Recursively emit all the callsite samples.
905 uint64_t NumCallsites = 0;
906 for (const auto &J : S.getCallsiteSamples())
907 NumCallsites += J.second.size();
908 encodeULEB128(NumCallsites, OS);
909 for (const auto &J : S.getCallsiteSamples())
910 for (const auto &FS : J.second) {
911 J.first.serialize(OS);
912 if (std::error_code EC = writeBody(FS.second))
913 return EC;
914 }
915
916 if (WriteVTableProf)
918
920}
921
922/// Write samples of a top-level function to a binary file.
923///
924/// \returns true if the samples were written successfully, false otherwise.
925std::error_code
930
931/// Create a sample profile file writer based on the specified format.
932///
933/// \param Filename The file to create.
934///
935/// \param Format Encoding format for the profile file.
936///
937/// \returns an error code indicating the status of the created writer.
940 std::error_code EC;
941 std::unique_ptr<raw_ostream> OS;
943 OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_None));
944 else
945 OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_TextWithCRLF));
946 if (EC)
947 return EC;
948
949 return create(OS, Format);
950}
951
952/// Create a sample profile stream writer based on the specified format.
953///
954/// \param OS The output stream to store the profile data to.
955///
956/// \param Format Encoding format for the profile file.
957///
958/// \returns an error code indicating the status of the created writer.
960SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
962 std::error_code EC;
963 std::unique_ptr<SampleProfileWriter> Writer;
964
965 // Currently only Text and Extended Binary format are supported for CSSPGO.
969
970 if (Format == SPF_Binary)
971 Writer.reset(new SampleProfileWriterRawBinary(OS));
972 else if (Format == SPF_Ext_Binary)
973 Writer.reset(new SampleProfileWriterExtBinary(OS));
974 else if (Format == SPF_Text)
975 Writer.reset(new SampleProfileWriterText(OS));
976 else if (Format == SPF_GCC)
978 else
980
981 if (EC)
982 return EC;
983
984 Writer->Format = Format;
985 return std::move(Writer);
986}
987
990 Summary = Builder.computeSummaryForProfiles(ProfileMap);
991}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
Provides ErrorOr<T> smart pointer.
#define I(x, y, z)
Definition MD5.cpp:58
static void splitProfileMapToTwo(const SampleProfileMap &ProfileMap, SampleProfileMap &ContextProfileMap, SampleProfileMap &NoContextProfileMap)
static cl::opt< bool > ExtBinaryWriteVTableTypeProf("extbinary-write-vtable-type-prof", cl::init(false), cl::Hidden, cl::desc("Write vtable type profile in ext-binary sample profile writer"))
#define LLVM_DEBUG(...)
Definition Debug.h:114
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
Represents either an error or a value T.
Definition ErrorOr.h:56
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
static LLVM_ABI const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
An abstract base class for streams implementations that also support a pwrite operation.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
A raw_ostream that writes to an SmallVector or SmallString.
DefaultFunctionPruningStrategy(SampleProfileMap &ProfileMap, size_t OutputSizeLimit)
void Erase(size_t CurrentOutputSize) override
In this default implementation, functions with fewest samples are dropped first.
This class represents a function that is read from a sample profile.
Definition FunctionId.h:36
When writing a profile with size limit, user may want to use a different strategy to reduce function ...
virtual void Erase(size_t CurrentOutputSize)=0
SampleProfileWriter::writeWithSizeLimit() calls this after every write iteration if the output size s...
FunctionPruningStrategy(SampleProfileMap &ProfileMap, size_t OutputSizeLimit)
ProfileMap A reference to the original profile map.
Representation of the samples collected for a function.
Definition SampleProf.h:777
static LLVM_ABI bool ProfileIsPreInlined
static constexpr const char * UniqSuffix
uint64_t getHeadSamples() const
For top-level functions, return the total number of branch samples that have the function as the bran...
Definition SampleProf.h:993
static LLVM_ABI bool ProfileIsCS
FunctionId getFunction() const
Return the function name.
const CallsiteTypeMap & getCallsiteTypeCounts() const
Returns vtable access samples for the C++ types collected in this function.
const TypeCountMap * findCallsiteTypeSamplesAt(const LineLocation &Loc) const
Returns the TypeCountMap for inlined callsites at the given Loc.
Definition SampleProf.h:963
static LLVM_ABI bool ProfileIsProbeBased
static LLVM_ABI bool ProfileIsFS
If this profile uses flow sensitive discriminators.
SampleContext & getContext() const
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
Definition SampleProf.h:985
const CallsiteSampleMap & getCallsiteSamples() const
Return all the callsite samples collected in the body of the function.
const BodySampleMap & getBodySamples() const
Return all the samples collected in the body of the function.
std::string toString() const
Definition SampleProf.h:664
This class provides operator overloads to the map container using MD5 as the key type,...
void stablizeNameTable(MapVector< FunctionId, uint32_t > &NameTable, std::set< FunctionId > &V)
virtual void addContext(const SampleContext &Context)
virtual std::error_code writeMagicIdent(SampleProfileFormat Format)
MapVector< FunctionId, uint32_t > NameTable
std::error_code writeCallsiteVTableProf(const CallsiteTypeMap &CallsiteTypeMap, raw_ostream &OS)
Write CallsiteTypeMap to the output stream OS.
virtual std::error_code writeContextIdx(const SampleContext &Context)
std::error_code writeSample(const FunctionSamples &S) override
Write samples of a top-level function to a binary file.
std::error_code writeHeader(const SampleProfileMap &ProfileMap) override
Write a file header for the profile file.
virtual MapVector< FunctionId, uint32_t > & getNameTable()
std::error_code writeBody(const FunctionSamples &S)
std::error_code writeNameIdx(FunctionId FName)
std::error_code writeNameTableSection(const SampleProfileMap &ProfileMap)
SmallVector< SecHdrTableEntry, 8 > SectionHdrLayout
std::error_code writeFuncMetadata(const SampleProfileMap &Profiles)
virtual std::error_code writeCustomSection(SecType Type)=0
virtual std::error_code writeOneSection(SecType Type, uint32_t LayoutIdx, const SampleProfileMap &ProfileMap)
std::error_code writeCSNameIdx(const SampleContext &Context)
virtual std::error_code writeSections(const SampleProfileMap &ProfileMap)=0
void addSectionFlag(SecType Type, SecFlagType Flag)
uint64_t markSectionStart(SecType Type, uint32_t LayoutIdx)
Return the current position and prepare to use it as the start position of a section given the sectio...
void addContext(const SampleContext &Context) override
std::error_code addNewSection(SecType Sec, uint32_t LayoutIdx, uint64_t SectionStart)
Add a new section into section header table given the section type Type, its position LayoutIdx in Se...
std::error_code write(const SampleProfileMap &ProfileMap) override
Write all the sample profiles in the given map of samples.
std::error_code writeContextIdx(const SampleContext &Context) override
std::error_code writeSample(const FunctionSamples &S) override
Write samples of a top-level function to a binary file.
SampleProfileWriterExtBinary(std::unique_ptr< raw_ostream > &OS)
Sample-based profile writer (text format).
std::error_code writeSample(const FunctionSamples &S) override
Write samples to a text file.
std::unique_ptr< ProfileSummary > Summary
Profile summary.
virtual std::error_code writeSample(const FunctionSamples &S)=0
Write sample profiles in S.
SampleProfileFormat Format
Profile format.
std::error_code writeWithSizeLimitInternal(SampleProfileMap &ProfileMap, size_t OutputSizeLimit, FunctionPruningStrategy *Strategy)
void computeSummary(const SampleProfileMap &ProfileMap)
Compute summary for this profile.
virtual std::error_code writeFuncProfiles(const SampleProfileMap &ProfileMap)
std::unique_ptr< raw_ostream > OutputStream
Output stream where to emit the profile to.
size_t LineCount
For writeWithSizeLimit in text mode, each newline takes 1 additional byte on Windows when actually wr...
static ErrorOr< std::unique_ptr< SampleProfileWriter > > create(StringRef Filename, SampleProfileFormat Format)
Profile writer factory.
virtual std::error_code writeHeader(const SampleProfileMap &ProfileMap)=0
Write a file header for the profile file.
virtual std::error_code write(const SampleProfileMap &ProfileMap)
Write all the sample profiles in the given map of samples.
Representation of a single sample record.
Definition SampleProf.h:350
LLVM_ABI std::error_code serialize(raw_ostream &OS, const MapVector< FunctionId, uint32_t > &NameTable) const
Serialize the sample record to the output stream using ULEB128 encoding.
const CallTargetMap & getCallTargets() const
Definition SampleProf.h:418
const SortedCallTargetSet getSortedCallTargets() const
Definition SampleProf.h:419
Sort a LocationT->SampleT map by LocationT.
const SamplesWithLocList & get() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
initializer< Ty > init(const Ty &Val)
LLVM_ABI void compress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &CompressedBuffer, int Level=DefaultCompression)
LLVM_ABI bool isAvailable()
constexpr int BestSizeCompression
Definition Compression.h:40
LLVM_ABI void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
Definition SampleProf.h:111
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:256
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:272
std::pair< hash_code, const FunctionSamples * > NameFunctionSamples
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
Definition SampleProf.h:208
@ SecFlagHasVTableTypeProf
SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
Definition SampleProf.h:211
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
Definition SampleProf.h:205
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
Definition SampleProf.h:202
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
Definition SampleProf.h:766
std::map< FunctionId, uint64_t > TypeCountMap
Key represents type of a C++ polymorphic class type by its vtable and value represents its counter.
Definition SampleProf.h:330
constexpr char kVTableProfPrefix[]
Definition SampleProf.h:94
std::error_code serializeTypeMap(const TypeCountMap &Map, const MapVector< FunctionId, uint32_t > &NameTable, raw_ostream &OS)
Write Map to the output stream.
static uint64_t SPVersion()
Definition SampleProf.h:118
std::map< LineLocation, TypeCountMap > CallsiteTypeMap
Definition SampleProf.h:768
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:771
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:310
@ Offset
Definition DWP.cpp:477
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct a string ref from an array ref of unsigned chars.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1407
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1417
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition LEB128.h:81
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
endianness
Definition bit.h:71
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
#define N
Represents the relative location of an instruction.
Definition SampleProf.h:288
Adapter to write values to a stream in a particular byte order.
void write(ArrayRef< value_type > Val)
static uint64_t round(uint64_t Acc, uint64_t Input)
Definition xxhash.cpp:80