Enhance BranchProbabilityInfo::calcUnreachableHeuristics for InvokeInst
[oota-llvm.git] / lib / ProfileData / InstrProfReader.cpp
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 ErrorOr<std::unique_ptr<MemoryBuffer>>
22 setupMemoryBuffer(std::string Path) {
23   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
24       MemoryBuffer::getFileOrSTDIN(Path);
25   if (std::error_code EC = BufferOrErr.getError())
26     return EC;
27   return std::move(BufferOrErr.get());
28 }
29
30 static std::error_code initializeReader(InstrProfReader &Reader) {
31   return Reader.readHeader();
32 }
33
34 ErrorOr<std::unique_ptr<InstrProfReader>>
35 InstrProfReader::create(std::string Path) {
36   // Set up the buffer to read.
37   auto BufferOrError = setupMemoryBuffer(Path);
38   if (std::error_code EC = BufferOrError.getError())
39     return EC;
40   return InstrProfReader::create(std::move(BufferOrError.get()));
41 }
42
43 ErrorOr<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 instrprof_error::too_large;
48
49   std::unique_ptr<InstrProfReader> Result;
50   // Create the reader.
51   if (IndexedInstrProfReader::hasFormat(*Buffer))
52     Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
53   else if (RawInstrProfReader64::hasFormat(*Buffer))
54     Result.reset(new RawInstrProfReader64(std::move(Buffer)));
55   else if (RawInstrProfReader32::hasFormat(*Buffer))
56     Result.reset(new RawInstrProfReader32(std::move(Buffer)));
57   else if (TextInstrProfReader::hasFormat(*Buffer))
58     Result.reset(new TextInstrProfReader(std::move(Buffer)));
59   else
60     return instrprof_error::unrecognized_format;
61
62   // Initialize the reader and return the result.
63   if (std::error_code EC = initializeReader(*Result))
64     return EC;
65
66   return std::move(Result);
67 }
68
69 ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
70 IndexedInstrProfReader::create(std::string Path) {
71   // Set up the buffer to read.
72   auto BufferOrError = setupMemoryBuffer(Path);
73   if (std::error_code EC = BufferOrError.getError())
74     return EC;
75   return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
76 }
77
78
79 ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
80 IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
81   // Sanity check the buffer.
82   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
83     return instrprof_error::too_large;
84
85   // Create the reader.
86   if (!IndexedInstrProfReader::hasFormat(*Buffer))
87     return instrprof_error::bad_magic;
88   auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
89
90   // Initialize the reader and return the result.
91   if (std::error_code EC = initializeReader(*Result))
92     return EC;
93
94   return std::move(Result);
95 }
96
97 void InstrProfIterator::Increment() {
98   if (Reader->readNextRecord(Record))
99     *this = InstrProfIterator();
100 }
101
102 bool TextInstrProfReader::hasFormat(const MemoryBuffer &Buffer) {
103   // Verify that this really looks like plain ASCII text by checking a
104   // 'reasonable' number of characters (up to profile magic size).
105   size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t));
106   StringRef buffer = Buffer.getBufferStart();
107   return count == 0 ||
108          std::all_of(buffer.begin(), buffer.begin() + count,
109                      [](char c) { return ::isprint(c) || ::isspace(c); });
110 }
111
112 std::error_code
113 TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
114
115 #define CHECK_LINE_END(Line)                                                   \
116   if (Line.is_at_end())                                                        \
117     return error(instrprof_error::truncated);
118 #define READ_NUM(Str, Dst)                                                     \
119   if ((Str).getAsInteger(10, (Dst)))                                           \
120     return error(instrprof_error::malformed);
121 #define VP_READ_ADVANCE(Val)                                                   \
122   CHECK_LINE_END(Line);                                                        \
123   uint32_t Val;                                                                \
124   READ_NUM((*Line), (Val));                                                    \
125   Line++;
126
127   if (Line.is_at_end())
128     return success();
129   uint32_t NumValueKinds;
130   if (Line->getAsInteger(10, NumValueKinds)) {
131     // No value profile data
132     return success();
133   }
134   if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
135     return error(instrprof_error::malformed);
136   Line++;
137
138   for (uint32_t VK = 0; VK < NumValueKinds; VK++) {
139     VP_READ_ADVANCE(ValueKind);
140     if (ValueKind > IPVK_Last)
141       return error(instrprof_error::malformed);
142     VP_READ_ADVANCE(NumValueSites);
143     if (!NumValueSites)
144       continue;
145
146     Record.reserveSites(VK, NumValueSites);
147     for (uint32_t S = 0; S < NumValueSites; S++) {
148       VP_READ_ADVANCE(NumValueData);
149
150       std::vector<InstrProfValueData> CurrentValues;
151       for (uint32_t V = 0; V < NumValueData; V++) {
152         CHECK_LINE_END(Line);
153         std::pair<StringRef, StringRef> VD = Line->split(':');
154         uint64_t TakenCount, Value;
155         READ_NUM(VD.second, TakenCount);
156         if (VK == IPVK_IndirectCallTarget)
157           Value = (uint64_t)StringTable.insertString(VD.first);
158         else {
159           READ_NUM(VD.first, Value);
160         }
161         CurrentValues.push_back({Value, TakenCount});
162         Line++;
163       }
164       Record.addValueData(VK, S, CurrentValues.data(), NumValueData, nullptr);
165     }
166   }
167   return success();
168
169 #undef CHECK_LINE_END
170 #undef READ_NUM
171 #undef VP_READ_ADVANCE
172 }
173
174 std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
175   // Skip empty lines and comments.
176   while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
177     ++Line;
178   // If we hit EOF while looking for a name, we're done.
179   if (Line.is_at_end())
180     return error(instrprof_error::eof);
181
182   // Read the function name.
183   Record.Name = *Line++;
184
185   // Read the function hash.
186   if (Line.is_at_end())
187     return error(instrprof_error::truncated);
188   if ((Line++)->getAsInteger(0, Record.Hash))
189     return error(instrprof_error::malformed);
190
191   // Read the number of counters.
192   uint64_t NumCounters;
193   if (Line.is_at_end())
194     return error(instrprof_error::truncated);
195   if ((Line++)->getAsInteger(10, NumCounters))
196     return error(instrprof_error::malformed);
197   if (NumCounters == 0)
198     return error(instrprof_error::malformed);
199
200   // Read each counter and fill our internal storage with the values.
201   Record.Counts.clear();
202   Record.Counts.reserve(NumCounters);
203   for (uint64_t I = 0; I < NumCounters; ++I) {
204     if (Line.is_at_end())
205       return error(instrprof_error::truncated);
206     uint64_t Count;
207     if ((Line++)->getAsInteger(10, Count))
208       return error(instrprof_error::malformed);
209     Record.Counts.push_back(Count);
210   }
211
212   // Check if value profile data exists and read it if so.
213   if (std::error_code EC = readValueProfileData(Record))
214     return EC;
215
216   return success();
217 }
218
219 template <class IntPtrT>
220 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
221   if (DataBuffer.getBufferSize() < sizeof(uint64_t))
222     return false;
223   uint64_t Magic =
224     *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
225   return RawInstrProf::getMagic<IntPtrT>() == Magic ||
226          sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
227 }
228
229 template <class IntPtrT>
230 std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
231   if (!hasFormat(*DataBuffer))
232     return error(instrprof_error::bad_magic);
233   if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
234     return error(instrprof_error::bad_header);
235   auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
236       DataBuffer->getBufferStart());
237   ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
238   return readHeader(*Header);
239 }
240
241 template <class IntPtrT>
242 std::error_code
243 RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
244   const char *End = DataBuffer->getBufferEnd();
245   // Skip zero padding between profiles.
246   while (CurrentPos != End && *CurrentPos == 0)
247     ++CurrentPos;
248   // If there's nothing left, we're done.
249   if (CurrentPos == End)
250     return instrprof_error::eof;
251   // If there isn't enough space for another header, this is probably just
252   // garbage at the end of the file.
253   if (CurrentPos + sizeof(RawInstrProf::Header) > End)
254     return instrprof_error::malformed;
255   // The writer ensures each profile is padded to start at an aligned address.
256   if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
257     return instrprof_error::malformed;
258   // The magic should have the same byte order as in the previous header.
259   uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
260   if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
261     return instrprof_error::bad_magic;
262
263   // There's another profile to read, so we need to process the header.
264   auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
265   return readHeader(*Header);
266 }
267
268 template <class IntPtrT>
269 std::error_code RawInstrProfReader<IntPtrT>::readHeader(
270     const RawInstrProf::Header &Header) {
271   if (swap(Header.Version) != RawInstrProf::Version)
272     return error(instrprof_error::unsupported_version);
273
274   CountersDelta = swap(Header.CountersDelta);
275   NamesDelta = swap(Header.NamesDelta);
276   auto DataSize = swap(Header.DataSize);
277   auto CountersSize = swap(Header.CountersSize);
278   auto NamesSize = swap(Header.NamesSize);
279   auto ValueDataSize = swap(Header.ValueDataSize);
280   ValueKindLast = swap(Header.ValueKindLast);
281
282   auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
283   auto PaddingSize = getNumPaddingBytes(NamesSize);
284
285   ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
286   ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
287   ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
288   ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
289   size_t ProfileSize = ValueDataOffset + ValueDataSize;
290
291   auto *Start = reinterpret_cast<const char *>(&Header);
292   if (Start + ProfileSize > DataBuffer->getBufferEnd())
293     return error(instrprof_error::bad_header);
294
295   Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
296       Start + DataOffset);
297   DataEnd = Data + DataSize;
298   CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
299   NamesStart = Start + NamesOffset;
300   ValueDataStart = reinterpret_cast<const uint8_t*>(Start + ValueDataOffset);
301   ProfileEnd = Start + ProfileSize;
302
303   FunctionPtrToNameMap.clear();
304   for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
305     const IntPtrT FPtr = swap(I->FunctionPointer);
306     if (!FPtr)
307       continue;
308     StringRef FunctionName(getName(I->NamePtr), swap(I->NameSize));
309     const char* NameEntryPtr = StringTable.insertString(FunctionName);
310     FunctionPtrToNameMap.push_back(std::pair<const IntPtrT, const char*>
311                                    (FPtr, NameEntryPtr));
312   }
313   std::sort(FunctionPtrToNameMap.begin(), FunctionPtrToNameMap.end(), less_first());
314   FunctionPtrToNameMap.erase(std::unique(FunctionPtrToNameMap.begin(),
315                                          FunctionPtrToNameMap.end()),
316                                          FunctionPtrToNameMap.end());
317   return success();
318 }
319
320 template <class IntPtrT>
321 std::error_code RawInstrProfReader<IntPtrT>::readName(InstrProfRecord &Record) {
322   Record.Name = StringRef(getName(Data->NamePtr), swap(Data->NameSize));
323   if (Record.Name.data() < NamesStart ||
324       Record.Name.data() + Record.Name.size() >
325           reinterpret_cast<const char *>(ValueDataStart))
326     return error(instrprof_error::malformed);
327   return success();
328 }
329
330 template <class IntPtrT>
331 std::error_code RawInstrProfReader<IntPtrT>::readFuncHash(
332     InstrProfRecord &Record) {
333   Record.Hash = swap(Data->FuncHash);
334   return success();
335 }
336
337 template <class IntPtrT>
338 std::error_code RawInstrProfReader<IntPtrT>::readRawCounts(
339     InstrProfRecord &Record) {
340   uint32_t NumCounters = swap(Data->NumCounters);
341   IntPtrT CounterPtr = Data->CounterPtr;
342   if (NumCounters == 0)
343     return error(instrprof_error::malformed);
344
345   auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
346   auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
347
348   // Check bounds.
349   if (RawCounts.data() < CountersStart ||
350       RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
351     return error(instrprof_error::malformed);
352
353   if (ShouldSwapBytes) {
354     Record.Counts.clear();
355     Record.Counts.reserve(RawCounts.size());
356     for (uint64_t Count : RawCounts)
357       Record.Counts.push_back(swap(Count));
358   } else
359     Record.Counts = RawCounts;
360
361   return success();
362 }
363
364 template <class IntPtrT>
365 std::error_code
366 RawInstrProfReader<IntPtrT>::readValueProfilingData(InstrProfRecord &Record) {
367
368   Record.clearValueData();
369   CurValueDataSize = 0;
370   // Need to match the logic in value profile dumper code in compiler-rt:
371   uint32_t NumValueKinds = 0;
372   for (uint32_t I = 0; I < IPVK_Last + 1; I++)
373     NumValueKinds += (Data->NumValueSites[I] != 0);
374
375   if (!NumValueKinds)
376     return success();
377
378   ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
379       ValueProfData::getValueProfData(ValueDataStart,
380                                       (const unsigned char *)ProfileEnd,
381                                       getDataEndianness());
382
383   if (VDataPtrOrErr.getError())
384     return VDataPtrOrErr.getError();
385
386   VDataPtrOrErr.get()->deserializeTo(Record, &FunctionPtrToNameMap);
387   CurValueDataSize = VDataPtrOrErr.get()->getSize();
388   return success();
389 }
390
391 template <class IntPtrT>
392 std::error_code
393 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
394   if (atEnd())
395     if (std::error_code EC = readNextHeader(ProfileEnd))
396       return EC;
397
398   // Read name ad set it in Record.
399   if (std::error_code EC = readName(Record))
400     return EC;
401
402   // Read FuncHash and set it in Record.
403   if (std::error_code EC = readFuncHash(Record))
404     return EC;
405
406   // Read raw counts and set Record.
407   if (std::error_code EC = readRawCounts(Record))
408     return EC;
409
410   // Read value data and set Record.
411   if (std::error_code EC = readValueProfilingData(Record))
412     return EC;
413
414   // Iterate.
415   advanceData();
416   return success();
417 }
418
419 namespace llvm {
420 template class RawInstrProfReader<uint32_t>;
421 template class RawInstrProfReader<uint64_t>;
422 }
423
424 InstrProfLookupTrait::hash_value_type
425 InstrProfLookupTrait::ComputeHash(StringRef K) {
426   return IndexedInstrProf::ComputeHash(HashType, K);
427 }
428
429 typedef InstrProfLookupTrait::data_type data_type;
430 typedef InstrProfLookupTrait::offset_type offset_type;
431
432 bool InstrProfLookupTrait::readValueProfilingData(
433     const unsigned char *&D, const unsigned char *const End) {
434   ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
435       ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
436
437   if (VDataPtrOrErr.getError())
438     return false;
439
440   VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), &HashKeys);
441   D += VDataPtrOrErr.get()->TotalSize;
442
443   return true;
444 }
445
446 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
447                                          offset_type N) {
448   // Check if the data is corrupt. If so, don't try to read it.
449   if (N % sizeof(uint64_t))
450     return data_type();
451
452   DataBuffer.clear();
453   std::vector<uint64_t> CounterBuffer;
454
455   using namespace support;
456   const unsigned char *End = D + N;
457   while (D < End) {
458     // Read hash.
459     if (D + sizeof(uint64_t) >= End)
460       return data_type();
461     uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
462
463     // Initialize number of counters for FormatVersion == 1.
464     uint64_t CountsSize = N / sizeof(uint64_t) - 1;
465     // If format version is different then read the number of counters.
466     if (FormatVersion != 1) {
467       if (D + sizeof(uint64_t) > End)
468         return data_type();
469       CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
470     }
471     // Read counter values.
472     if (D + CountsSize * sizeof(uint64_t) > End)
473       return data_type();
474
475     CounterBuffer.clear();
476     CounterBuffer.reserve(CountsSize);
477     for (uint64_t J = 0; J < CountsSize; ++J)
478       CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
479
480     DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
481
482     // Read value profiling data.
483     if (FormatVersion > 2 && !readValueProfilingData(D, End)) {
484       DataBuffer.clear();
485       return data_type();
486     }
487   }
488   return DataBuffer;
489 }
490
491 template <typename HashTableImpl>
492 std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
493     StringRef FuncName, ArrayRef<InstrProfRecord> &Data) {
494   auto Iter = HashTable->find(FuncName);
495   if (Iter == HashTable->end())
496     return instrprof_error::unknown_function;
497
498   Data = (*Iter);
499   if (Data.empty())
500     return instrprof_error::malformed;
501
502   return instrprof_error::success;
503 }
504
505 template <typename HashTableImpl>
506 std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
507     ArrayRef<InstrProfRecord> &Data) {
508   if (atEnd())
509     return instrprof_error::eof;
510
511   Data = *RecordIterator;
512
513   if (Data.empty())
514     return instrprof_error::malformed;
515
516   return instrprof_error::success;
517 }
518
519 template <typename HashTableImpl>
520 InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
521     const unsigned char *Buckets, const unsigned char *const Payload,
522     const unsigned char *const Base, IndexedInstrProf::HashT HashType,
523     uint64_t Version) {
524   FormatVersion = Version;
525   HashTable.reset(HashTableImpl::Create(
526       Buckets, Payload, Base,
527       typename HashTableImpl::InfoType(HashType, Version)));
528   // Form the map of hash values to const char* keys in profiling data.
529   std::vector<std::pair<uint64_t, const char *>> HashKeys;
530   for (auto Key : HashTable->keys()) {
531     const char *KeyTableRef = StringTable.insertString(Key);
532     HashKeys.push_back(std::make_pair(ComputeHash(HashType, Key), KeyTableRef));
533   }
534   std::sort(HashKeys.begin(), HashKeys.end(), less_first());
535   HashKeys.erase(std::unique(HashKeys.begin(), HashKeys.end()), HashKeys.end());
536   // Set the hash key map for the InstrLookupTrait
537   HashTable->getInfoObj().setHashKeys(std::move(HashKeys));
538   RecordIterator = HashTable->data_begin();
539 }
540
541 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
542   if (DataBuffer.getBufferSize() < 8)
543     return false;
544   using namespace support;
545   uint64_t Magic =
546       endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
547   // Verify that it's magical.
548   return Magic == IndexedInstrProf::Magic;
549 }
550
551 std::error_code IndexedInstrProfReader::readHeader() {
552   const unsigned char *Start =
553       (const unsigned char *)DataBuffer->getBufferStart();
554   const unsigned char *Cur = Start;
555   if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
556     return error(instrprof_error::truncated);
557
558   using namespace support;
559
560   auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
561   Cur += sizeof(IndexedInstrProf::Header);
562
563   // Check the magic number.
564   uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
565   if (Magic != IndexedInstrProf::Magic)
566     return error(instrprof_error::bad_magic);
567
568   // Read the version.
569   uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
570   if (FormatVersion > IndexedInstrProf::Version)
571     return error(instrprof_error::unsupported_version);
572
573   // Read the maximal function count.
574   MaxFunctionCount =
575       endian::byte_swap<uint64_t, little>(Header->MaxFunctionCount);
576
577   // Read the hash type and start offset.
578   IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
579       endian::byte_swap<uint64_t, little>(Header->HashType));
580   if (HashType > IndexedInstrProf::HashT::Last)
581     return error(instrprof_error::unsupported_hash_type);
582
583   uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
584
585   // The rest of the file is an on disk hash table.
586   InstrProfReaderIndexBase *IndexPtr = nullptr;
587   IndexPtr = new InstrProfReaderIndex<OnDiskHashTableImplV3>(
588       Start + HashOffset, Cur, Start, HashType, FormatVersion);
589   Index.reset(IndexPtr);
590   return success();
591 }
592
593 ErrorOr<InstrProfRecord>
594 IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
595                                            uint64_t FuncHash) {
596   ArrayRef<InstrProfRecord> Data;
597   std::error_code EC = Index->getRecords(FuncName, Data);
598   if (EC != instrprof_error::success)
599     return EC;
600   // Found it. Look for counters with the right hash.
601   for (unsigned I = 0, E = Data.size(); I < E; ++I) {
602     // Check for a match and fill the vector if there is one.
603     if (Data[I].Hash == FuncHash) {
604       return std::move(Data[I]);
605     }
606   }
607   return error(instrprof_error::hash_mismatch);
608 }
609
610 std::error_code
611 IndexedInstrProfReader::getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
612                                           std::vector<uint64_t> &Counts) {
613   ErrorOr<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
614   if (std::error_code EC = Record.getError())
615     return EC;
616
617   Counts = Record.get().Counts;
618   return success();
619 }
620
621 std::error_code IndexedInstrProfReader::readNextRecord(
622     InstrProfRecord &Record) {
623   static unsigned RecordIndex = 0;
624
625   ArrayRef<InstrProfRecord> Data;
626
627   std::error_code EC = Index->getRecords(Data);
628   if (EC != instrprof_error::success)
629     return error(EC);
630
631   Record = Data[RecordIndex++];
632   if (RecordIndex >= Data.size()) {
633     Index->advanceToNextKey();
634     RecordIndex = 0;
635   }
636   return success();
637 }