1 //===- InstrProfWriter.cpp - Instrumented profiling writer ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for writing profiling data for clang's
10 // instrumentation based PGO and coverage.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ProfileData/InstrProfWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/IR/ProfileSummary.h"
18 #include "llvm/ProfileData/InstrProf.h"
19 #include "llvm/ProfileData/MemProf.h"
20 #include "llvm/ProfileData/ProfileCommon.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/EndianStream.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/OnDiskHashTable.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 #include <cstdint>
29 #include <memory>
30 #include <string>
31 #include <tuple>
32 #include <utility>
33 #include <vector>
34 
35 using namespace llvm;
36 
37 // A struct to define how the data stream should be patched. For Indexed
38 // profiling, only uint64_t data type is needed.
39 struct PatchItem {
40   uint64_t Pos; // Where to patch.
41   uint64_t *D;  // Pointer to an array of source data.
42   int N;        // Number of elements in \c D array.
43 };
44 
45 namespace llvm {
46 
47 // A wrapper class to abstract writer stream with support of bytes
48 // back patching.
49 class ProfOStream {
50 public:
51   ProfOStream(raw_fd_ostream &FD)
52       : IsFDOStream(true), OS(FD), LE(FD, support::little) {}
53   ProfOStream(raw_string_ostream &STR)
54       : IsFDOStream(false), OS(STR), LE(STR, support::little) {}
55 
56   uint64_t tell() { return OS.tell(); }
57   void write(uint64_t V) { LE.write<uint64_t>(V); }
58 
59   // \c patch can only be called when all data is written and flushed.
60   // For raw_string_ostream, the patch is done on the target string
61   // directly and it won't be reflected in the stream's internal buffer.
62   void patch(PatchItem *P, int NItems) {
63     using namespace support;
64 
65     if (IsFDOStream) {
66       raw_fd_ostream &FDOStream = static_cast<raw_fd_ostream &>(OS);
67       const uint64_t LastPos = FDOStream.tell();
68       for (int K = 0; K < NItems; K++) {
69         FDOStream.seek(P[K].Pos);
70         for (int I = 0; I < P[K].N; I++)
71           write(P[K].D[I]);
72       }
73       // Reset the stream to the last position after patching so that users
74       // don't accidentally overwrite data. This makes it consistent with
75       // the string stream below which replaces the data directly.
76       FDOStream.seek(LastPos);
77     } else {
78       raw_string_ostream &SOStream = static_cast<raw_string_ostream &>(OS);
79       std::string &Data = SOStream.str(); // with flush
80       for (int K = 0; K < NItems; K++) {
81         for (int I = 0; I < P[K].N; I++) {
82           uint64_t Bytes = endian::byte_swap<uint64_t, little>(P[K].D[I]);
83           Data.replace(P[K].Pos + I * sizeof(uint64_t), sizeof(uint64_t),
84                        (const char *)&Bytes, sizeof(uint64_t));
85         }
86       }
87     }
88   }
89 
90   // If \c OS is an instance of \c raw_fd_ostream, this field will be
91   // true. Otherwise, \c OS will be an raw_string_ostream.
92   bool IsFDOStream;
93   raw_ostream &OS;
94   support::endian::Writer LE;
95 };
96 
97 class InstrProfRecordWriterTrait {
98 public:
99   using key_type = StringRef;
100   using key_type_ref = StringRef;
101 
102   using data_type = const InstrProfWriter::ProfilingData *const;
103   using data_type_ref = const InstrProfWriter::ProfilingData *const;
104 
105   using hash_value_type = uint64_t;
106   using offset_type = uint64_t;
107 
108   support::endianness ValueProfDataEndianness = support::little;
109   InstrProfSummaryBuilder *SummaryBuilder;
110   InstrProfSummaryBuilder *CSSummaryBuilder;
111 
112   InstrProfRecordWriterTrait() = default;
113 
114   static hash_value_type ComputeHash(key_type_ref K) {
115     return IndexedInstrProf::ComputeHash(K);
116   }
117 
118   static std::pair<offset_type, offset_type>
119   EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
120     using namespace support;
121 
122     endian::Writer LE(Out, little);
123 
124     offset_type N = K.size();
125     LE.write<offset_type>(N);
126 
127     offset_type M = 0;
128     for (const auto &ProfileData : *V) {
129       const InstrProfRecord &ProfRecord = ProfileData.second;
130       M += sizeof(uint64_t); // The function hash
131       M += sizeof(uint64_t); // The size of the Counts vector
132       M += ProfRecord.Counts.size() * sizeof(uint64_t);
133 
134       // Value data
135       M += ValueProfData::getSize(ProfileData.second);
136     }
137     LE.write<offset_type>(M);
138 
139     return std::make_pair(N, M);
140   }
141 
142   void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N) {
143     Out.write(K.data(), N);
144   }
145 
146   void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V, offset_type) {
147     using namespace support;
148 
149     endian::Writer LE(Out, little);
150     for (const auto &ProfileData : *V) {
151       const InstrProfRecord &ProfRecord = ProfileData.second;
152       if (NamedInstrProfRecord::hasCSFlagInHash(ProfileData.first))
153         CSSummaryBuilder->addRecord(ProfRecord);
154       else
155         SummaryBuilder->addRecord(ProfRecord);
156 
157       LE.write<uint64_t>(ProfileData.first); // Function hash
158       LE.write<uint64_t>(ProfRecord.Counts.size());
159       for (uint64_t I : ProfRecord.Counts)
160         LE.write<uint64_t>(I);
161 
162       // Write value data
163       std::unique_ptr<ValueProfData> VDataPtr =
164           ValueProfData::serializeFrom(ProfileData.second);
165       uint32_t S = VDataPtr->getSize();
166       VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
167       Out.write((const char *)VDataPtr.get(), S);
168     }
169   }
170 };
171 
172 } // end namespace llvm
173 
174 InstrProfWriter::InstrProfWriter(bool Sparse)
175     : Sparse(Sparse), InfoObj(new InstrProfRecordWriterTrait()) {}
176 
177 InstrProfWriter::~InstrProfWriter() { delete InfoObj; }
178 
179 // Internal interface for testing purpose only.
180 void InstrProfWriter::setValueProfDataEndianness(
181     support::endianness Endianness) {
182   InfoObj->ValueProfDataEndianness = Endianness;
183 }
184 
185 void InstrProfWriter::setOutputSparse(bool Sparse) {
186   this->Sparse = Sparse;
187 }
188 
189 void InstrProfWriter::addRecord(NamedInstrProfRecord &&I, uint64_t Weight,
190                                 function_ref<void(Error)> Warn) {
191   auto Name = I.Name;
192   auto Hash = I.Hash;
193   addRecord(Name, Hash, std::move(I), Weight, Warn);
194 }
195 
196 void InstrProfWriter::overlapRecord(NamedInstrProfRecord &&Other,
197                                     OverlapStats &Overlap,
198                                     OverlapStats &FuncLevelOverlap,
199                                     const OverlapFuncFilters &FuncFilter) {
200   auto Name = Other.Name;
201   auto Hash = Other.Hash;
202   Other.accumulateCounts(FuncLevelOverlap.Test);
203   if (FunctionData.find(Name) == FunctionData.end()) {
204     Overlap.addOneUnique(FuncLevelOverlap.Test);
205     return;
206   }
207   if (FuncLevelOverlap.Test.CountSum < 1.0f) {
208     Overlap.Overlap.NumEntries += 1;
209     return;
210   }
211   auto &ProfileDataMap = FunctionData[Name];
212   bool NewFunc;
213   ProfilingData::iterator Where;
214   std::tie(Where, NewFunc) =
215       ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
216   if (NewFunc) {
217     Overlap.addOneMismatch(FuncLevelOverlap.Test);
218     return;
219   }
220   InstrProfRecord &Dest = Where->second;
221 
222   uint64_t ValueCutoff = FuncFilter.ValueCutoff;
223   if (!FuncFilter.NameFilter.empty() && Name.contains(FuncFilter.NameFilter))
224     ValueCutoff = 0;
225 
226   Dest.overlap(Other, Overlap, FuncLevelOverlap, ValueCutoff);
227 }
228 
229 void InstrProfWriter::addRecord(StringRef Name, uint64_t Hash,
230                                 InstrProfRecord &&I, uint64_t Weight,
231                                 function_ref<void(Error)> Warn) {
232   auto &ProfileDataMap = FunctionData[Name];
233 
234   bool NewFunc;
235   ProfilingData::iterator Where;
236   std::tie(Where, NewFunc) =
237       ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
238   InstrProfRecord &Dest = Where->second;
239 
240   auto MapWarn = [&](instrprof_error E) {
241     Warn(make_error<InstrProfError>(E));
242   };
243 
244   if (NewFunc) {
245     // We've never seen a function with this name and hash, add it.
246     Dest = std::move(I);
247     if (Weight > 1)
248       Dest.scale(Weight, 1, MapWarn);
249   } else {
250     // We're updating a function we've seen before.
251     Dest.merge(I, Weight, MapWarn);
252   }
253 
254   Dest.sortValueData();
255 }
256 
257 void InstrProfWriter::addRecord(const memprof::MemProfRecord &MR,
258                                 function_ref<void(Error)> Warn) {
259   // Use 0 as a sentinel value since its highly unlikely that the lower 64-bits
260   // of a 128 bit md5 hash will be all zeros.
261   // TODO: Move this Key frame detection to the contructor to avoid having to
262   // scan all the callstacks again when adding a new record.
263   uint64_t Key = 0;
264   for (auto Iter = MR.CallStack.rbegin(), End = MR.CallStack.rend();
265        Iter != End; Iter++) {
266     if (!Iter->IsInlineFrame) {
267       Key = Iter->Function;
268       break;
269     }
270   }
271 
272   if (Key == 0) {
273     Warn(make_error<InstrProfError>(
274         instrprof_error::invalid_prof,
275         "could not determine leaf function for memprof record."));
276   }
277 
278   MemProfData[Key].push_back(MR);
279 }
280 
281 void InstrProfWriter::mergeRecordsFromWriter(InstrProfWriter &&IPW,
282                                              function_ref<void(Error)> Warn) {
283   for (auto &I : IPW.FunctionData)
284     for (auto &Func : I.getValue())
285       addRecord(I.getKey(), Func.first, std::move(Func.second), 1, Warn);
286 
287   for (auto &I : IPW.MemProfData)
288     for (const auto &MR : I.second)
289       addRecord(MR, Warn);
290 }
291 
292 bool InstrProfWriter::shouldEncodeData(const ProfilingData &PD) {
293   if (!Sparse)
294     return true;
295   for (const auto &Func : PD) {
296     const InstrProfRecord &IPR = Func.second;
297     if (llvm::any_of(IPR.Counts, [](uint64_t Count) { return Count > 0; }))
298       return true;
299   }
300   return false;
301 }
302 
303 static void setSummary(IndexedInstrProf::Summary *TheSummary,
304                        ProfileSummary &PS) {
305   using namespace IndexedInstrProf;
306 
307   const std::vector<ProfileSummaryEntry> &Res = PS.getDetailedSummary();
308   TheSummary->NumSummaryFields = Summary::NumKinds;
309   TheSummary->NumCutoffEntries = Res.size();
310   TheSummary->set(Summary::MaxFunctionCount, PS.getMaxFunctionCount());
311   TheSummary->set(Summary::MaxBlockCount, PS.getMaxCount());
312   TheSummary->set(Summary::MaxInternalBlockCount, PS.getMaxInternalCount());
313   TheSummary->set(Summary::TotalBlockCount, PS.getTotalCount());
314   TheSummary->set(Summary::TotalNumBlocks, PS.getNumCounts());
315   TheSummary->set(Summary::TotalNumFunctions, PS.getNumFunctions());
316   for (unsigned I = 0; I < Res.size(); I++)
317     TheSummary->setEntry(I, Res[I]);
318 }
319 
320 Error InstrProfWriter::writeImpl(ProfOStream &OS) {
321   using namespace IndexedInstrProf;
322 
323   OnDiskChainedHashTableGenerator<InstrProfRecordWriterTrait> Generator;
324 
325   InstrProfSummaryBuilder ISB(ProfileSummaryBuilder::DefaultCutoffs);
326   InfoObj->SummaryBuilder = &ISB;
327   InstrProfSummaryBuilder CSISB(ProfileSummaryBuilder::DefaultCutoffs);
328   InfoObj->CSSummaryBuilder = &CSISB;
329 
330   // Populate the hash table generator.
331   for (const auto &I : FunctionData)
332     if (shouldEncodeData(I.getValue()))
333       Generator.insert(I.getKey(), &I.getValue());
334 
335   // Write the header.
336   IndexedInstrProf::Header Header;
337   Header.Magic = IndexedInstrProf::Magic;
338   Header.Version = IndexedInstrProf::ProfVersion::CurrentVersion;
339   if (static_cast<bool>(ProfileKind & InstrProfKind::IRInstrumentation))
340     Header.Version |= VARIANT_MASK_IR_PROF;
341   if (static_cast<bool>(ProfileKind & InstrProfKind::ContextSensitive))
342     Header.Version |= VARIANT_MASK_CSIR_PROF;
343   if (static_cast<bool>(ProfileKind &
344                         InstrProfKind::FunctionEntryInstrumentation))
345     Header.Version |= VARIANT_MASK_INSTR_ENTRY;
346   if (static_cast<bool>(ProfileKind & InstrProfKind::SingleByteCoverage))
347     Header.Version |= VARIANT_MASK_BYTE_COVERAGE;
348   if (static_cast<bool>(ProfileKind & InstrProfKind::FunctionEntryOnly))
349     Header.Version |= VARIANT_MASK_FUNCTION_ENTRY_ONLY;
350   if (static_cast<bool>(ProfileKind & InstrProfKind::MemProf))
351     Header.Version |= VARIANT_MASK_MEMPROF;
352 
353   Header.Unused = 0;
354   Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
355   Header.HashOffset = 0;
356   Header.MemProfOffset = 0;
357   int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
358 
359   // Only write out all the fields except 'HashOffset' and 'MemProfOffset'. We
360   // need to remember the offset of these fields to allow back patching later.
361   for (int I = 0; I < N - 2; I++)
362     OS.write(reinterpret_cast<uint64_t *>(&Header)[I]);
363 
364   // Save the location of Header.HashOffset field in \c OS.
365   uint64_t HashTableStartFieldOffset = OS.tell();
366   // Reserve the space for HashOffset field.
367   OS.write(0);
368 
369   // Save the location of MemProf profile data. This is stored in two parts as
370   // the schema and as a separate on-disk chained hashtable.
371   uint64_t MemProfSectionOffset = OS.tell();
372   // Reserve space for the MemProf table field to be patched later if this
373   // profile contains memory profile information.
374   OS.write(0);
375 
376   // Reserve space to write profile summary data.
377   uint32_t NumEntries = ProfileSummaryBuilder::DefaultCutoffs.size();
378   uint32_t SummarySize = Summary::getSize(Summary::NumKinds, NumEntries);
379   // Remember the summary offset.
380   uint64_t SummaryOffset = OS.tell();
381   for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
382     OS.write(0);
383   uint64_t CSSummaryOffset = 0;
384   uint64_t CSSummarySize = 0;
385   if (static_cast<bool>(ProfileKind & InstrProfKind::ContextSensitive)) {
386     CSSummaryOffset = OS.tell();
387     CSSummarySize = SummarySize / sizeof(uint64_t);
388     for (unsigned I = 0; I < CSSummarySize; I++)
389       OS.write(0);
390   }
391 
392   // Write the hash table.
393   uint64_t HashTableStart = Generator.Emit(OS.OS, *InfoObj);
394 
395   // Write the MemProf profile data if we have it. This includes a simple schema
396   // with the format described below followed by the hashtable:
397   // uint64_t Offset = MemProfGenerator.Emit
398   // uint64_t Num schema entries
399   // uint64_t Schema entry 0
400   // uint64_t Schema entry 1
401   // ....
402   // uint64_t Schema entry N - 1
403   // OnDiskChainedHashTable MemProfFunctionData
404   uint64_t MemProfSectionStart = 0;
405   if (static_cast<bool>(ProfileKind & InstrProfKind::MemProf)) {
406     MemProfSectionStart = OS.tell();
407     OS.write(0ULL); // Reserve space for the offset.
408 
409     auto Schema = memprof::PortableMemInfoBlock::getSchema();
410     OS.write(static_cast<uint64_t>(Schema.size()));
411     for (const auto Id : Schema) {
412       OS.write(static_cast<uint64_t>(Id));
413     }
414 
415     auto MemProfWriter = std::make_unique<memprof::MemProfRecordWriterTrait>();
416     MemProfWriter->Schema = &Schema;
417     OnDiskChainedHashTableGenerator<memprof::MemProfRecordWriterTrait>
418         MemProfGenerator;
419     for (const auto &I : MemProfData) {
420       // Insert the key (func hash) and value (vector of memprof records).
421       MemProfGenerator.insert(I.first, I.second);
422     }
423 
424     uint64_t TableOffset = MemProfGenerator.Emit(OS.OS, *MemProfWriter);
425     PatchItem PatchItems[] = {
426         {MemProfSectionStart, &TableOffset, 1},
427     };
428     OS.patch(PatchItems, 1);
429   }
430 
431   // Allocate space for data to be serialized out.
432   std::unique_ptr<IndexedInstrProf::Summary> TheSummary =
433       IndexedInstrProf::allocSummary(SummarySize);
434   // Compute the Summary and copy the data to the data
435   // structure to be serialized out (to disk or buffer).
436   std::unique_ptr<ProfileSummary> PS = ISB.getSummary();
437   setSummary(TheSummary.get(), *PS);
438   InfoObj->SummaryBuilder = nullptr;
439 
440   // For Context Sensitive summary.
441   std::unique_ptr<IndexedInstrProf::Summary> TheCSSummary = nullptr;
442   if (static_cast<bool>(ProfileKind & InstrProfKind::ContextSensitive)) {
443     TheCSSummary = IndexedInstrProf::allocSummary(SummarySize);
444     std::unique_ptr<ProfileSummary> CSPS = CSISB.getSummary();
445     setSummary(TheCSSummary.get(), *CSPS);
446   }
447   InfoObj->CSSummaryBuilder = nullptr;
448 
449   // Now do the final patch:
450   PatchItem PatchItems[] = {
451       // Patch the Header.HashOffset field.
452       {HashTableStartFieldOffset, &HashTableStart, 1},
453       // Patch the Header.MemProfOffset (=0 for profiles without MemProf data).
454       {MemProfSectionOffset, &MemProfSectionStart, 1},
455       // Patch the summary data.
456       {SummaryOffset, reinterpret_cast<uint64_t *>(TheSummary.get()),
457        (int)(SummarySize / sizeof(uint64_t))},
458       {CSSummaryOffset, reinterpret_cast<uint64_t *>(TheCSSummary.get()),
459        (int)CSSummarySize}};
460 
461   OS.patch(PatchItems, sizeof(PatchItems) / sizeof(*PatchItems));
462 
463   for (const auto &I : FunctionData)
464     for (const auto &F : I.getValue())
465       if (Error E = validateRecord(F.second))
466         return E;
467 
468   return Error::success();
469 }
470 
471 Error InstrProfWriter::write(raw_fd_ostream &OS) {
472   // Write the hash table.
473   ProfOStream POS(OS);
474   return writeImpl(POS);
475 }
476 
477 std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
478   std::string Data;
479   raw_string_ostream OS(Data);
480   ProfOStream POS(OS);
481   // Write the hash table.
482   if (Error E = writeImpl(POS))
483     return nullptr;
484   // Return this in an aligned memory buffer.
485   return MemoryBuffer::getMemBufferCopy(Data);
486 }
487 
488 static const char *ValueProfKindStr[] = {
489 #define VALUE_PROF_KIND(Enumerator, Value, Descr) #Enumerator,
490 #include "llvm/ProfileData/InstrProfData.inc"
491 };
492 
493 Error InstrProfWriter::validateRecord(const InstrProfRecord &Func) {
494   for (uint32_t VK = 0; VK <= IPVK_Last; VK++) {
495     uint32_t NS = Func.getNumValueSites(VK);
496     if (!NS)
497       continue;
498     for (uint32_t S = 0; S < NS; S++) {
499       uint32_t ND = Func.getNumValueDataForSite(VK, S);
500       std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
501       bool WasZero = false;
502       for (uint32_t I = 0; I < ND; I++)
503         if ((VK != IPVK_IndirectCallTarget) && (VD[I].Value == 0)) {
504           if (WasZero)
505             return make_error<InstrProfError>(instrprof_error::invalid_prof);
506           WasZero = true;
507         }
508     }
509   }
510 
511   return Error::success();
512 }
513 
514 void InstrProfWriter::writeRecordInText(StringRef Name, uint64_t Hash,
515                                         const InstrProfRecord &Func,
516                                         InstrProfSymtab &Symtab,
517                                         raw_fd_ostream &OS) {
518   OS << Name << "\n";
519   OS << "# Func Hash:\n" << Hash << "\n";
520   OS << "# Num Counters:\n" << Func.Counts.size() << "\n";
521   OS << "# Counter Values:\n";
522   for (uint64_t Count : Func.Counts)
523     OS << Count << "\n";
524 
525   uint32_t NumValueKinds = Func.getNumValueKinds();
526   if (!NumValueKinds) {
527     OS << "\n";
528     return;
529   }
530 
531   OS << "# Num Value Kinds:\n" << Func.getNumValueKinds() << "\n";
532   for (uint32_t VK = 0; VK < IPVK_Last + 1; VK++) {
533     uint32_t NS = Func.getNumValueSites(VK);
534     if (!NS)
535       continue;
536     OS << "# ValueKind = " << ValueProfKindStr[VK] << ":\n" << VK << "\n";
537     OS << "# NumValueSites:\n" << NS << "\n";
538     for (uint32_t S = 0; S < NS; S++) {
539       uint32_t ND = Func.getNumValueDataForSite(VK, S);
540       OS << ND << "\n";
541       std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
542       for (uint32_t I = 0; I < ND; I++) {
543         if (VK == IPVK_IndirectCallTarget)
544           OS << Symtab.getFuncNameOrExternalSymbol(VD[I].Value) << ":"
545              << VD[I].Count << "\n";
546         else
547           OS << VD[I].Value << ":" << VD[I].Count << "\n";
548       }
549     }
550   }
551 
552   OS << "\n";
553 }
554 
555 Error InstrProfWriter::writeText(raw_fd_ostream &OS) {
556   // Check CS first since it implies an IR level profile.
557   if (static_cast<bool>(ProfileKind & InstrProfKind::ContextSensitive))
558     OS << "# CSIR level Instrumentation Flag\n:csir\n";
559   else if (static_cast<bool>(ProfileKind & InstrProfKind::IRInstrumentation))
560     OS << "# IR level Instrumentation Flag\n:ir\n";
561 
562   if (static_cast<bool>(ProfileKind &
563                         InstrProfKind::FunctionEntryInstrumentation))
564     OS << "# Always instrument the function entry block\n:entry_first\n";
565   InstrProfSymtab Symtab;
566 
567   using FuncPair = detail::DenseMapPair<uint64_t, InstrProfRecord>;
568   using RecordType = std::pair<StringRef, FuncPair>;
569   SmallVector<RecordType, 4> OrderedFuncData;
570 
571   for (const auto &I : FunctionData) {
572     if (shouldEncodeData(I.getValue())) {
573       if (Error E = Symtab.addFuncName(I.getKey()))
574         return E;
575       for (const auto &Func : I.getValue())
576         OrderedFuncData.push_back(std::make_pair(I.getKey(), Func));
577     }
578   }
579 
580   llvm::sort(OrderedFuncData, [](const RecordType &A, const RecordType &B) {
581     return std::tie(A.first, A.second.first) <
582            std::tie(B.first, B.second.first);
583   });
584 
585   for (const auto &record : OrderedFuncData) {
586     const StringRef &Name = record.first;
587     const FuncPair &Func = record.second;
588     writeRecordInText(Name, Func.first, Func.second, Symtab, OS);
589   }
590 
591   for (const auto &record : OrderedFuncData) {
592     const FuncPair &Func = record.second;
593     if (Error E = validateRecord(Func.second))
594       return E;
595   }
596 
597   return Error::success();
598 }
599