LLVM 24.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/Eytzinger.h"
22#include "llvm/ADT/StringRef.h"
29#include "llvm/Support/LEB128.h"
30#include "llvm/Support/MD5.h"
32#include <array>
33#include <cmath>
34#include <cstdint>
35#include <memory>
36#include <system_error>
37#include <utility>
38#include <vector>
39
40#define DEBUG_TYPE "llvm-profdata"
41
42using namespace llvm;
43using namespace sampleprof;
44
45// To begin with, make this option off by default.
47 "extbinary-write-vtable-type-prof", cl::init(false), cl::Hidden,
48 cl::desc("Write vtable type profile in ext-binary sample profile writer"));
49
51 "sample-profile-format-version", cl::init(DefaultVersion), cl::Hidden,
52 cl::desc("Format version to write for extensible binary profiles"));
53
54static cl::opt<bool>
55 WriteMD5ProfSymList("md5-prof-sym-list", cl::init(false), cl::Hidden,
56 cl::desc("Write ProfileSymbolList (Cold Symbols) as "
57 "64-bit MD5 hashes in Eytzinger layout"));
58
60 "sample-profile-write-eytzinger-name-tables", cl::init(false), cl::Hidden,
61 cl::desc("Write Eytzinger 3-span layout for NameTable"));
62
63namespace llvm {
64namespace support {
65namespace endian {
66namespace {
67
68// Adapter class to llvm::support::endian::Writer for pwrite().
69struct SeekableWriter {
71 endianness Endian;
72 SeekableWriter(raw_pwrite_stream &OS, endianness Endian)
73 : OS(OS), Endian(Endian) {}
74
75 template <typename ValueType> void pwrite(ValueType Val, size_t Offset) {
76 std::string StringBuf;
77 raw_string_ostream SStream(StringBuf);
78 Writer(SStream, Endian).write(Val);
79 OS.pwrite(StringBuf.data(), StringBuf.size(), Offset);
80 }
81};
82
83} // namespace
84} // namespace endian
85} // namespace support
86} // namespace llvm
87
93
94void DefaultFunctionPruningStrategy::Erase(size_t CurrentOutputSize) {
95 double D = (double)OutputSizeLimit / CurrentOutputSize;
96 size_t NewSize = (size_t)round(ProfileMap.size() * D * D);
97 size_t NumToRemove = ProfileMap.size() - NewSize;
98 if (NumToRemove < 1)
99 NumToRemove = 1;
100
101 assert(NumToRemove <= SortedFunctions.size());
102 for (const NameFunctionSamples &E :
103 llvm::drop_begin(SortedFunctions, SortedFunctions.size() - NumToRemove))
104 ProfileMap.erase(E.first);
105 SortedFunctions.resize(SortedFunctions.size() - NumToRemove);
106}
107
109 SampleProfileMap &ProfileMap, size_t OutputSizeLimit,
110 FunctionPruningStrategy *Strategy) {
111 if (OutputSizeLimit == 0)
112 return write(ProfileMap);
113
114 size_t OriginalFunctionCount = ProfileMap.size();
115
116 std::unique_ptr<raw_ostream> OriginalOutputStream;
117 OutputStream.swap(OriginalOutputStream);
118
119 size_t IterationCount = 0;
120 size_t TotalSize;
121
122 SmallVector<char> StringBuffer;
123 do {
124 StringBuffer.clear();
125 OutputStream.reset(new raw_svector_ostream(StringBuffer));
126 if (std::error_code EC = write(ProfileMap))
127 return EC;
128
129 TotalSize = StringBuffer.size();
130 // On Windows every "\n" is actually written as "\r\n" to disk but not to
131 // memory buffer, this difference should be added when considering the total
132 // output size.
133#ifdef _WIN32
134 if (Format == SPF_Text)
135 TotalSize += LineCount;
136#endif
137 if (TotalSize <= OutputSizeLimit)
138 break;
139
140 Strategy->Erase(TotalSize);
141 IterationCount++;
142 } while (ProfileMap.size() != 0);
143
144 if (ProfileMap.size() == 0)
146
147 OutputStream.swap(OriginalOutputStream);
148 OutputStream->write(StringBuffer.data(), StringBuffer.size());
149 LLVM_DEBUG(dbgs() << "Profile originally has " << OriginalFunctionCount
150 << " functions, reduced to " << ProfileMap.size() << " in "
151 << IterationCount << " iterations\n");
152 // Silence warning on Release build.
153 (void)OriginalFunctionCount;
154 (void)IterationCount;
156}
157
158std::error_code
160 std::vector<NameFunctionSamples> V;
161 sortFuncProfiles(ProfileMap, V);
162 for (const auto &I : V) {
163 if (std::error_code EC = writeSample(*I.second))
164 return EC;
165 }
167}
168
169std::error_code SampleProfileWriter::write(const SampleProfileMap &ProfileMap) {
170 if (std::error_code EC = writeHeader(ProfileMap))
171 return EC;
172
173 if (std::error_code EC = writeFuncProfiles(ProfileMap))
174 return EC;
175
177}
178
179/// Return the current position and prepare to use it as the start
180/// position of a section given the section type \p Type and its position
181/// \p LayoutIdx in SectionHdrLayout.
184 uint32_t LayoutIdx) {
185 uint64_t SectionStart = OutputStream->tell();
186 assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range");
187 const auto &Entry = SectionHdrLayout[LayoutIdx];
188 assert(Entry.Type == Type && "Unexpected section type");
189 // Use LocalBuf as a temporary output for writting data.
191 LocalBufStream.swap(OutputStream);
192 return SectionStart;
193}
194
195std::error_code SampleProfileWriterExtBinaryBase::compressAndOutput() {
198 std::string &UncompressedStrings =
199 static_cast<raw_string_ostream *>(LocalBufStream.get())->str();
200 if (UncompressedStrings.size() == 0)
202 auto &OS = *OutputStream;
203 SmallVector<uint8_t, 128> CompressedStrings;
205 CompressedStrings,
207 encodeULEB128(UncompressedStrings.size(), OS);
208 encodeULEB128(CompressedStrings.size(), OS);
209 OS << toStringRef(CompressedStrings);
210 UncompressedStrings.clear();
212}
213
214/// Add a new section into section header table given the section type
215/// \p Type, its position \p LayoutIdx in SectionHdrLayout and the
216/// location \p SectionStart where the section should be written to.
218 SecType Type, uint32_t LayoutIdx, uint64_t SectionStart) {
219 assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range");
220 const auto &Entry = SectionHdrLayout[LayoutIdx];
221 assert(Entry.Type == Type && "Unexpected section type");
223 LocalBufStream.swap(OutputStream);
224 if (std::error_code EC = compressAndOutput())
225 return EC;
226 }
227 SecHdrTable.push_back({Type, Entry.Flags, SectionStart - FileStart,
228 OutputStream->tell() - SectionStart, LayoutIdx});
230}
231
232std::error_code
234 // When calling write on a different profile map, existing states should be
235 // cleared.
236 NameTable.clear();
237 CSNameTable.clear();
238 SecHdrTable.clear();
239
240 if (std::error_code EC = writeHeader(ProfileMap))
241 return EC;
242
243 std::string LocalBuf;
244 LocalBufStream = std::make_unique<raw_string_ostream>(LocalBuf);
245 if (std::error_code EC = writeSections(ProfileMap))
246 return EC;
247
248 if (std::error_code EC = writeSecHdrTable())
249 return EC;
250
252}
253
255 const SampleContext &Context) {
256 if (Context.hasContext())
257 return writeCSNameIdx(Context);
258 else
259 return SampleProfileWriterBinary::writeNameIdx(Context.getFunction());
260}
261
262std::error_code
264 const auto &Ret = CSNameTable.find(Context);
265 if (Ret == CSNameTable.end())
267 encodeULEB128(Ret->second, *OutputStream);
269}
270
271std::error_code
273 uint64_t Offset = OutputStream->tell();
274 auto &Context = S.getContext();
275 FuncOffsetTable[Context] = Offset - SecLBRProfileStart;
277 return writeBody(S);
278}
279
281 auto &OS = *OutputStream;
282
283 // Write out the table size.
284 encodeULEB128(FuncOffsetTable.size(), OS);
285
286 // Write out FuncOffsetTable.
287 auto WriteItem = [&](const SampleContext &Context, uint64_t Offset) {
288 if (std::error_code EC = writeContextIdx(Context))
289 return EC;
291 return (std::error_code)sampleprof_error::success;
292 };
293
295 // Sort the contexts before writing them out. This is to help fast load all
296 // context profiles for a function as well as their callee contexts which
297 // can help profile-guided importing for ThinLTO.
298 std::map<SampleContext, uint64_t> OrderedFuncOffsetTable(
299 FuncOffsetTable.begin(), FuncOffsetTable.end());
300 for (const auto &Entry : OrderedFuncOffsetTable) {
301 if (std::error_code EC = WriteItem(Entry.first, Entry.second))
302 return EC;
303 }
305 } else {
306 for (const auto &Entry : FuncOffsetTable) {
307 if (std::error_code EC = WriteItem(Entry.first, Entry.second))
308 return EC;
309 }
310 }
311
312 FuncOffsetTable.clear();
314}
315
317 const FunctionSamples &FunctionProfile) {
318 auto &OS = *OutputStream;
319 if (std::error_code EC = writeContextIdx(FunctionProfile.getContext()))
320 return EC;
321
323 encodeULEB128(FunctionProfile.getFunctionHash(), OS);
325 encodeULEB128(FunctionProfile.getContext().getAllAttributes(), OS);
326 }
327
329 // Recursively emit attributes for all callee samples.
330 uint64_t NumCallsites = 0;
331 for (const auto &J : FunctionProfile.getCallsiteSamples())
332 NumCallsites += J.second.size();
333 encodeULEB128(NumCallsites, OS);
334 for (const auto &J : FunctionProfile.getCallsiteSamples()) {
335 for (const auto &FS : J.second) {
336 LineLocation Loc = J.first;
337 encodeULEB128(Loc.LineOffset, OS);
338 encodeULEB128(Loc.Discriminator, OS);
339 if (std::error_code EC = writeFuncMetadata(FS.second))
340 return EC;
341 }
342 }
343 }
344
346}
347
349 const SampleProfileMap &Profiles) {
353 for (const auto &Entry : Profiles) {
354 if (std::error_code EC = writeFuncMetadata(Entry.second))
355 return EC;
356 }
358}
359
360template <class KeyT, class ValT>
365
366 llvm::sort(Entries,
367 [](const auto *L, const auto *R) { return L->first < R->first; });
368
369 for (const auto &[I, Entry] : llvm::enumerate(Entries))
370 Entry->second = I;
371
372 return Entries;
373}
374
376 if (!UseMD5)
378
379 auto &OS = *OutputStream;
380
381 // Write out the MD5 name table. We wrote unencoded MD5 so reader can
382 // retrieve the name using the name index without having to read the
383 // whole name table.
384 encodeULEB128(NameTable.size(), OS);
386 for (const auto *Entry : stabilizeTable(NameTable))
387 Writer.write(Entry->first.getHashCode());
389}
390
392 const SampleProfileMap &ProfileMap) {
393 for (const auto &I : ProfileMap) {
394 addContext(I.second.getContext());
395 addNames(I.second);
396 }
397
398 // If NameTable contains ".__uniq." suffix, set SecFlagUniqSuffix flag
399 // so compiler won't strip the suffix during profile matching after
400 // seeing the flag in the profile.
401 // Original names are unavailable if using MD5, so this option has no use.
402 if (!UseMD5) {
403 for (const auto &I : NameTable) {
404 if (I.first.stringRef().contains(FunctionSamples::UniqSuffix)) {
406 break;
407 }
408 }
409 }
410
411 if (UseMD5 && WriteEytzingerNameTables) {
412 if (auto EC = writeEytzingerNameTableSection(ProfileMap))
413 return EC;
415 }
416
417 if (auto EC = writeNameTable())
418 return EC;
420}
421
422namespace {
423
424// Helper class to construct and write the SecNameTable section in Eytzinger
425// layout for ExtBinary MD5 profiles.
426//
427// The on-disk layout of the Eytzinger name table section consists of symbol
428// counts followed by three contiguous Eytzinger hash arrays:
429// - ULEB128 count of Context-Sensitive (CS) top-level profile symbol keys
430// - ULEB128 count of Flat top-level profile symbol keys
431// - ULEB128 count of Inlinee and auxiliary profile symbol keys
432// - Array of 64-bit little-endian MD5 hash keys for CS profiles in Eytzinger
433// order
434// - Array of 64-bit little-endian MD5 hash keys for Flat profiles in Eytzinger
435// order
436// - Array of 64-bit little-endian MD5 hash keys for Inlinees in Eytzinger order
437class EytzingerNameTable {
439 std::array<TableT, static_cast<size_t>(EytzingerSpan::NumSpans)> Spans;
440
441public:
442 EytzingerNameTable(std::vector<support::ulittle64_t> CSKeys,
443 std::vector<support::ulittle64_t> FlatKeys,
444 std::vector<support::ulittle64_t> InlineeKeys)
445 : Spans{TableT::create(std::move(CSKeys)),
446 TableT::create(std::move(FlatKeys)),
447 TableT::create(std::move(InlineeKeys))} {}
448
449 // Find the global index of GUID across the three Eytzinger table spans.
450 uint64_t findGlobalIdx(uint64_t GUID) const {
451 uint64_t BaseIdx = 0;
452 for (const auto &Table : Spans) {
453 if (std::optional<size_t> LocalIdx = Table.findIndex(GUID))
454 return BaseIdx + *LocalIdx;
455 BaseIdx += Table.size();
456 }
457 llvm_unreachable("Symbol in NameTable missing from Eytzinger spans");
458 }
459
460 void write(raw_ostream &OS) const {
461 for (const auto &Table : Spans)
462 encodeULEB128(uint64_t(Table.size()), OS);
463 for (const auto &Table : Spans)
464 OS.write(reinterpret_cast<const char *>(Table.data()),
465 Table.size() * sizeof(support::ulittle64_t));
466 }
467};
468
469} // end anonymous namespace
470
471std::error_code
473 const SampleProfileMap &ProfileMap) {
474 DenseSet<uint64_t> TopLevelGUIDs;
475 std::vector<support::ulittle64_t> CSKeys, FlatKeys, InlineeKeys;
476
477 // Collect top-level CS and Flat keys directly from ProfileMap.
478 for (const auto &I : ProfileMap) {
479 const SampleContext &Ctx = I.second.getContext();
480 uint64_t GUID = Ctx.getFunction().getHashCode();
481 if (TopLevelGUIDs.insert(GUID).second) {
482 if (Ctx.hasContext())
483 CSKeys.emplace_back(GUID);
484 else
485 FlatKeys.emplace_back(GUID);
486 }
487 }
488
489 // Collect remaining non-top-level symbols (inlinees, targets, vtables) from
490 // NameTable.
491 for (const auto &Entry : NameTable) {
492 uint64_t GUID = Entry.first.getHashCode();
493 if (!TopLevelGUIDs.contains(GUID))
494 InlineeKeys.emplace_back(GUID);
495 }
496
497 EytzingerNameTable Tables(std::move(CSKeys), std::move(FlatKeys),
498 std::move(InlineeKeys));
499
500 // Assign each symbol its corresponding index in the Eytzinger layout.
501 for (auto &[FId, Idx] : NameTable)
502 Idx = Tables.findGlobalIdx(FId.getHashCode());
503
504 Tables.write(*OutputStream);
505
507}
508
510 auto &OS = *OutputStream;
511 encodeULEB128(CSNameTable.size(), OS);
513 for (const auto *Entry : stabilizeTable(CSNameTable)) {
514 auto Frames = Entry->first.getContextFrames();
515 encodeULEB128(Frames.size(), OS);
516 for (auto &Callsite : Frames) {
517 if (std::error_code EC = writeNameIdx(Callsite.Func))
518 return EC;
519 encodeULEB128(Callsite.Location.LineOffset, OS);
520 encodeULEB128(Callsite.Location.Discriminator, OS);
521 }
522 }
523
525}
526
527std::error_code
533
534std::error_code
536 assert((!ProfSymList || !ProfSymList->isMD5()) &&
537 "Writing string-based ProfileSymbolListSection from MD5 table "
538 "not yet implemented");
539 if (ProfSymList && ProfSymList->size() > 0)
540 if (std::error_code EC = ProfSymList->write(*OutputStream))
541 return EC;
542
544}
545
546std::error_code
548 if (!ProfSymList || ProfSymList->size() == 0)
550 assert(!ProfSymList->isMD5() &&
551 "Writing MD5 ProfileSymbolListSection from existing MD5 "
552 "table not yet implemented");
553
554 auto &OS = *OutputStream;
555 std::vector<uint64_t> Keys = ProfSymList->collectGUIDs();
556
557 auto Table =
559
560 OS.write(reinterpret_cast<const char *>(Table.data()),
561 Table.size() * sizeof(support::ulittle64_t));
563}
564
566 SecType Type, uint32_t LayoutIdx, const SampleProfileMap &ProfileMap) {
567 // The setting of SecFlagCompress should happen before markSectionStart.
568 if (Type == SecProfileSymbolList && ProfSymList && ProfSymList->toCompress())
572 if (Type == SecFuncMetadata &&
586 if (Type == SecNameTable && WriteEytzingerNameTables && UseMD5)
588
589 uint64_t SectionStart = markSectionStart(Type, LayoutIdx);
590 switch (Type) {
591 case SecProfSummary:
592 computeSummary(ProfileMap);
593 if (auto EC = writeSummary())
594 return EC;
595 break;
596 case SecNameTable:
597 if (auto EC = writeNameTableSection(ProfileMap))
598 return EC;
599 break;
600 case SecCSNameTable:
601 if (auto EC = writeCSNameTableSection())
602 return EC;
603 break;
604 case SecLBRProfile:
606 if (std::error_code EC = writeFuncProfiles(ProfileMap))
607 return EC;
608 break;
610 if (auto EC = writeFuncOffsetTable())
611 return EC;
612 break;
613 case SecFuncMetadata:
614 if (std::error_code EC = writeFuncMetadata(ProfileMap))
615 return EC;
616 break;
618 if (auto EC = writeProfileSymbolListSection())
619 return EC;
620 break;
621 default:
622 if (auto EC = writeCustomSection(Type))
623 return EC;
624 break;
625 }
626 if (std::error_code EC = addNewSection(Type, LayoutIdx, SectionStart))
627 return EC;
629}
630
636
637std::error_code SampleProfileWriterExtBinary::writeDefaultLayout(
638 const SampleProfileMap &ProfileMap) {
639 // The const indices passed to writeOneSection below are specifying the
640 // positions of the sections in SectionHdrLayout. Look at
641 // initSectionHdrLayout to find out where each section is located in
642 // SectionHdrLayout.
643 if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
644 return EC;
645 if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
646 return EC;
647 if (auto EC = writeOneSection(SecCSNameTable, 2, ProfileMap))
648 return EC;
649 if (auto EC = writeOneSection(SecLBRProfile, 4, ProfileMap))
650 return EC;
651 if (auto EC = writeOneSection(SecProfileSymbolList, 5, ProfileMap))
652 return EC;
653 if (auto EC = writeOneSection(SecFuncOffsetTable, 3, ProfileMap))
654 return EC;
655 if (auto EC = writeOneSection(SecFuncMetadata, 6, ProfileMap))
656 return EC;
658}
659
660static void splitProfileMapToTwo(const SampleProfileMap &ProfileMap,
661 SampleProfileMap &ContextProfileMap,
662 SampleProfileMap &NoContextProfileMap) {
663 for (const auto &I : ProfileMap) {
664 if (I.second.getCallsiteSamples().size())
665 ContextProfileMap.insert({I.first, I.second});
666 else
667 NoContextProfileMap.insert({I.first, I.second});
668 }
669}
670
671std::error_code SampleProfileWriterExtBinary::writeCtxSplitLayout(
672 const SampleProfileMap &ProfileMap) {
673 SampleProfileMap ContextProfileMap, NoContextProfileMap;
674 splitProfileMapToTwo(ProfileMap, ContextProfileMap, NoContextProfileMap);
675
676 if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
677 return EC;
678 if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
679 return EC;
680 if (auto EC = writeOneSection(SecLBRProfile, 3, ContextProfileMap))
681 return EC;
682 if (auto EC = writeOneSection(SecFuncOffsetTable, 2, ContextProfileMap))
683 return EC;
684 // Mark the section to have no context. Note section flag needs to be set
685 // before writing the section.
687 if (auto EC = writeOneSection(SecLBRProfile, 5, NoContextProfileMap))
688 return EC;
689 // Mark the section to have no context. Note section flag needs to be set
690 // before writing the section.
692 if (auto EC = writeOneSection(SecFuncOffsetTable, 4, NoContextProfileMap))
693 return EC;
694 if (auto EC = writeOneSection(SecProfileSymbolList, 6, ProfileMap))
695 return EC;
696 if (auto EC = writeOneSection(SecFuncMetadata, 7, ProfileMap))
697 return EC;
698
700}
701
702std::error_code SampleProfileWriterExtBinary::writeSections(
703 const SampleProfileMap &ProfileMap) {
704 std::error_code EC;
706 EC = writeDefaultLayout(ProfileMap);
707 else if (SecLayout == CtxSplitLayout)
708 EC = writeCtxSplitLayout(ProfileMap);
709 else
710 llvm_unreachable("Unsupported layout");
711 return EC;
712}
713
714/// Write samples to a text file.
715///
716/// Note: it may be tempting to implement this in terms of
717/// FunctionSamples::print(). Please don't. The dump functionality is intended
718/// for debugging and has no specified form.
719///
720/// The format used here is more structured and deliberate because
721/// it needs to be parsed by the SampleProfileReaderText class.
723 auto &OS = *OutputStream;
725 OS << "[" << S.getContext().toString() << "]:" << S.getTotalSamples();
726 else
727 OS << S.getFunction() << ":" << S.getTotalSamples();
728
729 if (Indent == 0)
730 OS << ":" << S.getHeadSamples();
731 OS << "\n";
732 LineCount++;
733
735 for (const auto &I : SortedSamples.get()) {
736 LineLocation Loc = I->first;
737 const SampleRecord &Sample = I->second;
738 OS.indent(Indent + 1);
739 Loc.print(OS);
740 OS << ": " << Sample.getSamples();
741
742 for (const auto &J : Sample.getSortedCallTargets())
743 OS << " " << J.first << ":" << J.second;
744 OS << "\n";
745 LineCount++;
746
747 if (const TypeCountMap *Map = S.findCallsiteTypeSamplesAt(Loc);
748 Map && !Map->empty()) {
749 OS.indent(Indent + 1);
750 Loc.print(OS);
751 OS << ": ";
752 OS << kVTableProfPrefix;
753 for (const auto [TypeName, Count] : *Map) {
754 OS << TypeName << ":" << Count << " ";
755 }
756 OS << "\n";
757 LineCount++;
758 }
759 }
760
763 Indent += 1;
764 for (const auto *Element : SortedCallsiteSamples.get()) {
765 // Element is a pointer to a pair of LineLocation and FunctionSamplesMap.
766 const auto &[Loc, FunctionSamplesMap] = *Element;
767 for (const FunctionSamples &CalleeSamples :
769 OS.indent(Indent);
770 Loc.print(OS);
771 OS << ": ";
772 if (std::error_code EC = writeSample(CalleeSamples))
773 return EC;
774 }
775
776 if (const TypeCountMap *Map = S.findCallsiteTypeSamplesAt(Loc);
777 Map && !Map->empty()) {
778 OS.indent(Indent);
779 Loc.print(OS);
780 OS << ": ";
781 OS << kVTableProfPrefix;
782 for (const auto [TypeId, Count] : *Map) {
783 OS << TypeId << ":" << Count << " ";
784 }
785 OS << "\n";
786 LineCount++;
787 }
788 }
789
790 Indent -= 1;
791
793 OS.indent(Indent + 1);
794 OS << "!CFGChecksum: " << S.getFunctionHash() << "\n";
795 LineCount++;
796 }
797
798 if (S.getContext().getAllAttributes()) {
799 OS.indent(Indent + 1);
800 OS << "!Attributes: " << S.getContext().getAllAttributes() << "\n";
801 LineCount++;
802 }
803
804 if (Indent == 0 && MarkFlatProfiles && S.getCallsiteSamples().size() == 0)
805 OS << " !Flat\n";
806
808}
809
810std::error_code
812 assert(!Context.hasContext() && "cs profile is not supported");
813 return writeNameIdx(Context.getFunction());
814}
815
817 auto &NTable = getNameTable();
818 const auto &Ret = NTable.find(FName);
819 if (Ret == NTable.end())
821 encodeULEB128(Ret->second, *OutputStream);
823}
824
826 auto &NTable = getNameTable();
827 NTable.insert(std::make_pair(FName, 0));
828}
829
831 addName(Context.getFunction());
832}
833
835 // Add all the names in indirect call targets.
836 for (const auto &I : S.getBodySamples()) {
837 const SampleRecord &Sample = I.second;
838 for (const auto &J : Sample.getCallTargets())
839 addName(J.first);
840 }
841
842 // Recursively add all the names for inlined callsites.
843 for (const auto &J : S.getCallsiteSamples())
844 for (const auto &FS : J.second) {
845 const FunctionSamples &CalleeSamples = FS.second;
846 addName(CalleeSamples.getFunction());
847 addNames(CalleeSamples);
848 }
849
850 if (!WriteVTableProf)
851 return;
852 // Add all the vtable names to NameTable.
853 for (const auto &VTableAccessCountMap :
855 // Add type name to NameTable.
856 for (const auto Type : llvm::make_first_range(VTableAccessCountMap)) {
857 addName(Type);
858 }
859 }
860}
861
863 const SampleContext &Context) {
864 if (Context.hasContext()) {
865 for (auto &Callsite : Context.getContextFrames())
867 CSNameTable.insert(std::make_pair(Context, 0));
868 } else {
869 SampleProfileWriterBinary::addName(Context.getFunction());
870 }
871}
872
874 auto &OS = *OutputStream;
875
876 // Write out the name table.
877 encodeULEB128(NameTable.size(), OS);
878 for (const auto *Entry : stabilizeTable(NameTable)) {
879 OS << Entry->first;
880 encodeULEB128(0, OS);
881 }
883}
884
885std::error_code
893
894std::error_code
896 // When calling write on a different profile map, existing names should be
897 // cleared.
898 NameTable.clear();
899
901
902 computeSummary(ProfileMap);
903 if (auto EC = writeSummary())
904 return EC;
905
906 // Generate the name table for all the functions referenced in the profile.
907 for (const auto &I : ProfileMap) {
908 addContext(I.second.getContext());
909 addNames(I.second);
910 }
911
914}
915
920
924
925void SampleProfileWriterExtBinaryBase::allocSecHdrTable() {
927
928 Writer.write(static_cast<uint64_t>(SectionHdrLayout.size()));
929 SecHdrTableOffset = OutputStream->tell();
930 for (uint32_t i = 0; i < SectionHdrLayout.size(); i++) {
931 Writer.write(static_cast<uint64_t>(-1));
932 Writer.write(static_cast<uint64_t>(-1));
933 Writer.write(static_cast<uint64_t>(-1));
934 Writer.write(static_cast<uint64_t>(-1));
935 }
936}
937
938std::error_code SampleProfileWriterExtBinaryBase::writeSecHdrTable() {
939 assert(SecHdrTable.size() == SectionHdrLayout.size() &&
940 "SecHdrTable entries doesn't match SectionHdrLayout");
941 SmallVector<uint32_t, 16> IndexMap(SecHdrTable.size(), -1);
942 for (uint32_t TableIdx = 0; TableIdx < SecHdrTable.size(); TableIdx++) {
943 IndexMap[SecHdrTable[TableIdx].LayoutIndex] = TableIdx;
944 }
945
946 // Write the section header table in the order specified in
947 // SectionHdrLayout. SectionHdrLayout specifies the sections
948 // order in which profile reader expect to read, so the section
949 // header table should be written in the order in SectionHdrLayout.
950 // Note that the section order in SecHdrTable may be different
951 // from the order in SectionHdrLayout, for example, SecFuncOffsetTable
952 // needs to be computed after SecLBRProfile (the order in SecHdrTable),
953 // but it needs to be read before SecLBRProfile (the order in
954 // SectionHdrLayout). So we use IndexMap above to switch the order.
955 support::endian::SeekableWriter Writer(
956 static_cast<raw_pwrite_stream &>(*OutputStream),
958 for (uint32_t LayoutIdx = 0; LayoutIdx < SectionHdrLayout.size();
959 LayoutIdx++) {
960 assert(IndexMap[LayoutIdx] < SecHdrTable.size() &&
961 "Incorrect LayoutIdx in SecHdrTable");
962 auto Entry = SecHdrTable[IndexMap[LayoutIdx]];
963 Writer.pwrite(static_cast<uint64_t>(Entry.Type),
964 SecHdrTableOffset + 4 * LayoutIdx * sizeof(uint64_t));
965 Writer.pwrite(static_cast<uint64_t>(Entry.Flags),
966 SecHdrTableOffset + (4 * LayoutIdx + 1) * sizeof(uint64_t));
967 Writer.pwrite(static_cast<uint64_t>(Entry.Offset),
968 SecHdrTableOffset + (4 * LayoutIdx + 2) * sizeof(uint64_t));
969 Writer.pwrite(static_cast<uint64_t>(Entry.Size),
970 SecHdrTableOffset + (4 * LayoutIdx + 3) * sizeof(uint64_t));
971 }
972
974}
975
976std::error_code SampleProfileWriterExtBinaryBase::writeHeader(
977 const SampleProfileMap &ProfileMap) {
978 auto &OS = *OutputStream;
979 FileStart = OS.tell();
981
982 allocSecHdrTable();
984}
985
989 "writeCallsiteVTableProf should not be called if WriteVTableProf is "
990 "false");
991
992 encodeULEB128(CallsiteTypeMap.size(), OS);
993 for (const auto &[Loc, TypeMap] : CallsiteTypeMap) {
994 Loc.serialize(OS);
995 if (std::error_code EC = serializeTypeMap(TypeMap, getNameTable(), OS))
996 return EC;
997 }
998
1000}
1001
1003 auto &OS = *OutputStream;
1004 encodeULEB128(Summary->getTotalCount(), OS);
1005 encodeULEB128(Summary->getMaxCount(), OS);
1006 encodeULEB128(Summary->getMaxFunctionCount(), OS);
1007 encodeULEB128(Summary->getNumCounts(), OS);
1008 encodeULEB128(Summary->getNumFunctions(), OS);
1009 ArrayRef<ProfileSummaryEntry> Entries = Summary->getDetailedSummary();
1010 encodeULEB128(Entries.size(), OS);
1011 for (auto Entry : Entries) {
1012 encodeULEB128(Entry.Cutoff, OS);
1013 encodeULEB128(Entry.MinCount, OS);
1014 encodeULEB128(Entry.NumCounts, OS);
1015 }
1017}
1019 auto &OS = *OutputStream;
1020 if (std::error_code EC = writeContextIdx(S.getContext()))
1021 return EC;
1022
1024
1025 // Emit all the body samples.
1026 encodeULEB128(S.getBodySamples().size(), OS);
1027 for (const auto &I : S.getBodySamples()) {
1028 LineLocation Loc = I.first;
1029 const SampleRecord &Sample = I.second;
1030 Loc.serialize(OS);
1031 Sample.serialize(OS, getNameTable());
1032 }
1033
1034 // Recursively emit all the callsite samples.
1035 uint64_t NumCallsites = 0;
1036 for (const auto &J : S.getCallsiteSamples())
1037 NumCallsites += J.second.size();
1038 encodeULEB128(NumCallsites, OS);
1039 for (const auto &J : S.getCallsiteSamples())
1040 for (const auto &FS : J.second) {
1041 J.first.serialize(OS);
1042 if (std::error_code EC = writeBody(FS.second))
1043 return EC;
1044 }
1045
1046 if (WriteVTableProf)
1048
1050}
1051
1052/// Write samples of a top-level function to a binary file.
1053///
1054/// \returns true if the samples were written successfully, false otherwise.
1055std::error_code
1060
1061/// Create a sample profile file writer based on the specified format.
1062///
1063/// \param Filename The file to create.
1064///
1065/// \param Format Encoding format for the profile file.
1066///
1067/// \returns an error code indicating the status of the created writer.
1070 std::error_code EC;
1071 std::unique_ptr<raw_ostream> OS;
1073 OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_None));
1074 else
1076 if (EC)
1077 return EC;
1078
1079 return create(OS, Format);
1080}
1081
1082/// Create a sample profile stream writer based on the specified format.
1083///
1084/// \param OS The output stream to store the profile data to.
1085///
1086/// \param Format Encoding format for the profile file.
1087///
1088/// \returns an error code indicating the status of the created writer.
1090SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
1092 std::error_code EC;
1093 std::unique_ptr<SampleProfileWriter> Writer;
1094
1095 // Currently only Text and Extended Binary format are supported for CSSPGO.
1097 Format == SPF_Binary)
1099
1100 if (Format == SPF_Binary)
1101 Writer.reset(new SampleProfileWriterRawBinary(OS));
1102 else if (Format == SPF_Ext_Binary)
1103 Writer.reset(new SampleProfileWriterExtBinary(OS));
1104 else if (Format == SPF_Text)
1105 Writer.reset(new SampleProfileWriterText(OS));
1106 else if (Format == SPF_GCC)
1108 else
1110
1111 if (EC)
1112 return EC;
1113
1114 Writer->Format = Format;
1115 if (Format != SPF_Ext_Binary)
1116 Writer->setFormatVersion(DefaultVersion);
1118 Writer->setFormatVersion(RequestedVersion);
1119 else
1121 return std::move(Writer);
1122}
1123
1126 Summary = Builder.computeSummaryForProfiles(ProfileMap);
1127}
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.
This file defines the EytzingerTableSpan class, a non-owning view of a buffer formatted as a complete...
static uint64_t round(uint64_t Acc, uint64_t Input)
Definition KCFIHash.cpp:29
#define I(x, y, z)
Definition MD5.cpp:57
static constexpr StringLiteral Filename
static cl::opt< uint64_t > RequestedVersion("sample-profile-format-version", cl::init(DefaultVersion), cl::Hidden, cl::desc("Format version to write for extensible binary profiles"))
static SmallVector< std::pair< KeyT, ValT > *, 0 > stabilizeTable(MapVector< KeyT, ValT > &Table)
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"))
static cl::opt< bool > WriteMD5ProfSymList("md5-prof-sym-list", cl::init(false), cl::Hidden, cl::desc("Write ProfileSymbolList (Cold Symbols) as " "64-bit MD5 hashes in Eytzinger layout"))
static cl::opt< bool > WriteEytzingerNameTables("sample-profile-write-eytzinger-name-tables", cl::init(false), cl::Hidden, cl::desc("Write Eytzinger 3-span layout for NameTable"))
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Represents either an error or a value T.
Definition ErrorOr.h:56
Owning container that stores elements in a complete binary search tree formatted in Eytzinger (breadt...
Definition Eytzinger.h:123
static EytzingerTable< T > create(std::vector< KeyT > Keys)
Construct an Eytzinger search tree from a vector of keys by sorting, deduplicating,...
Definition Eytzinger.h:139
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
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
uint64_t tell() const
tell - Return the current offset with the file.
raw_ostream & write(unsigned char C)
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
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:815
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...
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:998
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.
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:703
This class provides operator overloads to the map container using MD5 as the key type,...
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 writeEytzingerNameTableSection(const SampleProfileMap &ProfileMap)
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.
uint64_t FormatVersion
Format version to write.
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:389
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:457
SortedCallTargetSet getSortedCallTargets() const
Definition SampleProf.h:458
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:112
static bool formatVersionIsSupported(uint64_t Version)
Definition SampleProf.h:130
static void addSecFlag(SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:286
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:302
std::pair< hash_code, const FunctionSamples * > NameFunctionSamples
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
Definition SampleProf.h:235
@ SecFlagHasVTableTypeProf
SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
Definition SampleProf.h:238
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
Definition SampleProf.h:232
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
Definition SampleProf.h:229
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
Definition SampleProf.h:805
static constexpr uint64_t DefaultVersion
Definition SampleProf.h:124
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:369
constexpr char kVTableProfPrefix[]
Definition SampleProf.h:95
LLVM_ABI std::error_code serializeTypeMap(const TypeCountMap &Map, const MapVector< FunctionId, uint32_t > &NameTable, raw_ostream &OS)
Write Map to the output stream.
std::map< LineLocation, TypeCountMap > CallsiteTypeMap
Definition SampleProf.h:807
detail::packed_endian_specific_integral< uint64_t, llvm::endianness::little, unaligned > ulittle64_t
Definition Endian.h:293
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:804
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:315
@ Offset
Definition DWP.cpp:578
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1399
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1409
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
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:79
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
endianness
Definition bit.h:71
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:747
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
Represents the relative location of an instruction.
Definition SampleProf.h:318
Adapter to write values to a stream in a particular byte order.
void write(ArrayRef< value_type > Val)