1 //===- InstrProfReader.cpp - Instrumented profiling reader ----------------===//
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 reading profiling data for clang's
10 // instrumentation based PGO and coverage.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ProfileData/InstrProfReader.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/IR/ProfileSummary.h"
20 #include "llvm/ProfileData/InstrProf.h"
21 #include "llvm/ProfileData/ProfileCommon.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/ErrorOr.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/SymbolRemappingReader.h"
27 #include "llvm/Support/SwapByteOrder.h"
28 #include <algorithm>
29 #include <cctype>
30 #include <cstddef>
31 #include <cstdint>
32 #include <limits>
33 #include <memory>
34 #include <system_error>
35 #include <utility>
36 #include <vector>
37 
38 using namespace llvm;
39 
40 static Expected<std::unique_ptr<MemoryBuffer>>
41 setupMemoryBuffer(const Twine &Path) {
42   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
43       MemoryBuffer::getFileOrSTDIN(Path);
44   if (std::error_code EC = BufferOrErr.getError())
45     return errorCodeToError(EC);
46   return std::move(BufferOrErr.get());
47 }
48 
49 static Error initializeReader(InstrProfReader &Reader) {
50   return Reader.readHeader();
51 }
52 
53 Expected<std::unique_ptr<InstrProfReader>>
54 InstrProfReader::create(const Twine &Path) {
55   // Set up the buffer to read.
56   auto BufferOrError = setupMemoryBuffer(Path);
57   if (Error E = BufferOrError.takeError())
58     return std::move(E);
59   return InstrProfReader::create(std::move(BufferOrError.get()));
60 }
61 
62 Expected<std::unique_ptr<InstrProfReader>>
63 InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
64   // Sanity check the buffer.
65   if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint64_t>::max())
66     return make_error<InstrProfError>(instrprof_error::too_large);
67 
68   if (Buffer->getBufferSize() == 0)
69     return make_error<InstrProfError>(instrprof_error::empty_raw_profile);
70 
71   std::unique_ptr<InstrProfReader> Result;
72   // Create the reader.
73   if (IndexedInstrProfReader::hasFormat(*Buffer))
74     Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
75   else if (RawInstrProfReader64::hasFormat(*Buffer))
76     Result.reset(new RawInstrProfReader64(std::move(Buffer)));
77   else if (RawInstrProfReader32::hasFormat(*Buffer))
78     Result.reset(new RawInstrProfReader32(std::move(Buffer)));
79   else if (TextInstrProfReader::hasFormat(*Buffer))
80     Result.reset(new TextInstrProfReader(std::move(Buffer)));
81   else
82     return make_error<InstrProfError>(instrprof_error::unrecognized_format);
83 
84   // Initialize the reader and return the result.
85   if (Error E = initializeReader(*Result))
86     return std::move(E);
87 
88   return std::move(Result);
89 }
90 
91 Expected<std::unique_ptr<IndexedInstrProfReader>>
92 IndexedInstrProfReader::create(const Twine &Path, const Twine &RemappingPath) {
93   // Set up the buffer to read.
94   auto BufferOrError = setupMemoryBuffer(Path);
95   if (Error E = BufferOrError.takeError())
96     return std::move(E);
97 
98   // Set up the remapping buffer if requested.
99   std::unique_ptr<MemoryBuffer> RemappingBuffer;
100   std::string RemappingPathStr = RemappingPath.str();
101   if (!RemappingPathStr.empty()) {
102     auto RemappingBufferOrError = setupMemoryBuffer(RemappingPathStr);
103     if (Error E = RemappingBufferOrError.takeError())
104       return std::move(E);
105     RemappingBuffer = std::move(RemappingBufferOrError.get());
106   }
107 
108   return IndexedInstrProfReader::create(std::move(BufferOrError.get()),
109                                         std::move(RemappingBuffer));
110 }
111 
112 Expected<std::unique_ptr<IndexedInstrProfReader>>
113 IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer,
114                                std::unique_ptr<MemoryBuffer> RemappingBuffer) {
115   // Sanity check the buffer.
116   if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint64_t>::max())
117     return make_error<InstrProfError>(instrprof_error::too_large);
118 
119   // Create the reader.
120   if (!IndexedInstrProfReader::hasFormat(*Buffer))
121     return make_error<InstrProfError>(instrprof_error::bad_magic);
122   auto Result = std::make_unique<IndexedInstrProfReader>(
123       std::move(Buffer), std::move(RemappingBuffer));
124 
125   // Initialize the reader and return the result.
126   if (Error E = initializeReader(*Result))
127     return std::move(E);
128 
129   return std::move(Result);
130 }
131 
132 void InstrProfIterator::Increment() {
133   if (auto E = Reader->readNextRecord(Record)) {
134     // Handle errors in the reader.
135     InstrProfError::take(std::move(E));
136     *this = InstrProfIterator();
137   }
138 }
139 
140 bool TextInstrProfReader::hasFormat(const MemoryBuffer &Buffer) {
141   // Verify that this really looks like plain ASCII text by checking a
142   // 'reasonable' number of characters (up to profile magic size).
143   size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));
144   StringRef buffer = Buffer.getBufferStart();
145   return count == 0 ||
146          std::all_of(buffer.begin(), buffer.begin() + count,
147                      [](char c) { return isPrint(c) || ::isspace(c); });
148 }
149 
150 // Read the profile variant flag from the header: ":FE" means this is a FE
151 // generated profile. ":IR" means this is an IR level profile. Other strings
152 // with a leading ':' will be reported an error format.
153 Error TextInstrProfReader::readHeader() {
154   Symtab.reset(new InstrProfSymtab());
155   bool IsIRInstr = false;
156   if (!Line->startswith(":")) {
157     IsIRLevelProfile = false;
158     return success();
159   }
160   StringRef Str = (Line)->substr(1);
161   if (Str.equals_lower("ir"))
162     IsIRInstr = true;
163   else if (Str.equals_lower("fe"))
164     IsIRInstr = false;
165   else if (Str.equals_lower("csir")) {
166     IsIRInstr = true;
167     HasCSIRLevelProfile = true;
168   } else
169     return error(instrprof_error::bad_header);
170 
171   ++Line;
172   IsIRLevelProfile = IsIRInstr;
173   return success();
174 }
175 
176 Error
177 TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
178 
179 #define CHECK_LINE_END(Line)                                                   \
180   if (Line.is_at_end())                                                        \
181     return error(instrprof_error::truncated);
182 #define READ_NUM(Str, Dst)                                                     \
183   if ((Str).getAsInteger(10, (Dst)))                                           \
184     return error(instrprof_error::malformed);
185 #define VP_READ_ADVANCE(Val)                                                   \
186   CHECK_LINE_END(Line);                                                        \
187   uint32_t Val;                                                                \
188   READ_NUM((*Line), (Val));                                                    \
189   Line++;
190 
191   if (Line.is_at_end())
192     return success();
193 
194   uint32_t NumValueKinds;
195   if (Line->getAsInteger(10, NumValueKinds)) {
196     // No value profile data
197     return success();
198   }
199   if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
200     return error(instrprof_error::malformed);
201   Line++;
202 
203   for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
204     VP_READ_ADVANCE(ValueKind);
205     if (ValueKind > IPVK_Last)
206       return error(instrprof_error::malformed);
207     VP_READ_ADVANCE(NumValueSites);
208     if (!NumValueSites)
209       continue;
210 
211     Record.reserveSites(VK, NumValueSites);
212     for (uint32_t S = 0; S < NumValueSites; S++) {
213       VP_READ_ADVANCE(NumValueData);
214 
215       std::vector<InstrProfValueData> CurrentValues;
216       for (uint32_t V = 0; V < NumValueData; V++) {
217         CHECK_LINE_END(Line);
218         std::pair<StringRef, StringRef> VD = Line->rsplit(':');
219         uint64_t TakenCount, Value;
220         if (ValueKind == IPVK_IndirectCallTarget) {
221           if (InstrProfSymtab::isExternalSymbol(VD.first)) {
222             Value = 0;
223           } else {
224             if (Error E = Symtab->addFuncName(VD.first))
225               return E;
226             Value = IndexedInstrProf::ComputeHash(VD.first);
227           }
228         } else {
229           READ_NUM(VD.first, Value);
230         }
231         READ_NUM(VD.second, TakenCount);
232         CurrentValues.push_back({Value, TakenCount});
233         Line++;
234       }
235       Record.addValueData(ValueKind, S, CurrentValues.data(), NumValueData,
236                           nullptr);
237     }
238   }
239   return success();
240 
241 #undef CHECK_LINE_END
242 #undef READ_NUM
243 #undef VP_READ_ADVANCE
244 }
245 
246 Error TextInstrProfReader::readNextRecord(NamedInstrProfRecord &Record) {
247   // Skip empty lines and comments.
248   while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
249     ++Line;
250   // If we hit EOF while looking for a name, we're done.
251   if (Line.is_at_end()) {
252     return error(instrprof_error::eof);
253   }
254 
255   // Read the function name.
256   Record.Name = *Line++;
257   if (Error E = Symtab->addFuncName(Record.Name))
258     return error(std::move(E));
259 
260   // Read the function hash.
261   if (Line.is_at_end())
262     return error(instrprof_error::truncated);
263   if ((Line++)->getAsInteger(0, Record.Hash))
264     return error(instrprof_error::malformed);
265 
266   // Read the number of counters.
267   uint64_t NumCounters;
268   if (Line.is_at_end())
269     return error(instrprof_error::truncated);
270   if ((Line++)->getAsInteger(10, NumCounters))
271     return error(instrprof_error::malformed);
272   if (NumCounters == 0)
273     return error(instrprof_error::malformed);
274 
275   // Read each counter and fill our internal storage with the values.
276   Record.Clear();
277   Record.Counts.reserve(NumCounters);
278   for (uint64_t I = 0; I < NumCounters; ++I) {
279     if (Line.is_at_end())
280       return error(instrprof_error::truncated);
281     uint64_t Count;
282     if ((Line++)->getAsInteger(10, Count))
283       return error(instrprof_error::malformed);
284     Record.Counts.push_back(Count);
285   }
286 
287   // Check if value profile data exists and read it if so.
288   if (Error E = readValueProfileData(Record))
289     return error(std::move(E));
290 
291   return success();
292 }
293 
294 template <class IntPtrT>
295 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
296   if (DataBuffer.getBufferSize() < sizeof(uint64_t))
297     return false;
298   uint64_t Magic =
299     *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
300   return RawInstrProf::getMagic<IntPtrT>() == Magic ||
301          sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
302 }
303 
304 template <class IntPtrT>
305 Error RawInstrProfReader<IntPtrT>::readHeader() {
306   if (!hasFormat(*DataBuffer))
307     return error(instrprof_error::bad_magic);
308   if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
309     return error(instrprof_error::bad_header);
310   auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
311       DataBuffer->getBufferStart());
312   ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
313   return readHeader(*Header);
314 }
315 
316 template <class IntPtrT>
317 Error RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
318   const char *End = DataBuffer->getBufferEnd();
319   // Skip zero padding between profiles.
320   while (CurrentPos != End && *CurrentPos == 0)
321     ++CurrentPos;
322   // If there's nothing left, we're done.
323   if (CurrentPos == End)
324     return make_error<InstrProfError>(instrprof_error::eof);
325   // If there isn't enough space for another header, this is probably just
326   // garbage at the end of the file.
327   if (CurrentPos + sizeof(RawInstrProf::Header) > End)
328     return make_error<InstrProfError>(instrprof_error::malformed);
329   // The writer ensures each profile is padded to start at an aligned address.
330   if (reinterpret_cast<size_t>(CurrentPos) % alignof(uint64_t))
331     return make_error<InstrProfError>(instrprof_error::malformed);
332   // The magic should have the same byte order as in the previous header.
333   uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
334   if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
335     return make_error<InstrProfError>(instrprof_error::bad_magic);
336 
337   // There's another profile to read, so we need to process the header.
338   auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
339   return readHeader(*Header);
340 }
341 
342 template <class IntPtrT>
343 Error RawInstrProfReader<IntPtrT>::createSymtab(InstrProfSymtab &Symtab) {
344   if (Error E = Symtab.create(StringRef(NamesStart, NamesSize)))
345     return error(std::move(E));
346   for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
347     const IntPtrT FPtr = swap(I->FunctionPointer);
348     if (!FPtr)
349       continue;
350     Symtab.mapAddress(FPtr, I->NameRef);
351   }
352   return success();
353 }
354 
355 template <class IntPtrT>
356 Error RawInstrProfReader<IntPtrT>::readHeader(
357     const RawInstrProf::Header &Header) {
358   Version = swap(Header.Version);
359   if (GET_VERSION(Version) != RawInstrProf::Version)
360     return error(instrprof_error::unsupported_version);
361 
362   CountersDelta = swap(Header.CountersDelta);
363   NamesDelta = swap(Header.NamesDelta);
364   auto DataSize = swap(Header.DataSize);
365   auto PaddingBytesBeforeCounters = swap(Header.PaddingBytesBeforeCounters);
366   auto CountersSize = swap(Header.CountersSize);
367   auto PaddingBytesAfterCounters = swap(Header.PaddingBytesAfterCounters);
368   NamesSize = swap(Header.NamesSize);
369   ValueKindLast = swap(Header.ValueKindLast);
370 
371   auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
372   auto PaddingSize = getNumPaddingBytes(NamesSize);
373 
374   ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
375   ptrdiff_t CountersOffset =
376       DataOffset + DataSizeInBytes + PaddingBytesBeforeCounters;
377   ptrdiff_t NamesOffset = CountersOffset + (sizeof(uint64_t) * CountersSize) +
378                           PaddingBytesAfterCounters;
379   ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
380 
381   auto *Start = reinterpret_cast<const char *>(&Header);
382   if (Start + ValueDataOffset > DataBuffer->getBufferEnd())
383     return error(instrprof_error::bad_header);
384 
385   Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
386       Start + DataOffset);
387   DataEnd = Data + DataSize;
388   CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
389   NamesStart = Start + NamesOffset;
390   ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset);
391 
392   std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>();
393   if (Error E = createSymtab(*NewSymtab.get()))
394     return E;
395 
396   Symtab = std::move(NewSymtab);
397   return success();
398 }
399 
400 template <class IntPtrT>
401 Error RawInstrProfReader<IntPtrT>::readName(NamedInstrProfRecord &Record) {
402   Record.Name = getName(Data->NameRef);
403   return success();
404 }
405 
406 template <class IntPtrT>
407 Error RawInstrProfReader<IntPtrT>::readFuncHash(NamedInstrProfRecord &Record) {
408   Record.Hash = swap(Data->FuncHash);
409   return success();
410 }
411 
412 template <class IntPtrT>
413 Error RawInstrProfReader<IntPtrT>::readRawCounts(
414     InstrProfRecord &Record) {
415   uint32_t NumCounters = swap(Data->NumCounters);
416   IntPtrT CounterPtr = Data->CounterPtr;
417   if (NumCounters == 0)
418     return error(instrprof_error::malformed);
419 
420   auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
421   ptrdiff_t MaxNumCounters = NamesStartAsCounter - CountersStart;
422 
423   // Check bounds. Note that the counter pointer embedded in the data record
424   // may itself be corrupt.
425   if (NumCounters > MaxNumCounters)
426     return error(instrprof_error::malformed);
427   ptrdiff_t CounterOffset = getCounterOffset(CounterPtr);
428   if (CounterOffset < 0 || CounterOffset > MaxNumCounters ||
429       (CounterOffset + NumCounters) > MaxNumCounters)
430     return error(instrprof_error::malformed);
431 
432   auto RawCounts = makeArrayRef(getCounter(CounterOffset), NumCounters);
433 
434   if (ShouldSwapBytes) {
435     Record.Counts.clear();
436     Record.Counts.reserve(RawCounts.size());
437     for (uint64_t Count : RawCounts)
438       Record.Counts.push_back(swap(Count));
439   } else
440     Record.Counts = RawCounts;
441 
442   return success();
443 }
444 
445 template <class IntPtrT>
446 Error RawInstrProfReader<IntPtrT>::readValueProfilingData(
447     InstrProfRecord &Record) {
448   Record.clearValueData();
449   CurValueDataSize = 0;
450   // Need to match the logic in value profile dumper code in compiler-rt:
451   uint32_t NumValueKinds = 0;
452   for (uint32_t I = 0; I < IPVK_Last + 1; I++)
453     NumValueKinds += (Data->NumValueSites[I] != 0);
454 
455   if (!NumValueKinds)
456     return success();
457 
458   Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
459       ValueProfData::getValueProfData(
460           ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(),
461           getDataEndianness());
462 
463   if (Error E = VDataPtrOrErr.takeError())
464     return E;
465 
466   // Note that besides deserialization, this also performs the conversion for
467   // indirect call targets.  The function pointers from the raw profile are
468   // remapped into function name hashes.
469   VDataPtrOrErr.get()->deserializeTo(Record, Symtab.get());
470   CurValueDataSize = VDataPtrOrErr.get()->getSize();
471   return success();
472 }
473 
474 template <class IntPtrT>
475 Error RawInstrProfReader<IntPtrT>::readNextRecord(NamedInstrProfRecord &Record) {
476   if (atEnd())
477     // At this point, ValueDataStart field points to the next header.
478     if (Error E = readNextHeader(getNextHeaderPos()))
479       return error(std::move(E));
480 
481   // Read name ad set it in Record.
482   if (Error E = readName(Record))
483     return error(std::move(E));
484 
485   // Read FuncHash and set it in Record.
486   if (Error E = readFuncHash(Record))
487     return error(std::move(E));
488 
489   // Read raw counts and set Record.
490   if (Error E = readRawCounts(Record))
491     return error(std::move(E));
492 
493   // Read value data and set Record.
494   if (Error E = readValueProfilingData(Record))
495     return error(std::move(E));
496 
497   // Iterate.
498   advanceData();
499   return success();
500 }
501 
502 namespace llvm {
503 
504 template class RawInstrProfReader<uint32_t>;
505 template class RawInstrProfReader<uint64_t>;
506 
507 } // end namespace llvm
508 
509 InstrProfLookupTrait::hash_value_type
510 InstrProfLookupTrait::ComputeHash(StringRef K) {
511   return IndexedInstrProf::ComputeHash(HashType, K);
512 }
513 
514 using data_type = InstrProfLookupTrait::data_type;
515 using offset_type = InstrProfLookupTrait::offset_type;
516 
517 bool InstrProfLookupTrait::readValueProfilingData(
518     const unsigned char *&D, const unsigned char *const End) {
519   Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
520       ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
521 
522   if (VDataPtrOrErr.takeError())
523     return false;
524 
525   VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);
526   D += VDataPtrOrErr.get()->TotalSize;
527 
528   return true;
529 }
530 
531 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
532                                          offset_type N) {
533   using namespace support;
534 
535   // Check if the data is corrupt. If so, don't try to read it.
536   if (N % sizeof(uint64_t))
537     return data_type();
538 
539   DataBuffer.clear();
540   std::vector<uint64_t> CounterBuffer;
541 
542   const unsigned char *End = D + N;
543   while (D < End) {
544     // Read hash.
545     if (D + sizeof(uint64_t) >= End)
546       return data_type();
547     uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
548 
549     // Initialize number of counters for GET_VERSION(FormatVersion) == 1.
550     uint64_t CountsSize = N / sizeof(uint64_t) - 1;
551     // If format version is different then read the number of counters.
552     if (GET_VERSION(FormatVersion) != IndexedInstrProf::ProfVersion::Version1) {
553       if (D + sizeof(uint64_t) > End)
554         return data_type();
555       CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
556     }
557     // Read counter values.
558     if (D + CountsSize * sizeof(uint64_t) > End)
559       return data_type();
560 
561     CounterBuffer.clear();
562     CounterBuffer.reserve(CountsSize);
563     for (uint64_t J = 0; J < CountsSize; ++J)
564       CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
565 
566     DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
567 
568     // Read value profiling data.
569     if (GET_VERSION(FormatVersion) > IndexedInstrProf::ProfVersion::Version2 &&
570         !readValueProfilingData(D, End)) {
571       DataBuffer.clear();
572       return data_type();
573     }
574   }
575   return DataBuffer;
576 }
577 
578 template <typename HashTableImpl>
579 Error InstrProfReaderIndex<HashTableImpl>::getRecords(
580     StringRef FuncName, ArrayRef<NamedInstrProfRecord> &Data) {
581   auto Iter = HashTable->find(FuncName);
582   if (Iter == HashTable->end())
583     return make_error<InstrProfError>(instrprof_error::unknown_function);
584 
585   Data = (*Iter);
586   if (Data.empty())
587     return make_error<InstrProfError>(instrprof_error::malformed);
588 
589   return Error::success();
590 }
591 
592 template <typename HashTableImpl>
593 Error InstrProfReaderIndex<HashTableImpl>::getRecords(
594     ArrayRef<NamedInstrProfRecord> &Data) {
595   if (atEnd())
596     return make_error<InstrProfError>(instrprof_error::eof);
597 
598   Data = *RecordIterator;
599 
600   if (Data.empty())
601     return make_error<InstrProfError>(instrprof_error::malformed);
602 
603   return Error::success();
604 }
605 
606 template <typename HashTableImpl>
607 InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
608     const unsigned char *Buckets, const unsigned char *const Payload,
609     const unsigned char *const Base, IndexedInstrProf::HashT HashType,
610     uint64_t Version) {
611   FormatVersion = Version;
612   HashTable.reset(HashTableImpl::Create(
613       Buckets, Payload, Base,
614       typename HashTableImpl::InfoType(HashType, Version)));
615   RecordIterator = HashTable->data_begin();
616 }
617 
618 namespace {
619 /// A remapper that does not apply any remappings.
620 class InstrProfReaderNullRemapper : public InstrProfReaderRemapper {
621   InstrProfReaderIndexBase &Underlying;
622 
623 public:
624   InstrProfReaderNullRemapper(InstrProfReaderIndexBase &Underlying)
625       : Underlying(Underlying) {}
626 
627   Error getRecords(StringRef FuncName,
628                    ArrayRef<NamedInstrProfRecord> &Data) override {
629     return Underlying.getRecords(FuncName, Data);
630   }
631 };
632 }
633 
634 /// A remapper that applies remappings based on a symbol remapping file.
635 template <typename HashTableImpl>
636 class llvm::InstrProfReaderItaniumRemapper
637     : public InstrProfReaderRemapper {
638 public:
639   InstrProfReaderItaniumRemapper(
640       std::unique_ptr<MemoryBuffer> RemapBuffer,
641       InstrProfReaderIndex<HashTableImpl> &Underlying)
642       : RemapBuffer(std::move(RemapBuffer)), Underlying(Underlying) {
643   }
644 
645   /// Extract the original function name from a PGO function name.
646   static StringRef extractName(StringRef Name) {
647     // We can have multiple :-separated pieces; there can be pieces both
648     // before and after the mangled name. Find the first part that starts
649     // with '_Z'; we'll assume that's the mangled name we want.
650     std::pair<StringRef, StringRef> Parts = {StringRef(), Name};
651     while (true) {
652       Parts = Parts.second.split(':');
653       if (Parts.first.startswith("_Z"))
654         return Parts.first;
655       if (Parts.second.empty())
656         return Name;
657     }
658   }
659 
660   /// Given a mangled name extracted from a PGO function name, and a new
661   /// form for that mangled name, reconstitute the name.
662   static void reconstituteName(StringRef OrigName, StringRef ExtractedName,
663                                StringRef Replacement,
664                                SmallVectorImpl<char> &Out) {
665     Out.reserve(OrigName.size() + Replacement.size() - ExtractedName.size());
666     Out.insert(Out.end(), OrigName.begin(), ExtractedName.begin());
667     Out.insert(Out.end(), Replacement.begin(), Replacement.end());
668     Out.insert(Out.end(), ExtractedName.end(), OrigName.end());
669   }
670 
671   Error populateRemappings() override {
672     if (Error E = Remappings.read(*RemapBuffer))
673       return E;
674     for (StringRef Name : Underlying.HashTable->keys()) {
675       StringRef RealName = extractName(Name);
676       if (auto Key = Remappings.insert(RealName)) {
677         // FIXME: We could theoretically map the same equivalence class to
678         // multiple names in the profile data. If that happens, we should
679         // return NamedInstrProfRecords from all of them.
680         MappedNames.insert({Key, RealName});
681       }
682     }
683     return Error::success();
684   }
685 
686   Error getRecords(StringRef FuncName,
687                    ArrayRef<NamedInstrProfRecord> &Data) override {
688     StringRef RealName = extractName(FuncName);
689     if (auto Key = Remappings.lookup(RealName)) {
690       StringRef Remapped = MappedNames.lookup(Key);
691       if (!Remapped.empty()) {
692         if (RealName.begin() == FuncName.begin() &&
693             RealName.end() == FuncName.end())
694           FuncName = Remapped;
695         else {
696           // Try rebuilding the name from the given remapping.
697           SmallString<256> Reconstituted;
698           reconstituteName(FuncName, RealName, Remapped, Reconstituted);
699           Error E = Underlying.getRecords(Reconstituted, Data);
700           if (!E)
701             return E;
702 
703           // If we failed because the name doesn't exist, fall back to asking
704           // about the original name.
705           if (Error Unhandled = handleErrors(
706                   std::move(E), [](std::unique_ptr<InstrProfError> Err) {
707                     return Err->get() == instrprof_error::unknown_function
708                                ? Error::success()
709                                : Error(std::move(Err));
710                   }))
711             return Unhandled;
712         }
713       }
714     }
715     return Underlying.getRecords(FuncName, Data);
716   }
717 
718 private:
719   /// The memory buffer containing the remapping configuration. Remappings
720   /// holds pointers into this buffer.
721   std::unique_ptr<MemoryBuffer> RemapBuffer;
722 
723   /// The mangling remapper.
724   SymbolRemappingReader Remappings;
725 
726   /// Mapping from mangled name keys to the name used for the key in the
727   /// profile data.
728   /// FIXME: Can we store a location within the on-disk hash table instead of
729   /// redoing lookup?
730   DenseMap<SymbolRemappingReader::Key, StringRef> MappedNames;
731 
732   /// The real profile data reader.
733   InstrProfReaderIndex<HashTableImpl> &Underlying;
734 };
735 
736 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
737   using namespace support;
738 
739   if (DataBuffer.getBufferSize() < 8)
740     return false;
741   uint64_t Magic =
742       endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
743   // Verify that it's magical.
744   return Magic == IndexedInstrProf::Magic;
745 }
746 
747 const unsigned char *
748 IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version,
749                                     const unsigned char *Cur, bool UseCS) {
750   using namespace IndexedInstrProf;
751   using namespace support;
752 
753   if (Version >= IndexedInstrProf::Version4) {
754     const IndexedInstrProf::Summary *SummaryInLE =
755         reinterpret_cast<const IndexedInstrProf::Summary *>(Cur);
756     uint64_t NFields =
757         endian::byte_swap<uint64_t, little>(SummaryInLE->NumSummaryFields);
758     uint64_t NEntries =
759         endian::byte_swap<uint64_t, little>(SummaryInLE->NumCutoffEntries);
760     uint32_t SummarySize =
761         IndexedInstrProf::Summary::getSize(NFields, NEntries);
762     std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
763         IndexedInstrProf::allocSummary(SummarySize);
764 
765     const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE);
766     uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get());
767     for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
768       Dst[I] = endian::byte_swap<uint64_t, little>(Src[I]);
769 
770     SummaryEntryVector DetailedSummary;
771     for (unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
772       const IndexedInstrProf::Summary::Entry &Ent = SummaryData->getEntry(I);
773       DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,
774                                    Ent.NumBlocks);
775     }
776     std::unique_ptr<llvm::ProfileSummary> &Summary =
777         UseCS ? this->CS_Summary : this->Summary;
778 
779     // initialize InstrProfSummary using the SummaryData from disk.
780     Summary = std::make_unique<ProfileSummary>(
781         UseCS ? ProfileSummary::PSK_CSInstr : ProfileSummary::PSK_Instr,
782         DetailedSummary, SummaryData->get(Summary::TotalBlockCount),
783         SummaryData->get(Summary::MaxBlockCount),
784         SummaryData->get(Summary::MaxInternalBlockCount),
785         SummaryData->get(Summary::MaxFunctionCount),
786         SummaryData->get(Summary::TotalNumBlocks),
787         SummaryData->get(Summary::TotalNumFunctions));
788     return Cur + SummarySize;
789   } else {
790     // The older versions do not support a profile summary. This just computes
791     // an empty summary, which will not result in accurate hot/cold detection.
792     // We would need to call addRecord for all NamedInstrProfRecords to get the
793     // correct summary. However, this version is old (prior to early 2016) and
794     // has not been supporting an accurate summary for several years.
795     InstrProfSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
796     Summary = Builder.getSummary();
797     return Cur;
798   }
799 }
800 
801 Error IndexedInstrProfReader::readHeader() {
802   using namespace support;
803 
804   const unsigned char *Start =
805       (const unsigned char *)DataBuffer->getBufferStart();
806   const unsigned char *Cur = Start;
807   if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
808     return error(instrprof_error::truncated);
809 
810   auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
811   Cur += sizeof(IndexedInstrProf::Header);
812 
813   // Check the magic number.
814   uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
815   if (Magic != IndexedInstrProf::Magic)
816     return error(instrprof_error::bad_magic);
817 
818   // Read the version.
819   uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
820   if (GET_VERSION(FormatVersion) >
821       IndexedInstrProf::ProfVersion::CurrentVersion)
822     return error(instrprof_error::unsupported_version);
823 
824   Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur,
825                     /* UseCS */ false);
826   if (FormatVersion & VARIANT_MASK_CSIR_PROF)
827     Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur,
828                       /* UseCS */ true);
829 
830   // Read the hash type and start offset.
831   IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
832       endian::byte_swap<uint64_t, little>(Header->HashType));
833   if (HashType > IndexedInstrProf::HashT::Last)
834     return error(instrprof_error::unsupported_hash_type);
835 
836   uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
837 
838   // The rest of the file is an on disk hash table.
839   auto IndexPtr =
840       std::make_unique<InstrProfReaderIndex<OnDiskHashTableImplV3>>(
841           Start + HashOffset, Cur, Start, HashType, FormatVersion);
842 
843   // Load the remapping table now if requested.
844   if (RemappingBuffer) {
845     Remapper = std::make_unique<
846         InstrProfReaderItaniumRemapper<OnDiskHashTableImplV3>>(
847         std::move(RemappingBuffer), *IndexPtr);
848     if (Error E = Remapper->populateRemappings())
849       return E;
850   } else {
851     Remapper = std::make_unique<InstrProfReaderNullRemapper>(*IndexPtr);
852   }
853   Index = std::move(IndexPtr);
854 
855   return success();
856 }
857 
858 InstrProfSymtab &IndexedInstrProfReader::getSymtab() {
859   if (Symtab.get())
860     return *Symtab.get();
861 
862   std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>();
863   if (Error E = Index->populateSymtab(*NewSymtab.get())) {
864     consumeError(error(InstrProfError::take(std::move(E))));
865   }
866 
867   Symtab = std::move(NewSymtab);
868   return *Symtab.get();
869 }
870 
871 Expected<InstrProfRecord>
872 IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
873                                            uint64_t FuncHash) {
874   ArrayRef<NamedInstrProfRecord> Data;
875   Error Err = Remapper->getRecords(FuncName, Data);
876   if (Err)
877     return std::move(Err);
878   // Found it. Look for counters with the right hash.
879   for (unsigned I = 0, E = Data.size(); I < E; ++I) {
880     // Check for a match and fill the vector if there is one.
881     if (Data[I].Hash == FuncHash) {
882       return std::move(Data[I]);
883     }
884   }
885   return error(instrprof_error::hash_mismatch);
886 }
887 
888 Error IndexedInstrProfReader::getFunctionCounts(StringRef FuncName,
889                                                 uint64_t FuncHash,
890                                                 std::vector<uint64_t> &Counts) {
891   Expected<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
892   if (Error E = Record.takeError())
893     return error(std::move(E));
894 
895   Counts = Record.get().Counts;
896   return success();
897 }
898 
899 Error IndexedInstrProfReader::readNextRecord(NamedInstrProfRecord &Record) {
900   ArrayRef<NamedInstrProfRecord> Data;
901 
902   Error E = Index->getRecords(Data);
903   if (E)
904     return error(std::move(E));
905 
906   Record = Data[RecordIndex++];
907   if (RecordIndex >= Data.size()) {
908     Index->advanceToNextKey();
909     RecordIndex = 0;
910   }
911   return success();
912 }
913 
914 void InstrProfReader::accumulateCounts(CountSumOrPercent &Sum, bool IsCS) {
915   uint64_t NumFuncs = 0;
916   for (const auto &Func : *this) {
917     if (isIRLevelProfile()) {
918       bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
919       if (FuncIsCS != IsCS)
920         continue;
921     }
922     Func.accumulateCounts(Sum);
923     ++NumFuncs;
924   }
925   Sum.NumEntries = NumFuncs;
926 }
927