1 //=-- InstrProfReader.cpp - Instrumented profiling reader -------------------=//
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 reading profiling data for clang's
11 // instrumentation based PGO and coverage.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ProfileData/InstrProfReader.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include <cassert>
18 
19 using namespace llvm;
20 
21 static Expected<std::unique_ptr<MemoryBuffer>>
22 setupMemoryBuffer(const Twine &Path) {
23   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
24       MemoryBuffer::getFileOrSTDIN(Path);
25   if (std::error_code EC = BufferOrErr.getError())
26     return errorCodeToError(EC);
27   return std::move(BufferOrErr.get());
28 }
29 
30 static Error initializeReader(InstrProfReader &Reader) {
31   return Reader.readHeader();
32 }
33 
34 Expected<std::unique_ptr<InstrProfReader>>
35 InstrProfReader::create(const Twine &Path) {
36   // Set up the buffer to read.
37   auto BufferOrError = setupMemoryBuffer(Path);
38   if (Error E = BufferOrError.takeError())
39     return std::move(E);
40   return InstrProfReader::create(std::move(BufferOrError.get()));
41 }
42 
43 Expected<std::unique_ptr<InstrProfReader>>
44 InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
45   // Sanity check the buffer.
46   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
47     return make_error<InstrProfError>(instrprof_error::too_large);
48 
49   if (Buffer->getBufferSize() == 0)
50     return make_error<InstrProfError>(instrprof_error::empty_raw_profile);
51 
52   std::unique_ptr<InstrProfReader> Result;
53   // Create the reader.
54   if (IndexedInstrProfReader::hasFormat(*Buffer))
55     Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
56   else if (RawInstrProfReader64::hasFormat(*Buffer))
57     Result.reset(new RawInstrProfReader64(std::move(Buffer)));
58   else if (RawInstrProfReader32::hasFormat(*Buffer))
59     Result.reset(new RawInstrProfReader32(std::move(Buffer)));
60   else if (TextInstrProfReader::hasFormat(*Buffer))
61     Result.reset(new TextInstrProfReader(std::move(Buffer)));
62   else
63     return make_error<InstrProfError>(instrprof_error::unrecognized_format);
64 
65   // Initialize the reader and return the result.
66   if (Error E = initializeReader(*Result))
67     return std::move(E);
68 
69   return std::move(Result);
70 }
71 
72 Expected<std::unique_ptr<IndexedInstrProfReader>>
73 IndexedInstrProfReader::create(const Twine &Path) {
74   // Set up the buffer to read.
75   auto BufferOrError = setupMemoryBuffer(Path);
76   if (Error E = BufferOrError.takeError())
77     return std::move(E);
78   return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
79 }
80 
81 
82 Expected<std::unique_ptr<IndexedInstrProfReader>>
83 IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
84   // Sanity check the buffer.
85   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
86     return make_error<InstrProfError>(instrprof_error::too_large);
87 
88   // Create the reader.
89   if (!IndexedInstrProfReader::hasFormat(*Buffer))
90     return make_error<InstrProfError>(instrprof_error::bad_magic);
91   auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
92 
93   // Initialize the reader and return the result.
94   if (Error E = initializeReader(*Result))
95     return std::move(E);
96 
97   return std::move(Result);
98 }
99 
100 void InstrProfIterator::Increment() {
101   if (auto E = Reader->readNextRecord(Record)) {
102     // Handle errors in the reader.
103     InstrProfError::take(std::move(E));
104     *this = InstrProfIterator();
105   }
106 }
107 
108 bool TextInstrProfReader::hasFormat(const MemoryBuffer &Buffer) {
109   // Verify that this really looks like plain ASCII text by checking a
110   // 'reasonable' number of characters (up to profile magic size).
111   size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));
112   StringRef buffer = Buffer.getBufferStart();
113   return count == 0 ||
114          std::all_of(buffer.begin(), buffer.begin() + count,
115                      [](char c) { return ::isprint(c) || ::isspace(c); });
116 }
117 
118 // Read the profile variant flag from the header: ":FE" means this is a FE
119 // generated profile. ":IR" means this is an IR level profile. Other strings
120 // with a leading ':' will be reported an error format.
121 Error TextInstrProfReader::readHeader() {
122   Symtab.reset(new InstrProfSymtab());
123   bool IsIRInstr = false;
124   if (!Line->startswith(":")) {
125     IsIRLevelProfile = false;
126     return success();
127   }
128   StringRef Str = (Line)->substr(1);
129   if (Str.equals_lower("ir"))
130     IsIRInstr = true;
131   else if (Str.equals_lower("fe"))
132     IsIRInstr = false;
133   else
134     return error(instrprof_error::bad_header);
135 
136   ++Line;
137   IsIRLevelProfile = IsIRInstr;
138   return success();
139 }
140 
141 Error
142 TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
143 
144 #define CHECK_LINE_END(Line)                                                   \
145   if (Line.is_at_end())                                                        \
146     return error(instrprof_error::truncated);
147 #define READ_NUM(Str, Dst)                                                     \
148   if ((Str).getAsInteger(10, (Dst)))                                           \
149     return error(instrprof_error::malformed);
150 #define VP_READ_ADVANCE(Val)                                                   \
151   CHECK_LINE_END(Line);                                                        \
152   uint32_t Val;                                                                \
153   READ_NUM((*Line), (Val));                                                    \
154   Line++;
155 
156   if (Line.is_at_end())
157     return success();
158 
159   uint32_t NumValueKinds;
160   if (Line->getAsInteger(10, NumValueKinds)) {
161     // No value profile data
162     return success();
163   }
164   if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
165     return error(instrprof_error::malformed);
166   Line++;
167 
168   for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
169     VP_READ_ADVANCE(ValueKind);
170     if (ValueKind > IPVK_Last)
171       return error(instrprof_error::malformed);
172     VP_READ_ADVANCE(NumValueSites);
173     if (!NumValueSites)
174       continue;
175 
176     Record.reserveSites(VK, NumValueSites);
177     for (uint32_t S = 0; S < NumValueSites; S++) {
178       VP_READ_ADVANCE(NumValueData);
179 
180       std::vector<InstrProfValueData> CurrentValues;
181       for (uint32_t V = 0; V < NumValueData; V++) {
182         CHECK_LINE_END(Line);
183         std::pair<StringRef, StringRef> VD = Line->rsplit(':');
184         uint64_t TakenCount, Value;
185         if (ValueKind == IPVK_IndirectCallTarget) {
186           Symtab->addFuncName(VD.first);
187           Value = IndexedInstrProf::ComputeHash(VD.first);
188         } else {
189           READ_NUM(VD.first, Value);
190         }
191         READ_NUM(VD.second, TakenCount);
192         CurrentValues.push_back({Value, TakenCount});
193         Line++;
194       }
195       Record.addValueData(ValueKind, S, CurrentValues.data(), NumValueData,
196                           nullptr);
197     }
198   }
199   return success();
200 
201 #undef CHECK_LINE_END
202 #undef READ_NUM
203 #undef VP_READ_ADVANCE
204 }
205 
206 Error TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
207   // Skip empty lines and comments.
208   while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
209     ++Line;
210   // If we hit EOF while looking for a name, we're done.
211   if (Line.is_at_end()) {
212     Symtab->finalizeSymtab();
213     return error(instrprof_error::eof);
214   }
215 
216   // Read the function name.
217   Record.Name = *Line++;
218   Symtab->addFuncName(Record.Name);
219 
220   // Read the function hash.
221   if (Line.is_at_end())
222     return error(instrprof_error::truncated);
223   if ((Line++)->getAsInteger(0, Record.Hash))
224     return error(instrprof_error::malformed);
225 
226   // Read the number of counters.
227   uint64_t NumCounters;
228   if (Line.is_at_end())
229     return error(instrprof_error::truncated);
230   if ((Line++)->getAsInteger(10, NumCounters))
231     return error(instrprof_error::malformed);
232   if (NumCounters == 0)
233     return error(instrprof_error::malformed);
234 
235   // Read each counter and fill our internal storage with the values.
236   Record.Counts.clear();
237   Record.Counts.reserve(NumCounters);
238   for (uint64_t I = 0; I < NumCounters; ++I) {
239     if (Line.is_at_end())
240       return error(instrprof_error::truncated);
241     uint64_t Count;
242     if ((Line++)->getAsInteger(10, Count))
243       return error(instrprof_error::malformed);
244     Record.Counts.push_back(Count);
245   }
246 
247   // Check if value profile data exists and read it if so.
248   if (Error E = readValueProfileData(Record))
249     return E;
250 
251   // This is needed to avoid two pass parsing because llvm-profdata
252   // does dumping while reading.
253   Symtab->finalizeSymtab();
254   return success();
255 }
256 
257 template <class IntPtrT>
258 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
259   if (DataBuffer.getBufferSize() < sizeof(uint64_t))
260     return false;
261   uint64_t Magic =
262     *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
263   return RawInstrProf::getMagic<IntPtrT>() == Magic ||
264          sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
265 }
266 
267 template <class IntPtrT>
268 Error RawInstrProfReader<IntPtrT>::readHeader() {
269   if (!hasFormat(*DataBuffer))
270     return error(instrprof_error::bad_magic);
271   if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
272     return error(instrprof_error::bad_header);
273   auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
274       DataBuffer->getBufferStart());
275   ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
276   return readHeader(*Header);
277 }
278 
279 template <class IntPtrT>
280 Error RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
281   const char *End = DataBuffer->getBufferEnd();
282   // Skip zero padding between profiles.
283   while (CurrentPos != End && *CurrentPos == 0)
284     ++CurrentPos;
285   // If there's nothing left, we're done.
286   if (CurrentPos == End)
287     return make_error<InstrProfError>(instrprof_error::eof);
288   // If there isn't enough space for another header, this is probably just
289   // garbage at the end of the file.
290   if (CurrentPos + sizeof(RawInstrProf::Header) > End)
291     return make_error<InstrProfError>(instrprof_error::malformed);
292   // The writer ensures each profile is padded to start at an aligned address.
293   if (reinterpret_cast<size_t>(CurrentPos) % alignof(uint64_t))
294     return make_error<InstrProfError>(instrprof_error::malformed);
295   // The magic should have the same byte order as in the previous header.
296   uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
297   if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
298     return make_error<InstrProfError>(instrprof_error::bad_magic);
299 
300   // There's another profile to read, so we need to process the header.
301   auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
302   return readHeader(*Header);
303 }
304 
305 template <class IntPtrT>
306 Error RawInstrProfReader<IntPtrT>::createSymtab(InstrProfSymtab &Symtab) {
307   if (Error E = Symtab.create(StringRef(NamesStart, NamesSize)))
308     return error(std::move(E));
309   for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
310     const IntPtrT FPtr = swap(I->FunctionPointer);
311     if (!FPtr)
312       continue;
313     Symtab.mapAddress(FPtr, I->NameRef);
314   }
315   Symtab.finalizeSymtab();
316   return success();
317 }
318 
319 template <class IntPtrT>
320 Error RawInstrProfReader<IntPtrT>::readHeader(
321     const RawInstrProf::Header &Header) {
322   Version = swap(Header.Version);
323   if (GET_VERSION(Version) != RawInstrProf::Version)
324     return error(instrprof_error::unsupported_version);
325 
326   CountersDelta = swap(Header.CountersDelta);
327   NamesDelta = swap(Header.NamesDelta);
328   auto DataSize = swap(Header.DataSize);
329   auto CountersSize = swap(Header.CountersSize);
330   NamesSize = swap(Header.NamesSize);
331   ValueKindLast = swap(Header.ValueKindLast);
332 
333   auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
334   auto PaddingSize = getNumPaddingBytes(NamesSize);
335 
336   ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
337   ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
338   ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
339   ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
340 
341   auto *Start = reinterpret_cast<const char *>(&Header);
342   if (Start + ValueDataOffset > DataBuffer->getBufferEnd())
343     return error(instrprof_error::bad_header);
344 
345   Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
346       Start + DataOffset);
347   DataEnd = Data + DataSize;
348   CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
349   NamesStart = Start + NamesOffset;
350   ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset);
351 
352   std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
353   if (Error E = createSymtab(*NewSymtab.get()))
354     return E;
355 
356   Symtab = std::move(NewSymtab);
357   return success();
358 }
359 
360 template <class IntPtrT>
361 Error RawInstrProfReader<IntPtrT>::readName(InstrProfRecord &Record) {
362   Record.Name = getName(Data->NameRef);
363   return success();
364 }
365 
366 template <class IntPtrT>
367 Error RawInstrProfReader<IntPtrT>::readFuncHash(InstrProfRecord &Record) {
368   Record.Hash = swap(Data->FuncHash);
369   return success();
370 }
371 
372 template <class IntPtrT>
373 Error RawInstrProfReader<IntPtrT>::readRawCounts(
374     InstrProfRecord &Record) {
375   uint32_t NumCounters = swap(Data->NumCounters);
376   IntPtrT CounterPtr = Data->CounterPtr;
377   if (NumCounters == 0)
378     return error(instrprof_error::malformed);
379 
380   auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
381   auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
382 
383   // Check bounds.
384   if (RawCounts.data() < CountersStart ||
385       RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
386     return error(instrprof_error::malformed);
387 
388   if (ShouldSwapBytes) {
389     Record.Counts.clear();
390     Record.Counts.reserve(RawCounts.size());
391     for (uint64_t Count : RawCounts)
392       Record.Counts.push_back(swap(Count));
393   } else
394     Record.Counts = RawCounts;
395 
396   return success();
397 }
398 
399 template <class IntPtrT>
400 Error RawInstrProfReader<IntPtrT>::readValueProfilingData(
401     InstrProfRecord &Record) {
402 
403   Record.clearValueData();
404   CurValueDataSize = 0;
405   // Need to match the logic in value profile dumper code in compiler-rt:
406   uint32_t NumValueKinds = 0;
407   for (uint32_t I = 0; I < IPVK_Last + 1; I++)
408     NumValueKinds += (Data->NumValueSites[I] != 0);
409 
410   if (!NumValueKinds)
411     return success();
412 
413   Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
414       ValueProfData::getValueProfData(
415           ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(),
416           getDataEndianness());
417 
418   if (Error E = VDataPtrOrErr.takeError())
419     return E;
420 
421   // Note that besides deserialization, this also performs the conversion for
422   // indirect call targets.  The function pointers from the raw profile are
423   // remapped into function name hashes.
424   VDataPtrOrErr.get()->deserializeTo(Record, &Symtab->getAddrHashMap());
425   CurValueDataSize = VDataPtrOrErr.get()->getSize();
426   return success();
427 }
428 
429 template <class IntPtrT>
430 Error RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
431   if (atEnd())
432     // At this point, ValueDataStart field points to the next header.
433     if (Error E = readNextHeader(getNextHeaderPos()))
434       return E;
435 
436   // Read name ad set it in Record.
437   if (Error E = readName(Record))
438     return E;
439 
440   // Read FuncHash and set it in Record.
441   if (Error E = readFuncHash(Record))
442     return E;
443 
444   // Read raw counts and set Record.
445   if (Error E = readRawCounts(Record))
446     return E;
447 
448   // Read value data and set Record.
449   if (Error E = readValueProfilingData(Record))
450     return E;
451 
452   // Iterate.
453   advanceData();
454   return success();
455 }
456 
457 namespace llvm {
458 template class RawInstrProfReader<uint32_t>;
459 template class RawInstrProfReader<uint64_t>;
460 }
461 
462 InstrProfLookupTrait::hash_value_type
463 InstrProfLookupTrait::ComputeHash(StringRef K) {
464   return IndexedInstrProf::ComputeHash(HashType, K);
465 }
466 
467 typedef InstrProfLookupTrait::data_type data_type;
468 typedef InstrProfLookupTrait::offset_type offset_type;
469 
470 bool InstrProfLookupTrait::readValueProfilingData(
471     const unsigned char *&D, const unsigned char *const End) {
472   Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
473       ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
474 
475   if (VDataPtrOrErr.takeError())
476     return false;
477 
478   VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr);
479   D += VDataPtrOrErr.get()->TotalSize;
480 
481   return true;
482 }
483 
484 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
485                                          offset_type N) {
486   // Check if the data is corrupt. If so, don't try to read it.
487   if (N % sizeof(uint64_t))
488     return data_type();
489 
490   DataBuffer.clear();
491   std::vector<uint64_t> CounterBuffer;
492 
493   using namespace support;
494   const unsigned char *End = D + N;
495   while (D < End) {
496     // Read hash.
497     if (D + sizeof(uint64_t) >= End)
498       return data_type();
499     uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
500 
501     // Initialize number of counters for GET_VERSION(FormatVersion) == 1.
502     uint64_t CountsSize = N / sizeof(uint64_t) - 1;
503     // If format version is different then read the number of counters.
504     if (GET_VERSION(FormatVersion) != IndexedInstrProf::ProfVersion::Version1) {
505       if (D + sizeof(uint64_t) > End)
506         return data_type();
507       CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
508     }
509     // Read counter values.
510     if (D + CountsSize * sizeof(uint64_t) > End)
511       return data_type();
512 
513     CounterBuffer.clear();
514     CounterBuffer.reserve(CountsSize);
515     for (uint64_t J = 0; J < CountsSize; ++J)
516       CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
517 
518     DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
519 
520     // Read value profiling data.
521     if (GET_VERSION(FormatVersion) > IndexedInstrProf::ProfVersion::Version2 &&
522         !readValueProfilingData(D, End)) {
523       DataBuffer.clear();
524       return data_type();
525     }
526   }
527   return DataBuffer;
528 }
529 
530 template <typename HashTableImpl>
531 Error InstrProfReaderIndex<HashTableImpl>::getRecords(
532     StringRef FuncName, ArrayRef<InstrProfRecord> &Data) {
533   auto Iter = HashTable->find(FuncName);
534   if (Iter == HashTable->end())
535     return make_error<InstrProfError>(instrprof_error::unknown_function);
536 
537   Data = (*Iter);
538   if (Data.empty())
539     return make_error<InstrProfError>(instrprof_error::malformed);
540 
541   return Error::success();
542 }
543 
544 template <typename HashTableImpl>
545 Error InstrProfReaderIndex<HashTableImpl>::getRecords(
546     ArrayRef<InstrProfRecord> &Data) {
547   if (atEnd())
548     return make_error<InstrProfError>(instrprof_error::eof);
549 
550   Data = *RecordIterator;
551 
552   if (Data.empty())
553     return make_error<InstrProfError>(instrprof_error::malformed);
554 
555   return Error::success();
556 }
557 
558 template <typename HashTableImpl>
559 InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
560     const unsigned char *Buckets, const unsigned char *const Payload,
561     const unsigned char *const Base, IndexedInstrProf::HashT HashType,
562     uint64_t Version) {
563   FormatVersion = Version;
564   HashTable.reset(HashTableImpl::Create(
565       Buckets, Payload, Base,
566       typename HashTableImpl::InfoType(HashType, Version)));
567   RecordIterator = HashTable->data_begin();
568 }
569 
570 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
571   if (DataBuffer.getBufferSize() < 8)
572     return false;
573   using namespace support;
574   uint64_t Magic =
575       endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
576   // Verify that it's magical.
577   return Magic == IndexedInstrProf::Magic;
578 }
579 
580 const unsigned char *
581 IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version,
582                                     const unsigned char *Cur) {
583   using namespace IndexedInstrProf;
584   using namespace support;
585   if (Version >= IndexedInstrProf::Version4) {
586     const IndexedInstrProf::Summary *SummaryInLE =
587         reinterpret_cast<const IndexedInstrProf::Summary *>(Cur);
588     uint64_t NFields =
589         endian::byte_swap<uint64_t, little>(SummaryInLE->NumSummaryFields);
590     uint64_t NEntries =
591         endian::byte_swap<uint64_t, little>(SummaryInLE->NumCutoffEntries);
592     uint32_t SummarySize =
593         IndexedInstrProf::Summary::getSize(NFields, NEntries);
594     std::unique_ptr<IndexedInstrProf::Summary> SummaryData =
595         IndexedInstrProf::allocSummary(SummarySize);
596 
597     const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE);
598     uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get());
599     for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
600       Dst[I] = endian::byte_swap<uint64_t, little>(Src[I]);
601 
602     llvm::SummaryEntryVector DetailedSummary;
603     for (unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) {
604       const IndexedInstrProf::Summary::Entry &Ent = SummaryData->getEntry(I);
605       DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,
606                                    Ent.NumBlocks);
607     }
608     // initialize InstrProfSummary using the SummaryData from disk.
609     this->Summary = llvm::make_unique<ProfileSummary>(
610         ProfileSummary::PSK_Instr, DetailedSummary,
611         SummaryData->get(Summary::TotalBlockCount),
612         SummaryData->get(Summary::MaxBlockCount),
613         SummaryData->get(Summary::MaxInternalBlockCount),
614         SummaryData->get(Summary::MaxFunctionCount),
615         SummaryData->get(Summary::TotalNumBlocks),
616         SummaryData->get(Summary::TotalNumFunctions));
617     return Cur + SummarySize;
618   } else {
619     // For older version of profile data, we need to compute on the fly:
620     using namespace IndexedInstrProf;
621     InstrProfSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
622     // FIXME: This only computes an empty summary. Need to call addRecord for
623     // all InstrProfRecords to get the correct summary.
624     this->Summary = Builder.getSummary();
625     return Cur;
626   }
627 }
628 
629 Error IndexedInstrProfReader::readHeader() {
630   const unsigned char *Start =
631       (const unsigned char *)DataBuffer->getBufferStart();
632   const unsigned char *Cur = Start;
633   if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
634     return error(instrprof_error::truncated);
635 
636   using namespace support;
637 
638   auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
639   Cur += sizeof(IndexedInstrProf::Header);
640 
641   // Check the magic number.
642   uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
643   if (Magic != IndexedInstrProf::Magic)
644     return error(instrprof_error::bad_magic);
645 
646   // Read the version.
647   uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
648   if (GET_VERSION(FormatVersion) >
649       IndexedInstrProf::ProfVersion::CurrentVersion)
650     return error(instrprof_error::unsupported_version);
651 
652   Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur);
653 
654   // Read the hash type and start offset.
655   IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
656       endian::byte_swap<uint64_t, little>(Header->HashType));
657   if (HashType > IndexedInstrProf::HashT::Last)
658     return error(instrprof_error::unsupported_hash_type);
659 
660   uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
661 
662   // The rest of the file is an on disk hash table.
663   InstrProfReaderIndexBase *IndexPtr = nullptr;
664   IndexPtr = new InstrProfReaderIndex<OnDiskHashTableImplV3>(
665       Start + HashOffset, Cur, Start, HashType, FormatVersion);
666   Index.reset(IndexPtr);
667   return success();
668 }
669 
670 InstrProfSymtab &IndexedInstrProfReader::getSymtab() {
671   if (Symtab.get())
672     return *Symtab.get();
673 
674   std::unique_ptr<InstrProfSymtab> NewSymtab = make_unique<InstrProfSymtab>();
675   Index->populateSymtab(*NewSymtab.get());
676 
677   Symtab = std::move(NewSymtab);
678   return *Symtab.get();
679 }
680 
681 Expected<InstrProfRecord>
682 IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
683                                            uint64_t FuncHash) {
684   ArrayRef<InstrProfRecord> Data;
685   Error Err = Index->getRecords(FuncName, Data);
686   if (Err)
687     return std::move(Err);
688   // Found it. Look for counters with the right hash.
689   for (unsigned I = 0, E = Data.size(); I < E; ++I) {
690     // Check for a match and fill the vector if there is one.
691     if (Data[I].Hash == FuncHash) {
692       return std::move(Data[I]);
693     }
694   }
695   return error(instrprof_error::hash_mismatch);
696 }
697 
698 Error IndexedInstrProfReader::getFunctionCounts(StringRef FuncName,
699                                                 uint64_t FuncHash,
700                                                 std::vector<uint64_t> &Counts) {
701   Expected<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
702   if (Error E = Record.takeError())
703     return error(std::move(E));
704 
705   Counts = Record.get().Counts;
706   return success();
707 }
708 
709 Error IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) {
710   static unsigned RecordIndex = 0;
711 
712   ArrayRef<InstrProfRecord> Data;
713 
714   Error E = Index->getRecords(Data);
715   if (E)
716     return error(std::move(E));
717 
718   Record = Data[RecordIndex++];
719   if (RecordIndex >= Data.size()) {
720     Index->advanceToNextKey();
721     RecordIndex = 0;
722   }
723   return success();
724 }
725