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 "InstrProfIndexed.h"
17 #include "llvm/ProfileData/InstrProf.h"
22 static ErrorOr<std::unique_ptr<MemoryBuffer>>
23 setupMemoryBuffer(std::string Path) {
24 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
25 MemoryBuffer::getFileOrSTDIN(Path);
26 if (std::error_code EC = BufferOrErr.getError())
28 return std::move(BufferOrErr.get());
31 static std::error_code initializeReader(InstrProfReader &Reader) {
32 return Reader.readHeader();
35 ErrorOr<std::unique_ptr<InstrProfReader>>
36 InstrProfReader::create(std::string Path) {
37 // Set up the buffer to read.
38 auto BufferOrError = setupMemoryBuffer(Path);
39 if (std::error_code EC = BufferOrError.getError())
41 return InstrProfReader::create(std::move(BufferOrError.get()));
44 ErrorOr<std::unique_ptr<InstrProfReader>>
45 InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
46 // Sanity check the buffer.
47 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
48 return instrprof_error::too_large;
50 std::unique_ptr<InstrProfReader> Result;
52 if (IndexedInstrProfReader::hasFormat(*Buffer))
53 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
54 else if (RawInstrProfReader64::hasFormat(*Buffer))
55 Result.reset(new RawInstrProfReader64(std::move(Buffer)));
56 else if (RawInstrProfReader32::hasFormat(*Buffer))
57 Result.reset(new RawInstrProfReader32(std::move(Buffer)));
59 Result.reset(new TextInstrProfReader(std::move(Buffer)));
61 // Initialize the reader and return the result.
62 if (std::error_code EC = initializeReader(*Result))
65 return std::move(Result);
68 ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
69 IndexedInstrProfReader::create(std::string Path) {
70 // Set up the buffer to read.
71 auto BufferOrError = setupMemoryBuffer(Path);
72 if (std::error_code EC = BufferOrError.getError())
74 return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
78 ErrorOr<std::unique_ptr<IndexedInstrProfReader>>
79 IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer) {
80 // Sanity check the buffer.
81 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
82 return instrprof_error::too_large;
85 if (!IndexedInstrProfReader::hasFormat(*Buffer))
86 return instrprof_error::bad_magic;
87 auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
89 // Initialize the reader and return the result.
90 if (std::error_code EC = initializeReader(*Result))
93 return std::move(Result);
96 void InstrProfIterator::Increment() {
97 if (Reader->readNextRecord(Record))
98 *this = InstrProfIterator();
101 std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
102 // Skip empty lines and comments.
103 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
105 // If we hit EOF while looking for a name, we're done.
106 if (Line.is_at_end())
107 return error(instrprof_error::eof);
109 // Read the function name.
110 Record.Name = *Line++;
112 // Read the function hash.
113 if (Line.is_at_end())
114 return error(instrprof_error::truncated);
115 if ((Line++)->getAsInteger(10, Record.Hash))
116 return error(instrprof_error::malformed);
118 // Read the number of counters.
119 uint64_t NumCounters;
120 if (Line.is_at_end())
121 return error(instrprof_error::truncated);
122 if ((Line++)->getAsInteger(10, NumCounters))
123 return error(instrprof_error::malformed);
124 if (NumCounters == 0)
125 return error(instrprof_error::malformed);
127 // Read each counter and fill our internal storage with the values.
129 Counts.reserve(NumCounters);
130 for (uint64_t I = 0; I < NumCounters; ++I) {
131 if (Line.is_at_end())
132 return error(instrprof_error::truncated);
134 if ((Line++)->getAsInteger(10, Count))
135 return error(instrprof_error::malformed);
136 Counts.push_back(Count);
138 // Give the record a reference to our internal counter storage.
139 Record.Counts = Counts;
144 template <class IntPtrT>
145 static uint64_t getRawMagic();
148 uint64_t getRawMagic<uint64_t>() {
150 uint64_t(255) << 56 |
151 uint64_t('l') << 48 |
152 uint64_t('p') << 40 |
153 uint64_t('r') << 32 |
154 uint64_t('o') << 24 |
155 uint64_t('f') << 16 |
161 uint64_t getRawMagic<uint32_t>() {
163 uint64_t(255) << 56 |
164 uint64_t('l') << 48 |
165 uint64_t('p') << 40 |
166 uint64_t('r') << 32 |
167 uint64_t('o') << 24 |
168 uint64_t('f') << 16 |
173 template <class IntPtrT>
174 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
175 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
178 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
179 return getRawMagic<IntPtrT>() == Magic ||
180 sys::getSwappedBytes(getRawMagic<IntPtrT>()) == Magic;
183 template <class IntPtrT>
184 std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
185 if (!hasFormat(*DataBuffer))
186 return error(instrprof_error::bad_magic);
187 if (DataBuffer->getBufferSize() < sizeof(RawHeader))
188 return error(instrprof_error::bad_header);
190 reinterpret_cast<const RawHeader *>(DataBuffer->getBufferStart());
191 ShouldSwapBytes = Header->Magic != getRawMagic<IntPtrT>();
192 return readHeader(*Header);
195 template <class IntPtrT>
197 RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
198 const char *End = DataBuffer->getBufferEnd();
199 // Skip zero padding between profiles.
200 while (CurrentPos != End && *CurrentPos == 0)
202 // If there's nothing left, we're done.
203 if (CurrentPos == End)
204 return instrprof_error::eof;
205 // If there isn't enough space for another header, this is probably just
206 // garbage at the end of the file.
207 if (CurrentPos + sizeof(RawHeader) > End)
208 return instrprof_error::malformed;
209 // The writer ensures each profile is padded to start at an aligned address.
210 if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
211 return instrprof_error::malformed;
212 // The magic should have the same byte order as in the previous header.
213 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
214 if (Magic != swap(getRawMagic<IntPtrT>()))
215 return instrprof_error::bad_magic;
217 // There's another profile to read, so we need to process the header.
218 auto *Header = reinterpret_cast<const RawHeader *>(CurrentPos);
219 return readHeader(*Header);
222 static uint64_t getRawVersion() {
226 template <class IntPtrT>
228 RawInstrProfReader<IntPtrT>::readHeader(const RawHeader &Header) {
229 if (swap(Header.Version) != getRawVersion())
230 return error(instrprof_error::unsupported_version);
232 CountersDelta = swap(Header.CountersDelta);
233 NamesDelta = swap(Header.NamesDelta);
234 auto DataSize = swap(Header.DataSize);
235 auto CountersSize = swap(Header.CountersSize);
236 auto NamesSize = swap(Header.NamesSize);
238 ptrdiff_t DataOffset = sizeof(RawHeader);
239 ptrdiff_t CountersOffset = DataOffset + sizeof(ProfileData) * DataSize;
240 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
241 size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize;
243 auto *Start = reinterpret_cast<const char *>(&Header);
244 if (Start + ProfileSize > DataBuffer->getBufferEnd())
245 return error(instrprof_error::bad_header);
247 Data = reinterpret_cast<const ProfileData *>(Start + DataOffset);
248 DataEnd = Data + DataSize;
249 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
250 NamesStart = Start + NamesOffset;
251 ProfileEnd = Start + ProfileSize;
256 template <class IntPtrT>
258 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
260 if (std::error_code EC = readNextHeader(ProfileEnd))
264 StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize));
265 uint32_t NumCounters = swap(Data->NumCounters);
266 if (NumCounters == 0)
267 return error(instrprof_error::malformed);
268 auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr), NumCounters);
271 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
272 if (RawName.data() < NamesStart ||
273 RawName.data() + RawName.size() > DataBuffer->getBufferEnd() ||
274 RawCounts.data() < CountersStart ||
275 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
276 return error(instrprof_error::malformed);
278 // Store the data in Record, byte-swapping as necessary.
279 Record.Hash = swap(Data->FuncHash);
280 Record.Name = RawName;
281 if (ShouldSwapBytes) {
283 Counts.reserve(RawCounts.size());
284 for (uint64_t Count : RawCounts)
285 Counts.push_back(swap(Count));
286 Record.Counts = Counts;
288 Record.Counts = RawCounts;
296 template class RawInstrProfReader<uint32_t>;
297 template class RawInstrProfReader<uint64_t>;
300 InstrProfLookupTrait::hash_value_type
301 InstrProfLookupTrait::ComputeHash(StringRef K) {
302 return IndexedInstrProf::ComputeHash(HashType, K);
305 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
306 if (DataBuffer.getBufferSize() < 8)
308 using namespace support;
310 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
311 return Magic == IndexedInstrProf::Magic;
314 std::error_code IndexedInstrProfReader::readHeader() {
315 const unsigned char *Start =
316 (const unsigned char *)DataBuffer->getBufferStart();
317 const unsigned char *Cur = Start;
318 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
319 return error(instrprof_error::truncated);
321 using namespace support;
323 // Check the magic number.
324 uint64_t Magic = endian::readNext<uint64_t, little, unaligned>(Cur);
325 if (Magic != IndexedInstrProf::Magic)
326 return error(instrprof_error::bad_magic);
329 FormatVersion = endian::readNext<uint64_t, little, unaligned>(Cur);
330 if (FormatVersion > IndexedInstrProf::Version)
331 return error(instrprof_error::unsupported_version);
333 // Read the maximal function count.
334 MaxFunctionCount = endian::readNext<uint64_t, little, unaligned>(Cur);
336 // Read the hash type and start offset.
337 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
338 endian::readNext<uint64_t, little, unaligned>(Cur));
339 if (HashType > IndexedInstrProf::HashT::Last)
340 return error(instrprof_error::unsupported_hash_type);
341 uint64_t HashOffset = endian::readNext<uint64_t, little, unaligned>(Cur);
343 // The rest of the file is an on disk hash table.
344 Index.reset(InstrProfReaderIndex::Create(Start + HashOffset, Cur, Start,
345 InstrProfLookupTrait(HashType)));
346 // Set up our iterator for readNextRecord.
347 RecordIterator = Index->data_begin();
352 std::error_code IndexedInstrProfReader::getFunctionCounts(
353 StringRef FuncName, uint64_t FuncHash, std::vector<uint64_t> &Counts) {
354 auto Iter = Index->find(FuncName);
355 if (Iter == Index->end())
356 return error(instrprof_error::unknown_function);
358 // Found it. Look for counters with the right hash.
359 ArrayRef<uint64_t> Data = (*Iter).Data;
361 for (uint64_t I = 0, E = Data.size(); I != E; I += NumCounts) {
362 // The function hash comes first.
363 uint64_t FoundHash = Data[I++];
364 // In v1, we have at least one count. Later, we have the number of counts.
366 return error(instrprof_error::malformed);
367 NumCounts = FormatVersion == 1 ? E - I : Data[I++];
368 // If we have more counts than data, this is bogus.
369 if (I + NumCounts > E)
370 return error(instrprof_error::malformed);
371 // Check for a match and fill the vector if there is one.
372 if (FoundHash == FuncHash) {
373 Counts = Data.slice(I, NumCounts);
377 return error(instrprof_error::hash_mismatch);
381 IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) {
382 // Are we out of records?
383 if (RecordIterator == Index->data_end())
384 return error(instrprof_error::eof);
386 // Record the current function name.
387 Record.Name = (*RecordIterator).Name;
389 ArrayRef<uint64_t> Data = (*RecordIterator).Data;
390 // Valid data starts with a hash and either a count or the number of counts.
391 if (CurrentOffset + 1 > Data.size())
392 return error(instrprof_error::malformed);
393 // First we have a function hash.
394 Record.Hash = Data[CurrentOffset++];
395 // In version 1 we knew the number of counters implicitly, but in newer
396 // versions we store the number of counters next.
398 FormatVersion == 1 ? Data.size() - CurrentOffset : Data[CurrentOffset++];
399 if (CurrentOffset + NumCounts > Data.size())
400 return error(instrprof_error::malformed);
401 // And finally the counts themselves.
402 Record.Counts = Data.slice(CurrentOffset, NumCounts);
404 // If we've exhausted this function's data, increment the record.
405 CurrentOffset += NumCounts;
406 if (CurrentOffset == Data.size()) {