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)));
58 Result.reset(new TextInstrProfReader(std::move(Buffer)));
60 // Initialize the reader and return the result.
61 if (std::error_code EC = initializeReader(*Result))
64 return std::move(Result);
67 ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
68 IndexedInstrProfReader::create(std::string Path) {
69 // Set up the buffer to read.
70 auto BufferOrError = setupMemoryBuffer(Path);
71 if (std::error_code EC = BufferOrError.getError())
73 return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
77 ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
78 IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
79 // Sanity check the buffer.
80 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
81 return instrprof_error::too_large;
84 if (!IndexedInstrProfReader::hasFormat(*Buffer))
85 return instrprof_error::bad_magic;
86 auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
88 // Initialize the reader and return the result.
89 if (std::error_code EC = initializeReader(*Result))
92 return std::move(Result);
95 void InstrProfIterator::Increment() {
96 if (Reader->readNextRecord(Record))
97 *this = InstrProfIterator();
100 std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
101 // Skip empty lines and comments.
102 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
104 // If we hit EOF while looking for a name, we're done.
105 if (Line.is_at_end())
106 return error(instrprof_error::eof);
108 // Read the function name.
109 Record.Name = *Line++;
111 // Read the function hash.
112 if (Line.is_at_end())
113 return error(instrprof_error::truncated);
114 if ((Line++)->getAsInteger(0, Record.Hash))
115 return error(instrprof_error::malformed);
117 // Read the number of counters.
118 uint64_t NumCounters;
119 if (Line.is_at_end())
120 return error(instrprof_error::truncated);
121 if ((Line++)->getAsInteger(10, NumCounters))
122 return error(instrprof_error::malformed);
123 if (NumCounters == 0)
124 return error(instrprof_error::malformed);
126 // Read each counter and fill our internal storage with the values.
127 Record.Counts.clear();
128 Record.Counts.reserve(NumCounters);
129 for (uint64_t I = 0; I < NumCounters; ++I) {
130 if (Line.is_at_end())
131 return error(instrprof_error::truncated);
133 if ((Line++)->getAsInteger(10, Count))
134 return error(instrprof_error::malformed);
135 Record.Counts.push_back(Count);
141 template <class IntPtrT>
142 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
143 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
146 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
147 return RawInstrProf::getMagic<IntPtrT>() == Magic ||
148 sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
151 template <class IntPtrT>
152 std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
153 if (!hasFormat(*DataBuffer))
154 return error(instrprof_error::bad_magic);
155 if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
156 return error(instrprof_error::bad_header);
157 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
158 DataBuffer->getBufferStart());
159 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
160 return readHeader(*Header);
163 template <class IntPtrT>
165 RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
166 const char *End = DataBuffer->getBufferEnd();
167 // Skip zero padding between profiles.
168 while (CurrentPos != End && *CurrentPos == 0)
170 // If there's nothing left, we're done.
171 if (CurrentPos == End)
172 return instrprof_error::eof;
173 // If there isn't enough space for another header, this is probably just
174 // garbage at the end of the file.
175 if (CurrentPos + sizeof(RawInstrProf::Header) > End)
176 return instrprof_error::malformed;
177 // The writer ensures each profile is padded to start at an aligned address.
178 if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
179 return instrprof_error::malformed;
180 // The magic should have the same byte order as in the previous header.
181 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
182 if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
183 return instrprof_error::bad_magic;
185 // There's another profile to read, so we need to process the header.
186 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
187 return readHeader(*Header);
190 template <class IntPtrT>
191 std::error_code RawInstrProfReader<IntPtrT>::readHeader(
192 const RawInstrProf::Header &Header) {
193 if (swap(Header.Version) != RawInstrProf::Version)
194 return error(instrprof_error::unsupported_version);
196 CountersDelta = swap(Header.CountersDelta);
197 NamesDelta = swap(Header.NamesDelta);
198 auto DataSize = swap(Header.DataSize);
199 auto CountersSize = swap(Header.CountersSize);
200 auto NamesSize = swap(Header.NamesSize);
202 ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
203 ptrdiff_t CountersOffset =
204 DataOffset + sizeof(RawInstrProf::ProfileData<IntPtrT>) * DataSize;
205 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
206 size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize;
208 auto *Start = reinterpret_cast<const char *>(&Header);
209 if (Start + ProfileSize > DataBuffer->getBufferEnd())
210 return error(instrprof_error::bad_header);
212 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
214 DataEnd = Data + DataSize;
215 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
216 NamesStart = Start + NamesOffset;
217 ProfileEnd = Start + ProfileSize;
222 template <class IntPtrT>
224 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
226 if (std::error_code EC = readNextHeader(ProfileEnd))
230 StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize));
231 uint32_t NumCounters = swap(Data->NumCounters);
232 if (NumCounters == 0)
233 return error(instrprof_error::malformed);
234 auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr), NumCounters);
237 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
238 if (RawName.data() < NamesStart ||
239 RawName.data() + RawName.size() > DataBuffer->getBufferEnd() ||
240 RawCounts.data() < CountersStart ||
241 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
242 return error(instrprof_error::malformed);
244 // Store the data in Record, byte-swapping as necessary.
245 Record.Hash = swap(Data->FuncHash);
246 Record.Name = RawName;
247 if (ShouldSwapBytes) {
248 Record.Counts.clear();
249 Record.Counts.reserve(RawCounts.size());
250 for (uint64_t Count : RawCounts)
251 Record.Counts.push_back(swap(Count));
253 Record.Counts = RawCounts;
261 template class RawInstrProfReader<uint32_t>;
262 template class RawInstrProfReader<uint64_t>;
265 InstrProfLookupTrait::hash_value_type
266 InstrProfLookupTrait::ComputeHash(StringRef K) {
267 return IndexedInstrProf::ComputeHash(HashType, K);
270 typedef InstrProfLookupTrait::data_type data_type;
271 typedef InstrProfLookupTrait::offset_type offset_type;
273 bool InstrProfLookupTrait::ReadValueProfilingData(
274 const unsigned char *&D, const unsigned char *const End) {
276 using namespace support;
277 // Read number of value kinds with value sites.
278 if (D + sizeof(uint64_t) > End)
280 uint64_t ValueKindCount = endian::readNext<uint64_t, little, unaligned>(D);
282 for (uint32_t Kind = 0; Kind < ValueKindCount; ++Kind) {
284 // Read value kind and number of value sites for kind.
285 if (D + 2 * sizeof(uint64_t) > End)
287 uint64_t ValueKind = endian::readNext<uint64_t, little, unaligned>(D);
288 uint64_t ValueSiteCount = endian::readNext<uint64_t, little, unaligned>(D);
290 std::vector<InstrProfValueSiteRecord> &ValueSites =
291 DataBuffer.back().getValueSitesForKind(ValueKind);
292 ValueSites.reserve(ValueSiteCount);
293 for (uint64_t VSite = 0; VSite < ValueSiteCount; ++VSite) {
294 // Read number of value data pairs at value site.
295 if (D + sizeof(uint64_t) > End)
297 uint64_t ValueDataCount =
298 endian::readNext<uint64_t, little, unaligned>(D);
300 // Check if there are as many ValueDataPairs as ValueDataCount in memory.
301 if (D + (ValueDataCount << 1) * sizeof(uint64_t) > End)
304 InstrProfValueSiteRecord VSiteRecord;
305 for (uint64_t VCount = 0; VCount < ValueDataCount; ++VCount) {
306 uint64_t Value = endian::readNext<uint64_t, little, unaligned>(D);
307 uint64_t NumTaken = endian::readNext<uint64_t, little, unaligned>(D);
309 case IPVK_IndirectCallTarget: {
311 std::lower_bound(HashKeys.begin(), HashKeys.end(), Value,
312 [](const std::pair<uint64_t, const char *> &LHS,
313 uint64_t RHS) { return LHS.first < RHS; });
314 assert(Result != HashKeys.end() &&
315 "Hash does not match any known keys\n");
316 Value = (uint64_t)Result->second;
320 VSiteRecord.ValueData.push_back(std::make_pair(Value, NumTaken));
322 ValueSites.push_back(std::move(VSiteRecord));
328 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
330 // Check if the data is corrupt. If so, don't try to read it.
331 if (N % sizeof(uint64_t))
335 std::vector<uint64_t> CounterBuffer;
337 using namespace support;
338 const unsigned char *End = D + N;
341 if (D + sizeof(uint64_t) >= End)
343 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
345 // Initialize number of counters for FormatVersion == 1.
346 uint64_t CountsSize = N / sizeof(uint64_t) - 1;
347 // If format version is different then read the number of counters.
348 if (FormatVersion != 1) {
349 if (D + sizeof(uint64_t) > End)
351 CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
353 // Read counter values.
354 if (D + CountsSize * sizeof(uint64_t) > End)
357 CounterBuffer.clear();
358 CounterBuffer.reserve(CountsSize);
359 for (uint64_t J = 0; J < CountsSize; ++J)
360 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
362 DataBuffer.push_back(InstrProfRecord(K, Hash, std::move(CounterBuffer)));
364 // Read value profiling data.
365 if (FormatVersion > 2 && !ReadValueProfilingData(D, End)) {
373 std::error_code InstrProfReaderIndex::getRecords(
374 StringRef FuncName, ArrayRef<InstrProfRecord> &Data) {
375 auto Iter = Index->find(FuncName);
376 if (Iter == Index->end()) return instrprof_error::unknown_function;
379 if (Data.empty()) return instrprof_error::malformed;
381 return instrprof_error::success;
384 std::error_code InstrProfReaderIndex::getRecords(
385 ArrayRef<InstrProfRecord> &Data) {
386 if (atEnd()) return instrprof_error::eof;
388 Data = *RecordIterator;
390 if (Data.empty()) return instrprof_error::malformed;
392 return instrprof_error::success;
395 void InstrProfReaderIndex::Init(const unsigned char *Buckets,
396 const unsigned char *const Payload,
397 const unsigned char *const Base,
398 IndexedInstrProf::HashT HashType,
400 FormatVersion = Version;
401 Index.reset(IndexType::Create(Buckets, Payload, Base,
402 InstrProfLookupTrait(HashType, Version)));
403 // Form the map of hash values to const char* keys in profiling data.
404 std::vector<std::pair<uint64_t, const char *>> HashKeys;
405 for (auto Key : Index->keys()) {
406 const char *KeyTableRef = StringTable.insertString(Key);
407 HashKeys.push_back(std::make_pair(ComputeHash(HashType, Key), KeyTableRef));
409 std::sort(HashKeys.begin(), HashKeys.end(), less_first());
410 HashKeys.erase(std::unique(HashKeys.begin(), HashKeys.end()), HashKeys.end());
411 // Set the hash key map for the InstrLookupTrait
412 Index->getInfoObj().setHashKeys(std::move(HashKeys));
413 RecordIterator = Index->data_begin();
416 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
417 if (DataBuffer.getBufferSize() < 8) return false;
418 using namespace support;
420 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
421 // Verify that it's magical.
422 return Magic == IndexedInstrProf::Magic;
425 std::error_code IndexedInstrProfReader::readHeader() {
426 const unsigned char *Start =
427 (const unsigned char *)DataBuffer->getBufferStart();
428 const unsigned char *Cur = Start;
429 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
430 return error(instrprof_error::truncated);
432 using namespace support;
434 auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
435 Cur += sizeof(IndexedInstrProf::Header);
437 // Check the magic number.
438 uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
439 if (Magic != IndexedInstrProf::Magic)
440 return error(instrprof_error::bad_magic);
443 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
444 if (FormatVersion > IndexedInstrProf::Version)
445 return error(instrprof_error::unsupported_version);
447 // Read the maximal function count.
449 endian::byte_swap<uint64_t, little>(Header->MaxFunctionCount);
451 // Read the hash type and start offset.
452 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
453 endian::byte_swap<uint64_t, little>(Header->HashType));
454 if (HashType > IndexedInstrProf::HashT::Last)
455 return error(instrprof_error::unsupported_hash_type);
457 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
459 // The rest of the file is an on disk hash table.
460 Index.Init(Start + HashOffset, Cur, Start, HashType, FormatVersion);
465 std::error_code IndexedInstrProfReader::getFunctionCounts(
466 StringRef FuncName, uint64_t FuncHash, std::vector<uint64_t> &Counts) {
467 ArrayRef<InstrProfRecord> Data;
469 std::error_code EC = Index.getRecords(FuncName, Data);
470 if (EC != instrprof_error::success) return EC;
472 // Found it. Look for counters with the right hash.
473 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
474 // Check for a match and fill the vector if there is one.
475 if (Data[I].Hash == FuncHash) {
476 Counts = Data[I].Counts;
480 return error(instrprof_error::hash_mismatch);
483 std::error_code IndexedInstrProfReader::readNextRecord(
484 InstrProfRecord &Record) {
485 static unsigned RecordIndex = 0;
487 ArrayRef<InstrProfRecord> Data;
489 std::error_code EC = Index.getRecords(Data);
490 if (EC != instrprof_error::success) return error(EC);
492 Record = Data[RecordIndex++];
493 if (RecordIndex >= Data.size()) {
494 Index.advanceToNextKey();