1 //===- InstrProfWriter.cpp - Instrumented profiling writer ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing profiling data for clang's
11 // instrumentation based PGO and coverage.
12 //
13 //===----------------------------------------------------------------------===//
14 
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/InstrProfWriter.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) : IsFDOStream(true), OS(FD), LE(FD) {}
52   ProfOStream(raw_string_ostream &STR)
53       : IsFDOStream(false), OS(STR), LE(STR) {}
54 
55   uint64_t tell() { return OS.tell(); }
56   void write(uint64_t V) { LE.write<uint64_t>(V); }
57 
58   // \c patch can only be called when all data is written and flushed.
59   // For raw_string_ostream, the patch is done on the target string
60   // directly and it won't be reflected in the stream's internal buffer.
61   void patch(PatchItem *P, int NItems) {
62     using namespace support;
63 
64     if (IsFDOStream) {
65       raw_fd_ostream &FDOStream = static_cast<raw_fd_ostream &>(OS);
66       for (int K = 0; K < NItems; K++) {
67         FDOStream.seek(P[K].Pos);
68         for (int I = 0; I < P[K].N; I++)
69           write(P[K].D[I]);
70       }
71     } else {
72       raw_string_ostream &SOStream =
73           static_cast<llvm::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<support::little> LE;
90 };
91 
92 class InstrProfRecordWriterTrait {
93 public:
94   typedef StringRef key_type;
95   typedef StringRef key_type_ref;
96 
97   typedef const InstrProfWriter::ProfilingData *const data_type;
98   typedef const InstrProfWriter::ProfilingData *const data_type_ref;
99 
100   typedef uint64_t hash_value_type;
101   typedef uint64_t offset_type;
102 
103   support::endianness ValueProfDataEndianness = support::little;
104   InstrProfSummaryBuilder *SummaryBuilder;
105 
106   InstrProfRecordWriterTrait() = default;
107 
108   static hash_value_type ComputeHash(key_type_ref K) {
109     return IndexedInstrProf::ComputeHash(K);
110   }
111 
112   static std::pair<offset_type, offset_type>
113   EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
114     using namespace support;
115 
116     endian::Writer<little> LE(Out);
117 
118     offset_type N = K.size();
119     LE.write<offset_type>(N);
120 
121     offset_type M = 0;
122     for (const auto &ProfileData : *V) {
123       const InstrProfRecord &ProfRecord = ProfileData.second;
124       M += sizeof(uint64_t); // The function hash
125       M += sizeof(uint64_t); // The size of the Counts vector
126       M += ProfRecord.Counts.size() * sizeof(uint64_t);
127 
128       // Value data
129       M += ValueProfData::getSize(ProfileData.second);
130     }
131     LE.write<offset_type>(M);
132 
133     return std::make_pair(N, M);
134   }
135 
136   void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N) {
137     Out.write(K.data(), N);
138   }
139 
140   void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V, offset_type) {
141     using namespace support;
142 
143     endian::Writer<little> LE(Out);
144     for (const auto &ProfileData : *V) {
145       const InstrProfRecord &ProfRecord = ProfileData.second;
146       SummaryBuilder->addRecord(ProfRecord);
147 
148       LE.write<uint64_t>(ProfileData.first); // Function hash
149       LE.write<uint64_t>(ProfRecord.Counts.size());
150       for (uint64_t I : ProfRecord.Counts)
151         LE.write<uint64_t>(I);
152 
153       // Write value data
154       std::unique_ptr<ValueProfData> VDataPtr =
155           ValueProfData::serializeFrom(ProfileData.second);
156       uint32_t S = VDataPtr->getSize();
157       VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
158       Out.write((const char *)VDataPtr.get(), S);
159     }
160   }
161 };
162 
163 } // end namespace llvm
164 
165 InstrProfWriter::InstrProfWriter(bool Sparse)
166     : Sparse(Sparse), InfoObj(new InstrProfRecordWriterTrait()) {}
167 
168 InstrProfWriter::~InstrProfWriter() { delete InfoObj; }
169 
170 // Internal interface for testing purpose only.
171 void InstrProfWriter::setValueProfDataEndianness(
172     support::endianness Endianness) {
173   InfoObj->ValueProfDataEndianness = Endianness;
174 }
175 
176 void InstrProfWriter::setOutputSparse(bool Sparse) {
177   this->Sparse = Sparse;
178 }
179 
180 Error InstrProfWriter::addRecord(InstrProfRecord &&I, uint64_t Weight) {
181   auto &ProfileDataMap = FunctionData[I.Name];
182 
183   bool NewFunc;
184   ProfilingData::iterator Where;
185   std::tie(Where, NewFunc) =
186       ProfileDataMap.insert(std::make_pair(I.Hash, InstrProfRecord()));
187   InstrProfRecord &Dest = Where->second;
188 
189   if (NewFunc) {
190     // We've never seen a function with this name and hash, add it.
191     Dest = std::move(I);
192     // Fix up the name to avoid dangling reference.
193     Dest.Name = FunctionData.find(Dest.Name)->getKey();
194     if (Weight > 1)
195       Dest.scale(Weight);
196   } else {
197     // We're updating a function we've seen before.
198     Dest.merge(I, Weight);
199   }
200 
201   Dest.sortValueData();
202 
203   return Dest.takeError();
204 }
205 
206 Error InstrProfWriter::mergeRecordsFromWriter(InstrProfWriter &&IPW) {
207   for (auto &I : IPW.FunctionData)
208     for (auto &Func : I.getValue())
209       if (Error E = addRecord(std::move(Func.second), 1))
210         return E;
211   return Error::success();
212 }
213 
214 bool InstrProfWriter::shouldEncodeData(const ProfilingData &PD) {
215   if (!Sparse)
216     return true;
217   for (const auto &Func : PD) {
218     const InstrProfRecord &IPR = Func.second;
219     if (llvm::any_of(IPR.Counts, [](uint64_t Count) { return Count > 0; }))
220       return true;
221   }
222   return false;
223 }
224 
225 static void setSummary(IndexedInstrProf::Summary *TheSummary,
226                        ProfileSummary &PS) {
227   using namespace IndexedInstrProf;
228 
229   std::vector<ProfileSummaryEntry> &Res = PS.getDetailedSummary();
230   TheSummary->NumSummaryFields = Summary::NumKinds;
231   TheSummary->NumCutoffEntries = Res.size();
232   TheSummary->set(Summary::MaxFunctionCount, PS.getMaxFunctionCount());
233   TheSummary->set(Summary::MaxBlockCount, PS.getMaxCount());
234   TheSummary->set(Summary::MaxInternalBlockCount, PS.getMaxInternalCount());
235   TheSummary->set(Summary::TotalBlockCount, PS.getTotalCount());
236   TheSummary->set(Summary::TotalNumBlocks, PS.getNumCounts());
237   TheSummary->set(Summary::TotalNumFunctions, PS.getNumFunctions());
238   for (unsigned I = 0; I < Res.size(); I++)
239     TheSummary->setEntry(I, Res[I]);
240 }
241 
242 void InstrProfWriter::writeImpl(ProfOStream &OS) {
243   using namespace IndexedInstrProf;
244 
245   OnDiskChainedHashTableGenerator<InstrProfRecordWriterTrait> Generator;
246 
247   InstrProfSummaryBuilder ISB(ProfileSummaryBuilder::DefaultCutoffs);
248   InfoObj->SummaryBuilder = &ISB;
249 
250   // Populate the hash table generator.
251   for (const auto &I : FunctionData)
252     if (shouldEncodeData(I.getValue()))
253       Generator.insert(I.getKey(), &I.getValue());
254   // Write the header.
255   IndexedInstrProf::Header Header;
256   Header.Magic = IndexedInstrProf::Magic;
257   Header.Version = IndexedInstrProf::ProfVersion::CurrentVersion;
258   if (ProfileKind == PF_IRLevel)
259     Header.Version |= VARIANT_MASK_IR_PROF;
260   Header.Unused = 0;
261   Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
262   Header.HashOffset = 0;
263   int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
264 
265   // Only write out all the fields except 'HashOffset'. We need
266   // to remember the offset of that field to allow back patching
267   // later.
268   for (int I = 0; I < N - 1; I++)
269     OS.write(reinterpret_cast<uint64_t *>(&Header)[I]);
270 
271   // Save the location of Header.HashOffset field in \c OS.
272   uint64_t HashTableStartFieldOffset = OS.tell();
273   // Reserve the space for HashOffset field.
274   OS.write(0);
275 
276   // Reserve space to write profile summary data.
277   uint32_t NumEntries = ProfileSummaryBuilder::DefaultCutoffs.size();
278   uint32_t SummarySize = Summary::getSize(Summary::NumKinds, NumEntries);
279   // Remember the summary offset.
280   uint64_t SummaryOffset = OS.tell();
281   for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
282     OS.write(0);
283 
284   // Write the hash table.
285   uint64_t HashTableStart = Generator.Emit(OS.OS, *InfoObj);
286 
287   // Allocate space for data to be serialized out.
288   std::unique_ptr<IndexedInstrProf::Summary> TheSummary =
289       IndexedInstrProf::allocSummary(SummarySize);
290   // Compute the Summary and copy the data to the data
291   // structure to be serialized out (to disk or buffer).
292   std::unique_ptr<ProfileSummary> PS = ISB.getSummary();
293   setSummary(TheSummary.get(), *PS);
294   InfoObj->SummaryBuilder = nullptr;
295 
296   // Now do the final patch:
297   PatchItem PatchItems[] = {
298       // Patch the Header.HashOffset field.
299       {HashTableStartFieldOffset, &HashTableStart, 1},
300       // Patch the summary data.
301       {SummaryOffset, reinterpret_cast<uint64_t *>(TheSummary.get()),
302        (int)(SummarySize / sizeof(uint64_t))}};
303   OS.patch(PatchItems, sizeof(PatchItems) / sizeof(*PatchItems));
304 }
305 
306 void InstrProfWriter::write(raw_fd_ostream &OS) {
307   // Write the hash table.
308   ProfOStream POS(OS);
309   writeImpl(POS);
310 }
311 
312 std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
313   std::string Data;
314   raw_string_ostream OS(Data);
315   ProfOStream POS(OS);
316   // Write the hash table.
317   writeImpl(POS);
318   // Return this in an aligned memory buffer.
319   return MemoryBuffer::getMemBufferCopy(Data);
320 }
321 
322 static const char *ValueProfKindStr[] = {
323 #define VALUE_PROF_KIND(Enumerator, Value) #Enumerator,
324 #include "llvm/ProfileData/InstrProfData.inc"
325 };
326 
327 void InstrProfWriter::writeRecordInText(const InstrProfRecord &Func,
328                                         InstrProfSymtab &Symtab,
329                                         raw_fd_ostream &OS) {
330   OS << Func.Name << "\n";
331   OS << "# Func Hash:\n" << Func.Hash << "\n";
332   OS << "# Num Counters:\n" << Func.Counts.size() << "\n";
333   OS << "# Counter Values:\n";
334   for (uint64_t Count : Func.Counts)
335     OS << Count << "\n";
336 
337   uint32_t NumValueKinds = Func.getNumValueKinds();
338   if (!NumValueKinds) {
339     OS << "\n";
340     return;
341   }
342 
343   OS << "# Num Value Kinds:\n" << Func.getNumValueKinds() << "\n";
344   for (uint32_t VK = 0; VK < IPVK_Last + 1; VK++) {
345     uint32_t NS = Func.getNumValueSites(VK);
346     if (!NS)
347       continue;
348     OS << "# ValueKind = " << ValueProfKindStr[VK] << ":\n" << VK << "\n";
349     OS << "# NumValueSites:\n" << NS << "\n";
350     for (uint32_t S = 0; S < NS; S++) {
351       uint32_t ND = Func.getNumValueDataForSite(VK, S);
352       OS << ND << "\n";
353       std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
354       for (uint32_t I = 0; I < ND; I++) {
355         if (VK == IPVK_IndirectCallTarget)
356           OS << Symtab.getFuncName(VD[I].Value) << ":" << VD[I].Count << "\n";
357         else
358           OS << VD[I].Value << ":" << VD[I].Count << "\n";
359       }
360     }
361   }
362 
363   OS << "\n";
364 }
365 
366 void InstrProfWriter::writeText(raw_fd_ostream &OS) {
367   if (ProfileKind == PF_IRLevel)
368     OS << "# IR level Instrumentation Flag\n:ir\n";
369   InstrProfSymtab Symtab;
370   for (const auto &I : FunctionData)
371     if (shouldEncodeData(I.getValue()))
372       Symtab.addFuncName(I.getKey());
373   Symtab.finalizeSymtab();
374 
375   for (const auto &I : FunctionData)
376     if (shouldEncodeData(I.getValue()))
377       for (const auto &Func : I.getValue())
378         writeRecordInText(Func.second, Symtab, OS);
379 }
380