1 //=-- InstrProfReader.cpp - Instrumented profiling reader -------------------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for reading profiling data for clang's
11 // instrumentation based PGO and coverage.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ProfileData/InstrProfReader.h"
16 #include "llvm/ADT/STLExtras.h"
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())
27 return std::move(BufferOrErr.get());
30 static std::error_code initializeReader(InstrProfReader &Reader) {
31 return Reader.readHeader();
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())
40 return InstrProfReader::create(std::move(BufferOrError.get()));
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;
49 std::unique_ptr<InstrProfReader> Result;
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)));
60 return instrprof_error::unrecognized_format;
62 // Initialize the reader and return the result.
63 if (std::error_code EC = initializeReader(*Result))
66 return std::move(Result);
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())
75 return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
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;
86 if (!IndexedInstrProfReader::hasFormat(*Buffer))
87 return instrprof_error::bad_magic;
88 auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
90 // Initialize the reader and return the result.
91 if (std::error_code EC = initializeReader(*Result))
94 return std::move(Result);
97 void InstrProfIterator::Increment() {
98 if (Reader->readNextRecord(Record))
99 *this = InstrProfIterator();
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();
108 std::all_of(buffer.begin(), buffer.begin() + count,
109 [](char c) { return ::isprint(c) || ::isspace(c); });
113 TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) {
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); \
124 READ_NUM((*Line), (Val)); \
127 if (Line.is_at_end())
129 uint32_t NumValueKinds;
130 if (Line->getAsInteger(10, NumValueKinds)) {
131 // No value profile data
134 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1)
135 return error(instrprof_error::malformed);
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);
146 Record.reserveSites(VK, NumValueSites);
147 for (uint32_t S = 0; S < NumValueSites; S++) {
148 VP_READ_ADVANCE(NumValueData);
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);
159 READ_NUM(VD.first, Value);
161 CurrentValues.push_back({Value, TakenCount});
164 Record.addValueData(VK, S, CurrentValues.data(), NumValueData, nullptr);
169 #undef CHECK_LINE_END
171 #undef VP_READ_ADVANCE
174 std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
175 // Skip empty lines and comments.
176 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
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);
182 // Read the function name.
183 Record.Name = *Line++;
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);
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);
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);
207 if ((Line++)->getAsInteger(10, Count))
208 return error(instrprof_error::malformed);
209 Record.Counts.push_back(Count);
212 // Check if value profile data exists and read it if so.
213 if (std::error_code EC = readValueProfileData(Record))
219 template <class IntPtrT>
220 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
221 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
224 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
225 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
226 sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
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);
241 template <class IntPtrT>
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)
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;
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);
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);
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);
282 auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
283 auto PaddingSize = getNumPaddingBytes(NamesSize);
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;
291 auto *Start = reinterpret_cast<const char *>(&Header);
292 if (Start + ProfileSize > DataBuffer->getBufferEnd())
293 return error(instrprof_error::bad_header);
295 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
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;
303 FunctionPtrToNameMap.clear();
304 for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
305 const IntPtrT FPtr = swap(I->FunctionPointer);
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));
313 std::sort(FunctionPtrToNameMap.begin(), FunctionPtrToNameMap.end(), less_first());
314 FunctionPtrToNameMap.erase(std::unique(FunctionPtrToNameMap.begin(),
315 FunctionPtrToNameMap.end()),
316 FunctionPtrToNameMap.end());
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);
330 template <class IntPtrT>
331 std::error_code RawInstrProfReader<IntPtrT>::readFuncHash(
332 InstrProfRecord &Record) {
333 Record.Hash = swap(Data->FuncHash);
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);
345 auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
346 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
349 if (RawCounts.data() < CountersStart ||
350 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
351 return error(instrprof_error::malformed);
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));
359 Record.Counts = RawCounts;
364 template <class IntPtrT>
366 RawInstrProfReader<IntPtrT>::readValueProfilingData(InstrProfRecord &Record) {
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);
378 ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
379 ValueProfData::getValueProfData(ValueDataStart,
380 (const unsigned char *)ProfileEnd,
381 getDataEndianness());
383 if (VDataPtrOrErr.getError())
384 return VDataPtrOrErr.getError();
386 VDataPtrOrErr.get()->deserializeTo(Record, &FunctionPtrToNameMap);
387 CurValueDataSize = VDataPtrOrErr.get()->getSize();
391 template <class IntPtrT>
393 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
395 if (std::error_code EC = readNextHeader(ProfileEnd))
398 // Read name ad set it in Record.
399 if (std::error_code EC = readName(Record))
402 // Read FuncHash and set it in Record.
403 if (std::error_code EC = readFuncHash(Record))
406 // Read raw counts and set Record.
407 if (std::error_code EC = readRawCounts(Record))
410 // Read value data and set Record.
411 if (std::error_code EC = readValueProfilingData(Record))
420 template class RawInstrProfReader<uint32_t>;
421 template class RawInstrProfReader<uint64_t>;
424 InstrProfLookupTrait::hash_value_type
425 InstrProfLookupTrait::ComputeHash(StringRef K) {
426 return IndexedInstrProf::ComputeHash(HashType, K);
429 typedef InstrProfLookupTrait::data_type data_type;
430 typedef InstrProfLookupTrait::offset_type offset_type;
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);
437 if (VDataPtrOrErr.getError())
440 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), &HashKeys);
441 D += VDataPtrOrErr.get()->TotalSize;
446 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
448 // Check if the data is corrupt. If so, don't try to read it.
449 if (N % sizeof(uint64_t))
453 std::vector<uint64_t> CounterBuffer;
455 using namespace support;
456 const unsigned char *End = D + N;
459 if (D + sizeof(uint64_t) >= End)
461 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
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)
469 CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
471 // Read counter values.
472 if (D + CountsSize * sizeof(uint64_t) > End)
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));
480 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
482 // Read value profiling data.
483 if (FormatVersion > 2 && !readValueProfilingData(D, End)) {
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;
500 return instrprof_error::malformed;
502 return instrprof_error::success;
505 template <typename HashTableImpl>
506 std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
507 ArrayRef<InstrProfRecord> &Data) {
509 return instrprof_error::eof;
511 Data = *RecordIterator;
514 return instrprof_error::malformed;
516 return instrprof_error::success;
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,
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));
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();
541 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
542 if (DataBuffer.getBufferSize() < 8)
544 using namespace support;
546 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
547 // Verify that it's magical.
548 return Magic == IndexedInstrProf::Magic;
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);
558 using namespace support;
560 auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
561 Cur += sizeof(IndexedInstrProf::Header);
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);
569 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
570 if (FormatVersion > IndexedInstrProf::Version)
571 return error(instrprof_error::unsupported_version);
573 // Read the maximal function count.
575 endian::byte_swap<uint64_t, little>(Header->MaxFunctionCount);
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);
583 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
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);
593 ErrorOr<InstrProfRecord>
594 IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
596 ArrayRef<InstrProfRecord> Data;
597 std::error_code EC = Index->getRecords(FuncName, Data);
598 if (EC != instrprof_error::success)
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]);
607 return error(instrprof_error::hash_mismatch);
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())
617 Counts = Record.get().Counts;
621 std::error_code IndexedInstrProfReader::readNextRecord(
622 InstrProfRecord &Record) {
623 static unsigned RecordIndex = 0;
625 ArrayRef<InstrProfRecord> Data;
627 std::error_code EC = Index->getRecords(Data);
628 if (EC != instrprof_error::success)
631 Record = Data[RecordIndex++];
632 if (RecordIndex >= Data.size()) {
633 Index->advanceToNextKey();