xref: /freebsd-src/contrib/llvm-project/llvm/lib/ProfileData/InstrProfWriter.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
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/ProfileCommon.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/EndianStream.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/OnDiskHashTable.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <algorithm>
27 #include <cstdint>
28 #include <memory>
29 #include <string>
30 #include <tuple>
31 #include <utility>
32 #include <vector>
33 
34 using namespace llvm;
35 extern cl::opt<bool> DebugInfoCorrelate;
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       for (int K = 0; K < NItems; K++) {
68         FDOStream.seek(P[K].Pos);
69         for (int I = 0; I < P[K].N; I++)
70           write(P[K].D[I]);
71       }
72     } else {
73       raw_string_ostream &SOStream = static_cast<raw_string_ostream &>(OS);
74       std::string &Data = SOStream.str(); // with flush
75       for (int K = 0; K < NItems; K++) {
76         for (int I = 0; I < P[K].N; I++) {
77           uint64_t Bytes = endian::byte_swap<uint64_t, little>(P[K].D[I]);
78           Data.replace(P[K].Pos + I * sizeof(uint64_t), sizeof(uint64_t),
79                        (const char *)&Bytes, sizeof(uint64_t));
80         }
81       }
82     }
83   }
84 
85   // If \c OS is an instance of \c raw_fd_ostream, this field will be
86   // true. Otherwise, \c OS will be an raw_string_ostream.
87   bool IsFDOStream;
88   raw_ostream &OS;
89   support::endian::Writer LE;
90 };
91 
92 class InstrProfRecordWriterTrait {
93 public:
94   using key_type = StringRef;
95   using key_type_ref = StringRef;
96 
97   using data_type = const InstrProfWriter::ProfilingData *const;
98   using data_type_ref = const InstrProfWriter::ProfilingData *const;
99 
100   using hash_value_type = uint64_t;
101   using offset_type = uint64_t;
102 
103   support::endianness ValueProfDataEndianness = support::little;
104   InstrProfSummaryBuilder *SummaryBuilder;
105   InstrProfSummaryBuilder *CSSummaryBuilder;
106 
107   InstrProfRecordWriterTrait() = default;
108 
109   static hash_value_type ComputeHash(key_type_ref K) {
110     return IndexedInstrProf::ComputeHash(K);
111   }
112 
113   static std::pair<offset_type, offset_type>
114   EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
115     using namespace support;
116 
117     endian::Writer LE(Out, little);
118 
119     offset_type N = K.size();
120     LE.write<offset_type>(N);
121 
122     offset_type M = 0;
123     for (const auto &ProfileData : *V) {
124       const InstrProfRecord &ProfRecord = ProfileData.second;
125       M += sizeof(uint64_t); // The function hash
126       M += sizeof(uint64_t); // The size of the Counts vector
127       M += ProfRecord.Counts.size() * sizeof(uint64_t);
128 
129       // Value data
130       M += ValueProfData::getSize(ProfileData.second);
131     }
132     LE.write<offset_type>(M);
133 
134     return std::make_pair(N, M);
135   }
136 
137   void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N) {
138     Out.write(K.data(), N);
139   }
140 
141   void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V, offset_type) {
142     using namespace support;
143 
144     endian::Writer LE(Out, little);
145     for (const auto &ProfileData : *V) {
146       const InstrProfRecord &ProfRecord = ProfileData.second;
147       if (NamedInstrProfRecord::hasCSFlagInHash(ProfileData.first))
148         CSSummaryBuilder->addRecord(ProfRecord);
149       else
150         SummaryBuilder->addRecord(ProfRecord);
151 
152       LE.write<uint64_t>(ProfileData.first); // Function hash
153       LE.write<uint64_t>(ProfRecord.Counts.size());
154       for (uint64_t I : ProfRecord.Counts)
155         LE.write<uint64_t>(I);
156 
157       // Write value data
158       std::unique_ptr<ValueProfData> VDataPtr =
159           ValueProfData::serializeFrom(ProfileData.second);
160       uint32_t S = VDataPtr->getSize();
161       VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
162       Out.write((const char *)VDataPtr.get(), S);
163     }
164   }
165 };
166 
167 } // end namespace llvm
168 
169 InstrProfWriter::InstrProfWriter(bool Sparse, bool InstrEntryBBEnabled)
170     : Sparse(Sparse), InstrEntryBBEnabled(InstrEntryBBEnabled),
171       InfoObj(new InstrProfRecordWriterTrait()) {}
172 
173 InstrProfWriter::~InstrProfWriter() { delete InfoObj; }
174 
175 // Internal interface for testing purpose only.
176 void InstrProfWriter::setValueProfDataEndianness(
177     support::endianness Endianness) {
178   InfoObj->ValueProfDataEndianness = Endianness;
179 }
180 
181 void InstrProfWriter::setOutputSparse(bool Sparse) {
182   this->Sparse = Sparse;
183 }
184 
185 void InstrProfWriter::addRecord(NamedInstrProfRecord &&I, uint64_t Weight,
186                                 function_ref<void(Error)> Warn) {
187   auto Name = I.Name;
188   auto Hash = I.Hash;
189   addRecord(Name, Hash, std::move(I), Weight, Warn);
190 }
191 
192 void InstrProfWriter::overlapRecord(NamedInstrProfRecord &&Other,
193                                     OverlapStats &Overlap,
194                                     OverlapStats &FuncLevelOverlap,
195                                     const OverlapFuncFilters &FuncFilter) {
196   auto Name = Other.Name;
197   auto Hash = Other.Hash;
198   Other.accumulateCounts(FuncLevelOverlap.Test);
199   if (FunctionData.find(Name) == FunctionData.end()) {
200     Overlap.addOneUnique(FuncLevelOverlap.Test);
201     return;
202   }
203   if (FuncLevelOverlap.Test.CountSum < 1.0f) {
204     Overlap.Overlap.NumEntries += 1;
205     return;
206   }
207   auto &ProfileDataMap = FunctionData[Name];
208   bool NewFunc;
209   ProfilingData::iterator Where;
210   std::tie(Where, NewFunc) =
211       ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
212   if (NewFunc) {
213     Overlap.addOneMismatch(FuncLevelOverlap.Test);
214     return;
215   }
216   InstrProfRecord &Dest = Where->second;
217 
218   uint64_t ValueCutoff = FuncFilter.ValueCutoff;
219   if (!FuncFilter.NameFilter.empty() && Name.contains(FuncFilter.NameFilter))
220     ValueCutoff = 0;
221 
222   Dest.overlap(Other, Overlap, FuncLevelOverlap, ValueCutoff);
223 }
224 
225 void InstrProfWriter::addRecord(StringRef Name, uint64_t Hash,
226                                 InstrProfRecord &&I, uint64_t Weight,
227                                 function_ref<void(Error)> Warn) {
228   auto &ProfileDataMap = FunctionData[Name];
229 
230   bool NewFunc;
231   ProfilingData::iterator Where;
232   std::tie(Where, NewFunc) =
233       ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
234   InstrProfRecord &Dest = Where->second;
235 
236   auto MapWarn = [&](instrprof_error E) {
237     Warn(make_error<InstrProfError>(E));
238   };
239 
240   if (NewFunc) {
241     // We've never seen a function with this name and hash, add it.
242     Dest = std::move(I);
243     if (Weight > 1)
244       Dest.scale(Weight, 1, MapWarn);
245   } else {
246     // We're updating a function we've seen before.
247     Dest.merge(I, Weight, MapWarn);
248   }
249 
250   Dest.sortValueData();
251 }
252 
253 void InstrProfWriter::mergeRecordsFromWriter(InstrProfWriter &&IPW,
254                                              function_ref<void(Error)> Warn) {
255   for (auto &I : IPW.FunctionData)
256     for (auto &Func : I.getValue())
257       addRecord(I.getKey(), Func.first, std::move(Func.second), 1, Warn);
258 }
259 
260 bool InstrProfWriter::shouldEncodeData(const ProfilingData &PD) {
261   if (!Sparse)
262     return true;
263   for (const auto &Func : PD) {
264     const InstrProfRecord &IPR = Func.second;
265     if (llvm::any_of(IPR.Counts, [](uint64_t Count) { return Count > 0; }))
266       return true;
267   }
268   return false;
269 }
270 
271 static void setSummary(IndexedInstrProf::Summary *TheSummary,
272                        ProfileSummary &PS) {
273   using namespace IndexedInstrProf;
274 
275   const std::vector<ProfileSummaryEntry> &Res = PS.getDetailedSummary();
276   TheSummary->NumSummaryFields = Summary::NumKinds;
277   TheSummary->NumCutoffEntries = Res.size();
278   TheSummary->set(Summary::MaxFunctionCount, PS.getMaxFunctionCount());
279   TheSummary->set(Summary::MaxBlockCount, PS.getMaxCount());
280   TheSummary->set(Summary::MaxInternalBlockCount, PS.getMaxInternalCount());
281   TheSummary->set(Summary::TotalBlockCount, PS.getTotalCount());
282   TheSummary->set(Summary::TotalNumBlocks, PS.getNumCounts());
283   TheSummary->set(Summary::TotalNumFunctions, PS.getNumFunctions());
284   for (unsigned I = 0; I < Res.size(); I++)
285     TheSummary->setEntry(I, Res[I]);
286 }
287 
288 Error InstrProfWriter::writeImpl(ProfOStream &OS) {
289   using namespace IndexedInstrProf;
290 
291   OnDiskChainedHashTableGenerator<InstrProfRecordWriterTrait> Generator;
292 
293   InstrProfSummaryBuilder ISB(ProfileSummaryBuilder::DefaultCutoffs);
294   InfoObj->SummaryBuilder = &ISB;
295   InstrProfSummaryBuilder CSISB(ProfileSummaryBuilder::DefaultCutoffs);
296   InfoObj->CSSummaryBuilder = &CSISB;
297 
298   // Populate the hash table generator.
299   for (const auto &I : FunctionData)
300     if (shouldEncodeData(I.getValue()))
301       Generator.insert(I.getKey(), &I.getValue());
302   // Write the header.
303   IndexedInstrProf::Header Header;
304   Header.Magic = IndexedInstrProf::Magic;
305   Header.Version = IndexedInstrProf::ProfVersion::CurrentVersion;
306   if (ProfileKind == PF_IRLevel)
307     Header.Version |= VARIANT_MASK_IR_PROF;
308   if (ProfileKind == PF_IRLevelWithCS) {
309     Header.Version |= VARIANT_MASK_IR_PROF;
310     Header.Version |= VARIANT_MASK_CSIR_PROF;
311   }
312   if (InstrEntryBBEnabled)
313     Header.Version |= VARIANT_MASK_INSTR_ENTRY;
314 
315   Header.Unused = 0;
316   Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
317   Header.HashOffset = 0;
318   int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
319 
320   // Only write out all the fields except 'HashOffset'. We need
321   // to remember the offset of that field to allow back patching
322   // later.
323   for (int I = 0; I < N - 1; I++)
324     OS.write(reinterpret_cast<uint64_t *>(&Header)[I]);
325 
326   // Save the location of Header.HashOffset field in \c OS.
327   uint64_t HashTableStartFieldOffset = OS.tell();
328   // Reserve the space for HashOffset field.
329   OS.write(0);
330 
331   // Reserve space to write profile summary data.
332   uint32_t NumEntries = ProfileSummaryBuilder::DefaultCutoffs.size();
333   uint32_t SummarySize = Summary::getSize(Summary::NumKinds, NumEntries);
334   // Remember the summary offset.
335   uint64_t SummaryOffset = OS.tell();
336   for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
337     OS.write(0);
338   uint64_t CSSummaryOffset = 0;
339   uint64_t CSSummarySize = 0;
340   if (ProfileKind == PF_IRLevelWithCS) {
341     CSSummaryOffset = OS.tell();
342     CSSummarySize = SummarySize / sizeof(uint64_t);
343     for (unsigned I = 0; I < CSSummarySize; I++)
344       OS.write(0);
345   }
346 
347   // Write the hash table.
348   uint64_t HashTableStart = Generator.Emit(OS.OS, *InfoObj);
349 
350   // Allocate space for data to be serialized out.
351   std::unique_ptr<IndexedInstrProf::Summary> TheSummary =
352       IndexedInstrProf::allocSummary(SummarySize);
353   // Compute the Summary and copy the data to the data
354   // structure to be serialized out (to disk or buffer).
355   std::unique_ptr<ProfileSummary> PS = ISB.getSummary();
356   setSummary(TheSummary.get(), *PS);
357   InfoObj->SummaryBuilder = nullptr;
358 
359   // For Context Sensitive summary.
360   std::unique_ptr<IndexedInstrProf::Summary> TheCSSummary = nullptr;
361   if (ProfileKind == PF_IRLevelWithCS) {
362     TheCSSummary = IndexedInstrProf::allocSummary(SummarySize);
363     std::unique_ptr<ProfileSummary> CSPS = CSISB.getSummary();
364     setSummary(TheCSSummary.get(), *CSPS);
365   }
366   InfoObj->CSSummaryBuilder = nullptr;
367 
368   // Now do the final patch:
369   PatchItem PatchItems[] = {
370       // Patch the Header.HashOffset field.
371       {HashTableStartFieldOffset, &HashTableStart, 1},
372       // Patch the summary data.
373       {SummaryOffset, reinterpret_cast<uint64_t *>(TheSummary.get()),
374        (int)(SummarySize / sizeof(uint64_t))},
375       {CSSummaryOffset, reinterpret_cast<uint64_t *>(TheCSSummary.get()),
376        (int)CSSummarySize}};
377 
378   OS.patch(PatchItems, sizeof(PatchItems) / sizeof(*PatchItems));
379 
380   for (const auto &I : FunctionData)
381     for (const auto &F : I.getValue())
382       if (Error E = validateRecord(F.second))
383         return E;
384 
385   return Error::success();
386 }
387 
388 Error InstrProfWriter::write(raw_fd_ostream &OS) {
389   // Write the hash table.
390   ProfOStream POS(OS);
391   return writeImpl(POS);
392 }
393 
394 std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
395   std::string Data;
396   raw_string_ostream OS(Data);
397   ProfOStream POS(OS);
398   // Write the hash table.
399   if (Error E = writeImpl(POS))
400     return nullptr;
401   // Return this in an aligned memory buffer.
402   return MemoryBuffer::getMemBufferCopy(Data);
403 }
404 
405 static const char *ValueProfKindStr[] = {
406 #define VALUE_PROF_KIND(Enumerator, Value, Descr) #Enumerator,
407 #include "llvm/ProfileData/InstrProfData.inc"
408 };
409 
410 Error InstrProfWriter::validateRecord(const InstrProfRecord &Func) {
411   for (uint32_t VK = 0; VK <= IPVK_Last; VK++) {
412     uint32_t NS = Func.getNumValueSites(VK);
413     if (!NS)
414       continue;
415     for (uint32_t S = 0; S < NS; S++) {
416       uint32_t ND = Func.getNumValueDataForSite(VK, S);
417       std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
418       bool WasZero = false;
419       for (uint32_t I = 0; I < ND; I++)
420         if ((VK != IPVK_IndirectCallTarget) && (VD[I].Value == 0)) {
421           if (WasZero)
422             return make_error<InstrProfError>(instrprof_error::invalid_prof);
423           WasZero = true;
424         }
425     }
426   }
427 
428   return Error::success();
429 }
430 
431 void InstrProfWriter::writeRecordInText(StringRef Name, uint64_t Hash,
432                                         const InstrProfRecord &Func,
433                                         InstrProfSymtab &Symtab,
434                                         raw_fd_ostream &OS) {
435   OS << Name << "\n";
436   OS << "# Func Hash:\n" << Hash << "\n";
437   OS << "# Num Counters:\n" << Func.Counts.size() << "\n";
438   OS << "# Counter Values:\n";
439   for (uint64_t Count : Func.Counts)
440     OS << Count << "\n";
441 
442   uint32_t NumValueKinds = Func.getNumValueKinds();
443   if (!NumValueKinds) {
444     OS << "\n";
445     return;
446   }
447 
448   OS << "# Num Value Kinds:\n" << Func.getNumValueKinds() << "\n";
449   for (uint32_t VK = 0; VK < IPVK_Last + 1; VK++) {
450     uint32_t NS = Func.getNumValueSites(VK);
451     if (!NS)
452       continue;
453     OS << "# ValueKind = " << ValueProfKindStr[VK] << ":\n" << VK << "\n";
454     OS << "# NumValueSites:\n" << NS << "\n";
455     for (uint32_t S = 0; S < NS; S++) {
456       uint32_t ND = Func.getNumValueDataForSite(VK, S);
457       OS << ND << "\n";
458       std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
459       for (uint32_t I = 0; I < ND; I++) {
460         if (VK == IPVK_IndirectCallTarget)
461           OS << Symtab.getFuncNameOrExternalSymbol(VD[I].Value) << ":"
462              << VD[I].Count << "\n";
463         else
464           OS << VD[I].Value << ":" << VD[I].Count << "\n";
465       }
466     }
467   }
468 
469   OS << "\n";
470 }
471 
472 Error InstrProfWriter::writeText(raw_fd_ostream &OS) {
473   if (ProfileKind == PF_IRLevel)
474     OS << "# IR level Instrumentation Flag\n:ir\n";
475   else if (ProfileKind == PF_IRLevelWithCS)
476     OS << "# CSIR level Instrumentation Flag\n:csir\n";
477   if (InstrEntryBBEnabled)
478     OS << "# Always instrument the function entry block\n:entry_first\n";
479   InstrProfSymtab Symtab;
480 
481   using FuncPair = detail::DenseMapPair<uint64_t, InstrProfRecord>;
482   using RecordType = std::pair<StringRef, FuncPair>;
483   SmallVector<RecordType, 4> OrderedFuncData;
484 
485   for (const auto &I : FunctionData) {
486     if (shouldEncodeData(I.getValue())) {
487       if (Error E = Symtab.addFuncName(I.getKey()))
488         return E;
489       for (const auto &Func : I.getValue())
490         OrderedFuncData.push_back(std::make_pair(I.getKey(), Func));
491     }
492   }
493 
494   llvm::sort(OrderedFuncData, [](const RecordType &A, const RecordType &B) {
495     return std::tie(A.first, A.second.first) <
496            std::tie(B.first, B.second.first);
497   });
498 
499   for (const auto &record : OrderedFuncData) {
500     const StringRef &Name = record.first;
501     const FuncPair &Func = record.second;
502     writeRecordInText(Name, Func.first, Func.second, Symtab, OS);
503   }
504 
505   for (const auto &record : OrderedFuncData) {
506     const FuncPair &Func = record.second;
507     if (Error E = validateRecord(Func.second))
508       return E;
509   }
510 
511   return Error::success();
512 }
513