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.getNameWithContext(true);
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 
208   // If NameTable contains ".__uniq." suffix, set SecFlagUniqSuffix flag
209   // so compiler won't strip the suffix during profile matching after
210   // seeing the flag in the profile.
211   for (const auto &I : NameTable) {
212     if (I.first.find(FunctionSamples::UniqSuffix) != StringRef::npos) {
213       addSectionFlag(SecNameTable, SecNameTableFlags::SecFlagUniqSuffix);
214       break;
215     }
216   }
217 
218   if (auto EC = writeNameTable())
219     return EC;
220   return sampleprof_error::success;
221 }
222 
223 std::error_code
224 SampleProfileWriterExtBinaryBase::writeProfileSymbolListSection() {
225   if (ProfSymList && ProfSymList->size() > 0)
226     if (std::error_code EC = ProfSymList->write(*OutputStream))
227       return EC;
228 
229   return sampleprof_error::success;
230 }
231 
232 std::error_code SampleProfileWriterExtBinaryBase::writeOneSection(
233     SecType Type, uint32_t LayoutIdx,
234     const StringMap<FunctionSamples> &ProfileMap) {
235   // The setting of SecFlagCompress should happen before markSectionStart.
236   if (Type == SecProfileSymbolList && ProfSymList && ProfSymList->toCompress())
237     setToCompressSection(SecProfileSymbolList);
238   if (Type == SecFuncMetadata && FunctionSamples::ProfileIsProbeBased)
239     addSectionFlag(SecFuncMetadata, SecFuncMetadataFlags::SecFlagIsProbeBased);
240   if (Type == SecProfSummary && FunctionSamples::ProfileIsCS)
241     addSectionFlag(SecProfSummary, SecProfSummaryFlags::SecFlagFullContext);
242 
243   uint64_t SectionStart = markSectionStart(Type, LayoutIdx);
244   switch (Type) {
245   case SecProfSummary:
246     computeSummary(ProfileMap);
247     if (auto EC = writeSummary())
248       return EC;
249     break;
250   case SecNameTable:
251     if (auto EC = writeNameTableSection(ProfileMap))
252       return EC;
253     break;
254   case SecLBRProfile:
255     SecLBRProfileStart = OutputStream->tell();
256     if (std::error_code EC = writeFuncProfiles(ProfileMap))
257       return EC;
258     break;
259   case SecFuncOffsetTable:
260     if (auto EC = writeFuncOffsetTable())
261       return EC;
262     break;
263   case SecFuncMetadata:
264     if (std::error_code EC = writeFuncMetadata(ProfileMap))
265       return EC;
266     break;
267   case SecProfileSymbolList:
268     if (auto EC = writeProfileSymbolListSection())
269       return EC;
270     break;
271   default:
272     if (auto EC = writeCustomSection(Type))
273       return EC;
274     break;
275   }
276   if (std::error_code EC = addNewSection(Type, LayoutIdx, SectionStart))
277     return EC;
278   return sampleprof_error::success;
279 }
280 
281 std::error_code SampleProfileWriterExtBinary::writeDefaultLayout(
282     const StringMap<FunctionSamples> &ProfileMap) {
283   // The const indices passed to writeOneSection below are specifying the
284   // positions of the sections in SectionHdrLayout. Look at
285   // initSectionHdrLayout to find out where each section is located in
286   // SectionHdrLayout.
287   if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
288     return EC;
289   if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
290     return EC;
291   if (auto EC = writeOneSection(SecLBRProfile, 3, ProfileMap))
292     return EC;
293   if (auto EC = writeOneSection(SecProfileSymbolList, 4, ProfileMap))
294     return EC;
295   if (auto EC = writeOneSection(SecFuncOffsetTable, 2, ProfileMap))
296     return EC;
297   if (auto EC = writeOneSection(SecFuncMetadata, 5, ProfileMap))
298     return EC;
299   return sampleprof_error::success;
300 }
301 
302 static void
303 splitProfileMapToTwo(const StringMap<FunctionSamples> &ProfileMap,
304                      StringMap<FunctionSamples> &ContextProfileMap,
305                      StringMap<FunctionSamples> &NoContextProfileMap) {
306   for (const auto &I : ProfileMap) {
307     if (I.second.getCallsiteSamples().size())
308       ContextProfileMap.insert({I.first(), I.second});
309     else
310       NoContextProfileMap.insert({I.first(), I.second});
311   }
312 }
313 
314 std::error_code SampleProfileWriterExtBinary::writeCtxSplitLayout(
315     const StringMap<FunctionSamples> &ProfileMap) {
316   StringMap<FunctionSamples> ContextProfileMap, NoContextProfileMap;
317   splitProfileMapToTwo(ProfileMap, ContextProfileMap, NoContextProfileMap);
318 
319   if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap))
320     return EC;
321   if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap))
322     return EC;
323   if (auto EC = writeOneSection(SecLBRProfile, 3, ContextProfileMap))
324     return EC;
325   if (auto EC = writeOneSection(SecFuncOffsetTable, 2, ContextProfileMap))
326     return EC;
327   // Mark the section to have no context. Note section flag needs to be set
328   // before writing the section.
329   addSectionFlag(5, SecCommonFlags::SecFlagFlat);
330   if (auto EC = writeOneSection(SecLBRProfile, 5, NoContextProfileMap))
331     return EC;
332   // Mark the section to have no context. Note section flag needs to be set
333   // before writing the section.
334   addSectionFlag(4, SecCommonFlags::SecFlagFlat);
335   if (auto EC = writeOneSection(SecFuncOffsetTable, 4, NoContextProfileMap))
336     return EC;
337   if (auto EC = writeOneSection(SecProfileSymbolList, 6, ProfileMap))
338     return EC;
339   if (auto EC = writeOneSection(SecFuncMetadata, 7, ProfileMap))
340     return EC;
341 
342   return sampleprof_error::success;
343 }
344 
345 std::error_code SampleProfileWriterExtBinary::writeSections(
346     const StringMap<FunctionSamples> &ProfileMap) {
347   std::error_code EC;
348   if (SecLayout == DefaultLayout)
349     EC = writeDefaultLayout(ProfileMap);
350   else if (SecLayout == CtxSplitLayout)
351     EC = writeCtxSplitLayout(ProfileMap);
352   else
353     llvm_unreachable("Unsupported layout");
354   return EC;
355 }
356 
357 std::error_code SampleProfileWriterCompactBinary::write(
358     const StringMap<FunctionSamples> &ProfileMap) {
359   if (std::error_code EC = SampleProfileWriter::write(ProfileMap))
360     return EC;
361   if (std::error_code EC = writeFuncOffsetTable())
362     return EC;
363   return sampleprof_error::success;
364 }
365 
366 /// Write samples to a text file.
367 ///
368 /// Note: it may be tempting to implement this in terms of
369 /// FunctionSamples::print().  Please don't.  The dump functionality is intended
370 /// for debugging and has no specified form.
371 ///
372 /// The format used here is more structured and deliberate because
373 /// it needs to be parsed by the SampleProfileReaderText class.
374 std::error_code SampleProfileWriterText::writeSample(const FunctionSamples &S) {
375   auto &OS = *OutputStream;
376   OS << S.getNameWithContext(true) << ":" << S.getTotalSamples();
377   if (Indent == 0)
378     OS << ":" << S.getHeadSamples();
379   OS << "\n";
380 
381   SampleSorter<LineLocation, SampleRecord> SortedSamples(S.getBodySamples());
382   for (const auto &I : SortedSamples.get()) {
383     LineLocation Loc = I->first;
384     const SampleRecord &Sample = I->second;
385     OS.indent(Indent + 1);
386     if (Loc.Discriminator == 0)
387       OS << Loc.LineOffset << ": ";
388     else
389       OS << Loc.LineOffset << "." << Loc.Discriminator << ": ";
390 
391     OS << Sample.getSamples();
392 
393     for (const auto &J : Sample.getSortedCallTargets())
394       OS << " " << J.first << ":" << J.second;
395     OS << "\n";
396   }
397 
398   SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples(
399       S.getCallsiteSamples());
400   Indent += 1;
401   for (const auto &I : SortedCallsiteSamples.get())
402     for (const auto &FS : I->second) {
403       LineLocation Loc = I->first;
404       const FunctionSamples &CalleeSamples = FS.second;
405       OS.indent(Indent);
406       if (Loc.Discriminator == 0)
407         OS << Loc.LineOffset << ": ";
408       else
409         OS << Loc.LineOffset << "." << Loc.Discriminator << ": ";
410       if (std::error_code EC = writeSample(CalleeSamples))
411         return EC;
412     }
413   Indent -= 1;
414 
415   if (Indent == 0) {
416     if (FunctionSamples::ProfileIsProbeBased) {
417       OS.indent(Indent + 1);
418       OS << "!CFGChecksum: " << S.getFunctionHash() << "\n";
419     }
420   }
421 
422   return sampleprof_error::success;
423 }
424 
425 std::error_code SampleProfileWriterBinary::writeNameIdx(StringRef FName) {
426   const auto &ret = NameTable.find(FName);
427   if (ret == NameTable.end())
428     return sampleprof_error::truncated_name_table;
429   encodeULEB128(ret->second, *OutputStream);
430   return sampleprof_error::success;
431 }
432 
433 void SampleProfileWriterBinary::addName(StringRef FName) {
434   NameTable.insert(std::make_pair(FName, 0));
435 }
436 
437 void SampleProfileWriterBinary::addNames(const FunctionSamples &S) {
438   // Add all the names in indirect call targets.
439   for (const auto &I : S.getBodySamples()) {
440     const SampleRecord &Sample = I.second;
441     for (const auto &J : Sample.getCallTargets())
442       addName(J.first());
443   }
444 
445   // Recursively add all the names for inlined callsites.
446   for (const auto &J : S.getCallsiteSamples())
447     for (const auto &FS : J.second) {
448       const FunctionSamples &CalleeSamples = FS.second;
449       addName(CalleeSamples.getName());
450       addNames(CalleeSamples);
451     }
452 }
453 
454 void SampleProfileWriterBinary::stablizeNameTable(std::set<StringRef> &V) {
455   // Sort the names to make NameTable deterministic.
456   for (const auto &I : NameTable)
457     V.insert(I.first);
458   int i = 0;
459   for (const StringRef &N : V)
460     NameTable[N] = i++;
461 }
462 
463 std::error_code SampleProfileWriterBinary::writeNameTable() {
464   auto &OS = *OutputStream;
465   std::set<StringRef> V;
466   stablizeNameTable(V);
467 
468   // Write out the name table.
469   encodeULEB128(NameTable.size(), OS);
470   for (auto N : V) {
471     OS << N;
472     encodeULEB128(0, OS);
473   }
474   return sampleprof_error::success;
475 }
476 
477 std::error_code SampleProfileWriterCompactBinary::writeFuncOffsetTable() {
478   auto &OS = *OutputStream;
479 
480   // Fill the slot remembered by TableOffset with the offset of FuncOffsetTable.
481   auto &OFS = static_cast<raw_fd_ostream &>(OS);
482   uint64_t FuncOffsetTableStart = OS.tell();
483   if (OFS.seek(TableOffset) == (uint64_t)-1)
484     return sampleprof_error::ostream_seek_unsupported;
485   support::endian::Writer Writer(*OutputStream, support::little);
486   Writer.write(FuncOffsetTableStart);
487   if (OFS.seek(FuncOffsetTableStart) == (uint64_t)-1)
488     return sampleprof_error::ostream_seek_unsupported;
489 
490   // Write out the table size.
491   encodeULEB128(FuncOffsetTable.size(), OS);
492 
493   // Write out FuncOffsetTable.
494   for (auto entry : FuncOffsetTable) {
495     writeNameIdx(entry.first);
496     encodeULEB128(entry.second, OS);
497   }
498   return sampleprof_error::success;
499 }
500 
501 std::error_code SampleProfileWriterCompactBinary::writeNameTable() {
502   auto &OS = *OutputStream;
503   std::set<StringRef> V;
504   stablizeNameTable(V);
505 
506   // Write out the name table.
507   encodeULEB128(NameTable.size(), OS);
508   for (auto N : V) {
509     encodeULEB128(MD5Hash(N), OS);
510   }
511   return sampleprof_error::success;
512 }
513 
514 std::error_code
515 SampleProfileWriterBinary::writeMagicIdent(SampleProfileFormat Format) {
516   auto &OS = *OutputStream;
517   // Write file magic identifier.
518   encodeULEB128(SPMagic(Format), OS);
519   encodeULEB128(SPVersion(), OS);
520   return sampleprof_error::success;
521 }
522 
523 std::error_code SampleProfileWriterBinary::writeHeader(
524     const StringMap<FunctionSamples> &ProfileMap) {
525   writeMagicIdent(Format);
526 
527   computeSummary(ProfileMap);
528   if (auto EC = writeSummary())
529     return EC;
530 
531   // Generate the name table for all the functions referenced in the profile.
532   for (const auto &I : ProfileMap) {
533     addName(I.first());
534     addNames(I.second);
535   }
536 
537   writeNameTable();
538   return sampleprof_error::success;
539 }
540 
541 void SampleProfileWriterExtBinaryBase::setToCompressAllSections() {
542   for (auto &Entry : SectionHdrLayout)
543     addSecFlag(Entry, SecCommonFlags::SecFlagCompress);
544 }
545 
546 void SampleProfileWriterExtBinaryBase::setToCompressSection(SecType Type) {
547   addSectionFlag(Type, SecCommonFlags::SecFlagCompress);
548 }
549 
550 void SampleProfileWriterExtBinaryBase::allocSecHdrTable() {
551   support::endian::Writer Writer(*OutputStream, support::little);
552 
553   Writer.write(static_cast<uint64_t>(SectionHdrLayout.size()));
554   SecHdrTableOffset = OutputStream->tell();
555   for (uint32_t i = 0; i < SectionHdrLayout.size(); i++) {
556     Writer.write(static_cast<uint64_t>(-1));
557     Writer.write(static_cast<uint64_t>(-1));
558     Writer.write(static_cast<uint64_t>(-1));
559     Writer.write(static_cast<uint64_t>(-1));
560   }
561 }
562 
563 std::error_code SampleProfileWriterExtBinaryBase::writeSecHdrTable() {
564   auto &OFS = static_cast<raw_fd_ostream &>(*OutputStream);
565   uint64_t Saved = OutputStream->tell();
566 
567   // Set OutputStream to the location saved in SecHdrTableOffset.
568   if (OFS.seek(SecHdrTableOffset) == (uint64_t)-1)
569     return sampleprof_error::ostream_seek_unsupported;
570   support::endian::Writer Writer(*OutputStream, support::little);
571 
572   assert(SecHdrTable.size() == SectionHdrLayout.size() &&
573          "SecHdrTable entries doesn't match SectionHdrLayout");
574   SmallVector<uint32_t, 16> IndexMap(SecHdrTable.size(), -1);
575   for (uint32_t TableIdx = 0; TableIdx < SecHdrTable.size(); TableIdx++) {
576     IndexMap[SecHdrTable[TableIdx].LayoutIndex] = TableIdx;
577   }
578 
579   // Write the section header table in the order specified in
580   // SectionHdrLayout. SectionHdrLayout specifies the sections
581   // order in which profile reader expect to read, so the section
582   // header table should be written in the order in SectionHdrLayout.
583   // Note that the section order in SecHdrTable may be different
584   // from the order in SectionHdrLayout, for example, SecFuncOffsetTable
585   // needs to be computed after SecLBRProfile (the order in SecHdrTable),
586   // but it needs to be read before SecLBRProfile (the order in
587   // SectionHdrLayout). So we use IndexMap above to switch the order.
588   for (uint32_t LayoutIdx = 0; LayoutIdx < SectionHdrLayout.size();
589        LayoutIdx++) {
590     assert(IndexMap[LayoutIdx] < SecHdrTable.size() &&
591            "Incorrect LayoutIdx in SecHdrTable");
592     auto Entry = SecHdrTable[IndexMap[LayoutIdx]];
593     Writer.write(static_cast<uint64_t>(Entry.Type));
594     Writer.write(static_cast<uint64_t>(Entry.Flags));
595     Writer.write(static_cast<uint64_t>(Entry.Offset));
596     Writer.write(static_cast<uint64_t>(Entry.Size));
597   }
598 
599   // Reset OutputStream.
600   if (OFS.seek(Saved) == (uint64_t)-1)
601     return sampleprof_error::ostream_seek_unsupported;
602 
603   return sampleprof_error::success;
604 }
605 
606 std::error_code SampleProfileWriterExtBinaryBase::writeHeader(
607     const StringMap<FunctionSamples> &ProfileMap) {
608   auto &OS = *OutputStream;
609   FileStart = OS.tell();
610   writeMagicIdent(Format);
611 
612   allocSecHdrTable();
613   return sampleprof_error::success;
614 }
615 
616 std::error_code SampleProfileWriterCompactBinary::writeHeader(
617     const StringMap<FunctionSamples> &ProfileMap) {
618   support::endian::Writer Writer(*OutputStream, support::little);
619   if (auto EC = SampleProfileWriterBinary::writeHeader(ProfileMap))
620     return EC;
621 
622   // Reserve a slot for the offset of function offset table. The slot will
623   // be populated with the offset of FuncOffsetTable later.
624   TableOffset = OutputStream->tell();
625   Writer.write(static_cast<uint64_t>(-2));
626   return sampleprof_error::success;
627 }
628 
629 std::error_code SampleProfileWriterBinary::writeSummary() {
630   auto &OS = *OutputStream;
631   encodeULEB128(Summary->getTotalCount(), OS);
632   encodeULEB128(Summary->getMaxCount(), OS);
633   encodeULEB128(Summary->getMaxFunctionCount(), OS);
634   encodeULEB128(Summary->getNumCounts(), OS);
635   encodeULEB128(Summary->getNumFunctions(), OS);
636   std::vector<ProfileSummaryEntry> &Entries = Summary->getDetailedSummary();
637   encodeULEB128(Entries.size(), OS);
638   for (auto Entry : Entries) {
639     encodeULEB128(Entry.Cutoff, OS);
640     encodeULEB128(Entry.MinCount, OS);
641     encodeULEB128(Entry.NumCounts, OS);
642   }
643   return sampleprof_error::success;
644 }
645 std::error_code SampleProfileWriterBinary::writeBody(const FunctionSamples &S) {
646   auto &OS = *OutputStream;
647 
648   if (std::error_code EC = writeNameIdx(S.getNameWithContext(true)))
649     return EC;
650 
651   encodeULEB128(S.getTotalSamples(), OS);
652 
653   // Emit all the body samples.
654   encodeULEB128(S.getBodySamples().size(), OS);
655   for (const auto &I : S.getBodySamples()) {
656     LineLocation Loc = I.first;
657     const SampleRecord &Sample = I.second;
658     encodeULEB128(Loc.LineOffset, OS);
659     encodeULEB128(Loc.Discriminator, OS);
660     encodeULEB128(Sample.getSamples(), OS);
661     encodeULEB128(Sample.getCallTargets().size(), OS);
662     for (const auto &J : Sample.getSortedCallTargets()) {
663       StringRef Callee = J.first;
664       uint64_t CalleeSamples = J.second;
665       if (std::error_code EC = writeNameIdx(Callee))
666         return EC;
667       encodeULEB128(CalleeSamples, OS);
668     }
669   }
670 
671   // Recursively emit all the callsite samples.
672   uint64_t NumCallsites = 0;
673   for (const auto &J : S.getCallsiteSamples())
674     NumCallsites += J.second.size();
675   encodeULEB128(NumCallsites, OS);
676   for (const auto &J : S.getCallsiteSamples())
677     for (const auto &FS : J.second) {
678       LineLocation Loc = J.first;
679       const FunctionSamples &CalleeSamples = FS.second;
680       encodeULEB128(Loc.LineOffset, OS);
681       encodeULEB128(Loc.Discriminator, OS);
682       if (std::error_code EC = writeBody(CalleeSamples))
683         return EC;
684     }
685 
686   return sampleprof_error::success;
687 }
688 
689 /// Write samples of a top-level function to a binary file.
690 ///
691 /// \returns true if the samples were written successfully, false otherwise.
692 std::error_code
693 SampleProfileWriterBinary::writeSample(const FunctionSamples &S) {
694   encodeULEB128(S.getHeadSamples(), *OutputStream);
695   return writeBody(S);
696 }
697 
698 std::error_code
699 SampleProfileWriterCompactBinary::writeSample(const FunctionSamples &S) {
700   uint64_t Offset = OutputStream->tell();
701   StringRef Name = S.getName();
702   FuncOffsetTable[Name] = Offset;
703   encodeULEB128(S.getHeadSamples(), *OutputStream);
704   return writeBody(S);
705 }
706 
707 /// Create a sample profile file writer based on the specified format.
708 ///
709 /// \param Filename The file to create.
710 ///
711 /// \param Format Encoding format for the profile file.
712 ///
713 /// \returns an error code indicating the status of the created writer.
714 ErrorOr<std::unique_ptr<SampleProfileWriter>>
715 SampleProfileWriter::create(StringRef Filename, SampleProfileFormat Format) {
716   std::error_code EC;
717   std::unique_ptr<raw_ostream> OS;
718   if (Format == SPF_Binary || Format == SPF_Ext_Binary ||
719       Format == SPF_Compact_Binary)
720     OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_None));
721   else
722     OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_Text));
723   if (EC)
724     return EC;
725 
726   return create(OS, Format);
727 }
728 
729 /// Create a sample profile stream writer based on the specified format.
730 ///
731 /// \param OS The output stream to store the profile data to.
732 ///
733 /// \param Format Encoding format for the profile file.
734 ///
735 /// \returns an error code indicating the status of the created writer.
736 ErrorOr<std::unique_ptr<SampleProfileWriter>>
737 SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
738                             SampleProfileFormat Format) {
739   std::error_code EC;
740   std::unique_ptr<SampleProfileWriter> Writer;
741 
742   if (Format == SPF_Binary)
743     Writer.reset(new SampleProfileWriterRawBinary(OS));
744   else if (Format == SPF_Ext_Binary)
745     Writer.reset(new SampleProfileWriterExtBinary(OS));
746   else if (Format == SPF_Compact_Binary)
747     Writer.reset(new SampleProfileWriterCompactBinary(OS));
748   else if (Format == SPF_Text)
749     Writer.reset(new SampleProfileWriterText(OS));
750   else if (Format == SPF_GCC)
751     EC = sampleprof_error::unsupported_writing_format;
752   else
753     EC = sampleprof_error::unrecognized_format;
754 
755   if (EC)
756     return EC;
757 
758   Writer->Format = Format;
759   return std::move(Writer);
760 }
761 
762 void SampleProfileWriter::computeSummary(
763     const StringMap<FunctionSamples> &ProfileMap) {
764   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
765   Summary = Builder.computeSummaryForProfiles(ProfileMap);
766 }
767