xref: /freebsd-src/contrib/llvm-project/llvm/lib/ProfileData/SampleProfWriter.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
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 
20 #include "llvm/ProfileData/SampleProfWriter.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/StringSet.h"
23 #include "llvm/ProfileData/ProfileCommon.h"
24 #include "llvm/ProfileData/SampleProf.h"
25 #include "llvm/Support/Compression.h"
26 #include "llvm/Support/Endian.h"
27 #include "llvm/Support/EndianStream.h"
28 #include "llvm/Support/ErrorOr.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/LEB128.h"
31 #include "llvm/Support/MD5.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 #include <cstdint>
35 #include <memory>
36 #include <set>
37 #include <system_error>
38 #include <utility>
39 #include <vector>
40 
41 using namespace llvm;
42 using namespace sampleprof;
43 
44 std::error_code SampleProfileWriter::writeFuncProfiles(
45     const StringMap<FunctionSamples> &ProfileMap) {
46   // Sort the ProfileMap by total samples.
47   typedef std::pair<StringRef, const FunctionSamples *> NameFunctionSamples;
48   std::vector<NameFunctionSamples> V;
49   for (const auto &I : ProfileMap)
50     V.push_back(std::make_pair(I.getKey(), &I.second));
51 
52   llvm::stable_sort(
53       V, [](const NameFunctionSamples &A, const NameFunctionSamples &B) {
54         if (A.second->getTotalSamples() == B.second->getTotalSamples())
55           return A.first > B.first;
56         return A.second->getTotalSamples() > B.second->getTotalSamples();
57       });
58 
59   for (const auto &I : V) {
60     if (std::error_code EC = writeSample(*I.second))
61       return EC;
62   }
63   return sampleprof_error::success;
64 }
65 
66 std::error_code
67 SampleProfileWriter::write(const StringMap<FunctionSamples> &ProfileMap) {
68   if (std::error_code EC = writeHeader(ProfileMap))
69     return EC;
70 
71   if (std::error_code EC = writeFuncProfiles(ProfileMap))
72     return EC;
73 
74   return sampleprof_error::success;
75 }
76 
77 /// Return the current position and prepare to use it as the start
78 /// position of a section given the section type \p Type and its position
79 /// \p LayoutIdx in SectionHdrLayout.
80 uint64_t
81 SampleProfileWriterExtBinaryBase::markSectionStart(SecType Type,
82                                                    uint32_t LayoutIdx) {
83   uint64_t SectionStart = OutputStream->tell();
84   assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range");
85   const auto &Entry = SectionHdrLayout[LayoutIdx];
86   assert(Entry.Type == Type && "Unexpected section type");
87   // Use LocalBuf as a temporary output for writting data.
88   if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress))
89     LocalBufStream.swap(OutputStream);
90   return SectionStart;
91 }
92 
93 std::error_code SampleProfileWriterExtBinaryBase::compressAndOutput() {
94   if (!llvm::zlib::isAvailable())
95     return sampleprof_error::zlib_unavailable;
96   std::string &UncompressedStrings =
97       static_cast<raw_string_ostream *>(LocalBufStream.get())->str();
98   if (UncompressedStrings.size() == 0)
99     return sampleprof_error::success;
100   auto &OS = *OutputStream;
101   SmallString<128> CompressedStrings;
102   llvm::Error E = zlib::compress(UncompressedStrings, CompressedStrings,
103                                  zlib::BestSizeCompression);
104   if (E)
105     return sampleprof_error::compress_failed;
106   encodeULEB128(UncompressedStrings.size(), OS);
107   encodeULEB128(CompressedStrings.size(), OS);
108   OS << CompressedStrings.str();
109   UncompressedStrings.clear();
110   return sampleprof_error::success;
111 }
112 
113 /// Add a new section into section header table given the section type
114 /// \p Type, its position \p LayoutIdx in SectionHdrLayout and the
115 /// location \p SectionStart where the section should be written to.
116 std::error_code SampleProfileWriterExtBinaryBase::addNewSection(
117     SecType Type, uint32_t LayoutIdx, uint64_t SectionStart) {
118   assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range");
119   const auto &Entry = SectionHdrLayout[LayoutIdx];
120   assert(Entry.Type == Type && "Unexpected section type");
121   if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress)) {
122     LocalBufStream.swap(OutputStream);
123     if (std::error_code EC = compressAndOutput())
124       return EC;
125   }
126   SecHdrTable.push_back({Type, Entry.Flags, SectionStart - FileStart,
127                          OutputStream->tell() - SectionStart, LayoutIdx});
128   return sampleprof_error::success;
129 }
130 
131 std::error_code SampleProfileWriterExtBinaryBase::write(
132     const StringMap<FunctionSamples> &ProfileMap) {
133   if (std::error_code EC = writeHeader(ProfileMap))
134     return EC;
135 
136   std::string LocalBuf;
137   LocalBufStream = std::make_unique<raw_string_ostream>(LocalBuf);
138   if (std::error_code EC = writeSections(ProfileMap))
139     return EC;
140 
141   if (std::error_code EC = writeSecHdrTable())
142     return EC;
143 
144   return sampleprof_error::success;
145 }
146 
147 std::error_code
148 SampleProfileWriterExtBinaryBase::writeSample(const FunctionSamples &S) {
149   uint64_t Offset = OutputStream->tell();
150   StringRef Name = S.getName();
151   FuncOffsetTable[Name] = Offset - SecLBRProfileStart;
152   encodeULEB128(S.getHeadSamples(), *OutputStream);
153   return writeBody(S);
154 }
155 
156 std::error_code SampleProfileWriterExtBinaryBase::writeFuncOffsetTable() {
157   auto &OS = *OutputStream;
158 
159   // Write out the table size.
160   encodeULEB128(FuncOffsetTable.size(), OS);
161 
162   // Write out FuncOffsetTable.
163   for (auto entry : FuncOffsetTable) {
164     writeNameIdx(entry.first);
165     encodeULEB128(entry.second, OS);
166   }
167   FuncOffsetTable.clear();
168   return sampleprof_error::success;
169 }
170 
171 std::error_code SampleProfileWriterExtBinaryBase::writeFuncMetadata(
172     const StringMap<FunctionSamples> &Profiles) {
173   if (!FunctionSamples::ProfileIsProbeBased)
174     return sampleprof_error::success;
175   auto &OS = *OutputStream;
176   for (const auto &Entry : Profiles) {
177     writeNameIdx(Entry.first());
178     encodeULEB128(Entry.second.getFunctionHash(), OS);
179   }
180   return sampleprof_error::success;
181 }
182 
183 std::error_code SampleProfileWriterExtBinaryBase::writeNameTable() {
184   if (!UseMD5)
185     return SampleProfileWriterBinary::writeNameTable();
186 
187   auto &OS = *OutputStream;
188   std::set<StringRef> V;
189   stablizeNameTable(V);
190 
191   // Write out the MD5 name table. We wrote unencoded MD5 so reader can
192   // retrieve the name using the name index without having to read the
193   // whole name table.
194   encodeULEB128(NameTable.size(), OS);
195   support::endian::Writer Writer(OS, support::little);
196   for (auto N : V)
197     Writer.write(MD5Hash(N));
198   return sampleprof_error::success;
199 }
200 
201 std::error_code SampleProfileWriterExtBinaryBase::writeNameTableSection(
202     const StringMap<FunctionSamples> &ProfileMap) {
203   for (const auto &I : ProfileMap) {
204     addName(I.first());
205     addNames(I.second);
206   }
207   if (auto EC = writeNameTable())
208     return EC;
209   return sampleprof_error::success;
210 }
211 
212 std::error_code
213 SampleProfileWriterExtBinaryBase::writeProfileSymbolListSection() {
214   if (ProfSymList && ProfSymList->size() > 0)
215     if (std::error_code EC = ProfSymList->write(*OutputStream))
216       return EC;
217 
218   return sampleprof_error::success;
219 }
220 
221 std::error_code SampleProfileWriterExtBinaryBase::writeOneSection(
222     SecType Type, uint32_t LayoutIdx,
223     const StringMap<FunctionSamples> &ProfileMap) {
224   // The setting of SecFlagCompress should happen before markSectionStart.
225   if (Type == SecProfileSymbolList && ProfSymList && ProfSymList->toCompress())
226     setToCompressSection(SecProfileSymbolList);
227   if (Type == SecFuncMetadata && FunctionSamples::ProfileIsProbeBased)
228     addSectionFlag(SecFuncMetadata, SecFuncMetadataFlags::SecFlagIsProbeBased);
229 
230   uint64_t SectionStart = markSectionStart(Type, LayoutIdx);
231   switch (Type) {
232   case SecProfSummary:
233     computeSummary(ProfileMap);
234     if (auto EC = writeSummary())
235       return EC;
236     break;
237   case SecNameTable:
238     if (auto EC = writeNameTableSection(ProfileMap))
239       return EC;
240     break;
241   case SecLBRProfile:
242     SecLBRProfileStart = OutputStream->tell();
243     if (std::error_code EC = writeFuncProfiles(ProfileMap))
244       return EC;
245     break;
246   case SecFuncOffsetTable:
247     if (auto EC = writeFuncOffsetTable())
248       return EC;
249     break;
250   case SecFuncMetadata:
251     if (std::error_code EC = writeFuncMetadata(ProfileMap))
252       return EC;
253     break;
254   case SecProfileSymbolList:
255     if (auto EC = writeProfileSymbolListSection())
256       return EC;
257     break;
258   default:
259     if (auto EC = writeCustomSection(Type))
260       return EC;
261     break;
262   }
263   if (std::error_code EC = addNewSection(Type, LayoutIdx, SectionStart))
264     return EC;
265   return sampleprof_error::success;
266 }
267 
268 std::error_code SampleProfileWriterExtBinary::writeDefaultLayout(
269     const StringMap<FunctionSamples> &ProfileMap) {
270   // The const indices passed to writeOneSection below are specifying the
271   // positions of the sections in SectionHdrLayout. Look at
272   // initSectionHdrLayout to find out where each section is located in
273   // SectionHdrLayout.
274   if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
275     return EC;
276   if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
277     return EC;
278   if (auto EC = writeOneSection(SecLBRProfile, 3, ProfileMap))
279     return EC;
280   if (auto EC = writeOneSection(SecProfileSymbolList, 4, ProfileMap))
281     return EC;
282   if (auto EC = writeOneSection(SecFuncOffsetTable, 2, ProfileMap))
283     return EC;
284   if (auto EC = writeOneSection(SecFuncMetadata, 5, ProfileMap))
285     return EC;
286   return sampleprof_error::success;
287 }
288 
289 static void
290 splitProfileMapToTwo(const StringMap<FunctionSamples> &ProfileMap,
291                      StringMap<FunctionSamples> &ContextProfileMap,
292                      StringMap<FunctionSamples> &NoContextProfileMap) {
293   for (const auto &I : ProfileMap) {
294     if (I.second.getCallsiteSamples().size())
295       ContextProfileMap.insert({I.first(), I.second});
296     else
297       NoContextProfileMap.insert({I.first(), I.second});
298   }
299 }
300 
301 std::error_code SampleProfileWriterExtBinary::writeCtxSplitLayout(
302     const StringMap<FunctionSamples> &ProfileMap) {
303   StringMap<FunctionSamples> ContextProfileMap, NoContextProfileMap;
304   splitProfileMapToTwo(ProfileMap, ContextProfileMap, NoContextProfileMap);
305 
306   if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
307     return EC;
308   if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
309     return EC;
310   if (auto EC = writeOneSection(SecLBRProfile, 3, ContextProfileMap))
311     return EC;
312   if (auto EC = writeOneSection(SecFuncOffsetTable, 2, ContextProfileMap))
313     return EC;
314   // Mark the section to have no context. Note section flag needs to be set
315   // before writing the section.
316   addSectionFlag(5, SecCommonFlags::SecFlagFlat);
317   if (auto EC = writeOneSection(SecLBRProfile, 5, NoContextProfileMap))
318     return EC;
319   // Mark the section to have no context. Note section flag needs to be set
320   // before writing the section.
321   addSectionFlag(4, SecCommonFlags::SecFlagFlat);
322   if (auto EC = writeOneSection(SecFuncOffsetTable, 4, NoContextProfileMap))
323     return EC;
324   if (auto EC = writeOneSection(SecProfileSymbolList, 6, ProfileMap))
325     return EC;
326   if (auto EC = writeOneSection(SecFuncMetadata, 7, ProfileMap))
327     return EC;
328 
329   return sampleprof_error::success;
330 }
331 
332 std::error_code SampleProfileWriterExtBinary::writeSections(
333     const StringMap<FunctionSamples> &ProfileMap) {
334   std::error_code EC;
335   if (SecLayout == DefaultLayout)
336     EC = writeDefaultLayout(ProfileMap);
337   else if (SecLayout == CtxSplitLayout)
338     EC = writeCtxSplitLayout(ProfileMap);
339   else
340     llvm_unreachable("Unsupported layout");
341   return EC;
342 }
343 
344 std::error_code SampleProfileWriterCompactBinary::write(
345     const StringMap<FunctionSamples> &ProfileMap) {
346   if (std::error_code EC = SampleProfileWriter::write(ProfileMap))
347     return EC;
348   if (std::error_code EC = writeFuncOffsetTable())
349     return EC;
350   return sampleprof_error::success;
351 }
352 
353 /// Write samples to a text file.
354 ///
355 /// Note: it may be tempting to implement this in terms of
356 /// FunctionSamples::print().  Please don't.  The dump functionality is intended
357 /// for debugging and has no specified form.
358 ///
359 /// The format used here is more structured and deliberate because
360 /// it needs to be parsed by the SampleProfileReaderText class.
361 std::error_code SampleProfileWriterText::writeSample(const FunctionSamples &S) {
362   auto &OS = *OutputStream;
363   if (FunctionSamples::ProfileIsCS)
364     OS << "[" << S.getNameWithContext() << "]:" << S.getTotalSamples();
365   else
366     OS << S.getName() << ":" << S.getTotalSamples();
367   if (Indent == 0)
368     OS << ":" << S.getHeadSamples();
369   OS << "\n";
370 
371   SampleSorter<LineLocation, SampleRecord> SortedSamples(S.getBodySamples());
372   for (const auto &I : SortedSamples.get()) {
373     LineLocation Loc = I->first;
374     const SampleRecord &Sample = I->second;
375     OS.indent(Indent + 1);
376     if (Loc.Discriminator == 0)
377       OS << Loc.LineOffset << ": ";
378     else
379       OS << Loc.LineOffset << "." << Loc.Discriminator << ": ";
380 
381     OS << Sample.getSamples();
382 
383     for (const auto &J : Sample.getSortedCallTargets())
384       OS << " " << J.first << ":" << J.second;
385     OS << "\n";
386   }
387 
388   SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples(
389       S.getCallsiteSamples());
390   Indent += 1;
391   for (const auto &I : SortedCallsiteSamples.get())
392     for (const auto &FS : I->second) {
393       LineLocation Loc = I->first;
394       const FunctionSamples &CalleeSamples = FS.second;
395       OS.indent(Indent);
396       if (Loc.Discriminator == 0)
397         OS << Loc.LineOffset << ": ";
398       else
399         OS << Loc.LineOffset << "." << Loc.Discriminator << ": ";
400       if (std::error_code EC = writeSample(CalleeSamples))
401         return EC;
402     }
403   Indent -= 1;
404 
405   if (Indent == 0) {
406     if (FunctionSamples::ProfileIsProbeBased) {
407       OS.indent(Indent + 1);
408       OS << "!CFGChecksum: " << S.getFunctionHash() << "\n";
409     }
410   }
411 
412   return sampleprof_error::success;
413 }
414 
415 std::error_code SampleProfileWriterBinary::writeNameIdx(StringRef FName) {
416   const auto &ret = NameTable.find(FName);
417   if (ret == NameTable.end())
418     return sampleprof_error::truncated_name_table;
419   encodeULEB128(ret->second, *OutputStream);
420   return sampleprof_error::success;
421 }
422 
423 void SampleProfileWriterBinary::addName(StringRef FName) {
424   NameTable.insert(std::make_pair(FName, 0));
425 }
426 
427 void SampleProfileWriterBinary::addNames(const FunctionSamples &S) {
428   // Add all the names in indirect call targets.
429   for (const auto &I : S.getBodySamples()) {
430     const SampleRecord &Sample = I.second;
431     for (const auto &J : Sample.getCallTargets())
432       addName(J.first());
433   }
434 
435   // Recursively add all the names for inlined callsites.
436   for (const auto &J : S.getCallsiteSamples())
437     for (const auto &FS : J.second) {
438       const FunctionSamples &CalleeSamples = FS.second;
439       addName(CalleeSamples.getName());
440       addNames(CalleeSamples);
441     }
442 }
443 
444 void SampleProfileWriterBinary::stablizeNameTable(std::set<StringRef> &V) {
445   // Sort the names to make NameTable deterministic.
446   for (const auto &I : NameTable)
447     V.insert(I.first);
448   int i = 0;
449   for (const StringRef &N : V)
450     NameTable[N] = i++;
451 }
452 
453 std::error_code SampleProfileWriterBinary::writeNameTable() {
454   auto &OS = *OutputStream;
455   std::set<StringRef> V;
456   stablizeNameTable(V);
457 
458   // Write out the name table.
459   encodeULEB128(NameTable.size(), OS);
460   for (auto N : V) {
461     OS << N;
462     encodeULEB128(0, OS);
463   }
464   return sampleprof_error::success;
465 }
466 
467 std::error_code SampleProfileWriterCompactBinary::writeFuncOffsetTable() {
468   auto &OS = *OutputStream;
469 
470   // Fill the slot remembered by TableOffset with the offset of FuncOffsetTable.
471   auto &OFS = static_cast<raw_fd_ostream &>(OS);
472   uint64_t FuncOffsetTableStart = OS.tell();
473   if (OFS.seek(TableOffset) == (uint64_t)-1)
474     return sampleprof_error::ostream_seek_unsupported;
475   support::endian::Writer Writer(*OutputStream, support::little);
476   Writer.write(FuncOffsetTableStart);
477   if (OFS.seek(FuncOffsetTableStart) == (uint64_t)-1)
478     return sampleprof_error::ostream_seek_unsupported;
479 
480   // Write out the table size.
481   encodeULEB128(FuncOffsetTable.size(), OS);
482 
483   // Write out FuncOffsetTable.
484   for (auto entry : FuncOffsetTable) {
485     writeNameIdx(entry.first);
486     encodeULEB128(entry.second, OS);
487   }
488   return sampleprof_error::success;
489 }
490 
491 std::error_code SampleProfileWriterCompactBinary::writeNameTable() {
492   auto &OS = *OutputStream;
493   std::set<StringRef> V;
494   stablizeNameTable(V);
495 
496   // Write out the name table.
497   encodeULEB128(NameTable.size(), OS);
498   for (auto N : V) {
499     encodeULEB128(MD5Hash(N), OS);
500   }
501   return sampleprof_error::success;
502 }
503 
504 std::error_code
505 SampleProfileWriterBinary::writeMagicIdent(SampleProfileFormat Format) {
506   auto &OS = *OutputStream;
507   // Write file magic identifier.
508   encodeULEB128(SPMagic(Format), OS);
509   encodeULEB128(SPVersion(), OS);
510   return sampleprof_error::success;
511 }
512 
513 std::error_code SampleProfileWriterBinary::writeHeader(
514     const StringMap<FunctionSamples> &ProfileMap) {
515   writeMagicIdent(Format);
516 
517   computeSummary(ProfileMap);
518   if (auto EC = writeSummary())
519     return EC;
520 
521   // Generate the name table for all the functions referenced in the profile.
522   for (const auto &I : ProfileMap) {
523     addName(I.first());
524     addNames(I.second);
525   }
526 
527   writeNameTable();
528   return sampleprof_error::success;
529 }
530 
531 void SampleProfileWriterExtBinaryBase::setToCompressAllSections() {
532   for (auto &Entry : SectionHdrLayout)
533     addSecFlag(Entry, SecCommonFlags::SecFlagCompress);
534 }
535 
536 void SampleProfileWriterExtBinaryBase::setToCompressSection(SecType Type) {
537   addSectionFlag(Type, SecCommonFlags::SecFlagCompress);
538 }
539 
540 void SampleProfileWriterExtBinaryBase::allocSecHdrTable() {
541   support::endian::Writer Writer(*OutputStream, support::little);
542 
543   Writer.write(static_cast<uint64_t>(SectionHdrLayout.size()));
544   SecHdrTableOffset = OutputStream->tell();
545   for (uint32_t i = 0; i < SectionHdrLayout.size(); i++) {
546     Writer.write(static_cast<uint64_t>(-1));
547     Writer.write(static_cast<uint64_t>(-1));
548     Writer.write(static_cast<uint64_t>(-1));
549     Writer.write(static_cast<uint64_t>(-1));
550   }
551 }
552 
553 std::error_code SampleProfileWriterExtBinaryBase::writeSecHdrTable() {
554   auto &OFS = static_cast<raw_fd_ostream &>(*OutputStream);
555   uint64_t Saved = OutputStream->tell();
556 
557   // Set OutputStream to the location saved in SecHdrTableOffset.
558   if (OFS.seek(SecHdrTableOffset) == (uint64_t)-1)
559     return sampleprof_error::ostream_seek_unsupported;
560   support::endian::Writer Writer(*OutputStream, support::little);
561 
562   assert(SecHdrTable.size() == SectionHdrLayout.size() &&
563          "SecHdrTable entries doesn't match SectionHdrLayout");
564   SmallVector<uint32_t, 16> IndexMap(SecHdrTable.size(), -1);
565   for (uint32_t TableIdx = 0; TableIdx < SecHdrTable.size(); TableIdx++) {
566     IndexMap[SecHdrTable[TableIdx].LayoutIndex] = TableIdx;
567   }
568 
569   // Write the section header table in the order specified in
570   // SectionHdrLayout. SectionHdrLayout specifies the sections
571   // order in which profile reader expect to read, so the section
572   // header table should be written in the order in SectionHdrLayout.
573   // Note that the section order in SecHdrTable may be different
574   // from the order in SectionHdrLayout, for example, SecFuncOffsetTable
575   // needs to be computed after SecLBRProfile (the order in SecHdrTable),
576   // but it needs to be read before SecLBRProfile (the order in
577   // SectionHdrLayout). So we use IndexMap above to switch the order.
578   for (uint32_t LayoutIdx = 0; LayoutIdx < SectionHdrLayout.size();
579        LayoutIdx++) {
580     assert(IndexMap[LayoutIdx] < SecHdrTable.size() &&
581            "Incorrect LayoutIdx in SecHdrTable");
582     auto Entry = SecHdrTable[IndexMap[LayoutIdx]];
583     Writer.write(static_cast<uint64_t>(Entry.Type));
584     Writer.write(static_cast<uint64_t>(Entry.Flags));
585     Writer.write(static_cast<uint64_t>(Entry.Offset));
586     Writer.write(static_cast<uint64_t>(Entry.Size));
587   }
588 
589   // Reset OutputStream.
590   if (OFS.seek(Saved) == (uint64_t)-1)
591     return sampleprof_error::ostream_seek_unsupported;
592 
593   return sampleprof_error::success;
594 }
595 
596 std::error_code SampleProfileWriterExtBinaryBase::writeHeader(
597     const StringMap<FunctionSamples> &ProfileMap) {
598   auto &OS = *OutputStream;
599   FileStart = OS.tell();
600   writeMagicIdent(Format);
601 
602   allocSecHdrTable();
603   return sampleprof_error::success;
604 }
605 
606 std::error_code SampleProfileWriterCompactBinary::writeHeader(
607     const StringMap<FunctionSamples> &ProfileMap) {
608   support::endian::Writer Writer(*OutputStream, support::little);
609   if (auto EC = SampleProfileWriterBinary::writeHeader(ProfileMap))
610     return EC;
611 
612   // Reserve a slot for the offset of function offset table. The slot will
613   // be populated with the offset of FuncOffsetTable later.
614   TableOffset = OutputStream->tell();
615   Writer.write(static_cast<uint64_t>(-2));
616   return sampleprof_error::success;
617 }
618 
619 std::error_code SampleProfileWriterBinary::writeSummary() {
620   auto &OS = *OutputStream;
621   encodeULEB128(Summary->getTotalCount(), OS);
622   encodeULEB128(Summary->getMaxCount(), OS);
623   encodeULEB128(Summary->getMaxFunctionCount(), OS);
624   encodeULEB128(Summary->getNumCounts(), OS);
625   encodeULEB128(Summary->getNumFunctions(), OS);
626   std::vector<ProfileSummaryEntry> &Entries = Summary->getDetailedSummary();
627   encodeULEB128(Entries.size(), OS);
628   for (auto Entry : Entries) {
629     encodeULEB128(Entry.Cutoff, OS);
630     encodeULEB128(Entry.MinCount, OS);
631     encodeULEB128(Entry.NumCounts, OS);
632   }
633   return sampleprof_error::success;
634 }
635 std::error_code SampleProfileWriterBinary::writeBody(const FunctionSamples &S) {
636   auto &OS = *OutputStream;
637 
638   if (std::error_code EC = writeNameIdx(S.getName()))
639     return EC;
640 
641   encodeULEB128(S.getTotalSamples(), OS);
642 
643   // Emit all the body samples.
644   encodeULEB128(S.getBodySamples().size(), OS);
645   for (const auto &I : S.getBodySamples()) {
646     LineLocation Loc = I.first;
647     const SampleRecord &Sample = I.second;
648     encodeULEB128(Loc.LineOffset, OS);
649     encodeULEB128(Loc.Discriminator, OS);
650     encodeULEB128(Sample.getSamples(), OS);
651     encodeULEB128(Sample.getCallTargets().size(), OS);
652     for (const auto &J : Sample.getSortedCallTargets()) {
653       StringRef Callee = J.first;
654       uint64_t CalleeSamples = J.second;
655       if (std::error_code EC = writeNameIdx(Callee))
656         return EC;
657       encodeULEB128(CalleeSamples, OS);
658     }
659   }
660 
661   // Recursively emit all the callsite samples.
662   uint64_t NumCallsites = 0;
663   for (const auto &J : S.getCallsiteSamples())
664     NumCallsites += J.second.size();
665   encodeULEB128(NumCallsites, OS);
666   for (const auto &J : S.getCallsiteSamples())
667     for (const auto &FS : J.second) {
668       LineLocation Loc = J.first;
669       const FunctionSamples &CalleeSamples = FS.second;
670       encodeULEB128(Loc.LineOffset, OS);
671       encodeULEB128(Loc.Discriminator, OS);
672       if (std::error_code EC = writeBody(CalleeSamples))
673         return EC;
674     }
675 
676   return sampleprof_error::success;
677 }
678 
679 /// Write samples of a top-level function to a binary file.
680 ///
681 /// \returns true if the samples were written successfully, false otherwise.
682 std::error_code
683 SampleProfileWriterBinary::writeSample(const FunctionSamples &S) {
684   encodeULEB128(S.getHeadSamples(), *OutputStream);
685   return writeBody(S);
686 }
687 
688 std::error_code
689 SampleProfileWriterCompactBinary::writeSample(const FunctionSamples &S) {
690   uint64_t Offset = OutputStream->tell();
691   StringRef Name = S.getName();
692   FuncOffsetTable[Name] = Offset;
693   encodeULEB128(S.getHeadSamples(), *OutputStream);
694   return writeBody(S);
695 }
696 
697 /// Create a sample profile file writer based on the specified format.
698 ///
699 /// \param Filename The file to create.
700 ///
701 /// \param Format Encoding format for the profile file.
702 ///
703 /// \returns an error code indicating the status of the created writer.
704 ErrorOr<std::unique_ptr<SampleProfileWriter>>
705 SampleProfileWriter::create(StringRef Filename, SampleProfileFormat Format) {
706   std::error_code EC;
707   std::unique_ptr<raw_ostream> OS;
708   if (Format == SPF_Binary || Format == SPF_Ext_Binary ||
709       Format == SPF_Compact_Binary)
710     OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_None));
711   else
712     OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_Text));
713   if (EC)
714     return EC;
715 
716   return create(OS, Format);
717 }
718 
719 /// Create a sample profile stream writer based on the specified format.
720 ///
721 /// \param OS The output stream to store the profile data to.
722 ///
723 /// \param Format Encoding format for the profile file.
724 ///
725 /// \returns an error code indicating the status of the created writer.
726 ErrorOr<std::unique_ptr<SampleProfileWriter>>
727 SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
728                             SampleProfileFormat Format) {
729   std::error_code EC;
730   std::unique_ptr<SampleProfileWriter> Writer;
731 
732   if (Format == SPF_Binary)
733     Writer.reset(new SampleProfileWriterRawBinary(OS));
734   else if (Format == SPF_Ext_Binary)
735     Writer.reset(new SampleProfileWriterExtBinary(OS));
736   else if (Format == SPF_Compact_Binary)
737     Writer.reset(new SampleProfileWriterCompactBinary(OS));
738   else if (Format == SPF_Text)
739     Writer.reset(new SampleProfileWriterText(OS));
740   else if (Format == SPF_GCC)
741     EC = sampleprof_error::unsupported_writing_format;
742   else
743     EC = sampleprof_error::unrecognized_format;
744 
745   if (EC)
746     return EC;
747 
748   Writer->Format = Format;
749   return std::move(Writer);
750 }
751 
752 void SampleProfileWriter::computeSummary(
753     const StringMap<FunctionSamples> &ProfileMap) {
754   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
755   for (const auto &I : ProfileMap) {
756     const FunctionSamples &Profile = I.second;
757     Builder.addRecord(Profile);
758   }
759   Summary = Builder.getSummary();
760 }
761