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/ProfileData/InstrProf.h"
18 #include "InstrProfIndexed.h"
23 using std::error_code;
25 static error_code setupMemoryBuffer(std::string Path,
26 std::unique_ptr<MemoryBuffer> &Buffer) {
27 if (error_code EC = MemoryBuffer::getFileOrSTDIN(Path, Buffer))
30 // Sanity check the file.
31 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
32 return instrprof_error::too_large;
33 return instrprof_error::success;
36 static error_code initializeReader(InstrProfReader &Reader) {
37 return Reader.readHeader();
40 error_code InstrProfReader::create(std::string Path,
41 std::unique_ptr<InstrProfReader> &Result) {
42 // Set up the buffer to read.
43 std::unique_ptr<MemoryBuffer> Buffer;
44 if (error_code EC = setupMemoryBuffer(Path, Buffer))
48 if (IndexedInstrProfReader::hasFormat(*Buffer))
49 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
50 else if (RawInstrProfReader64::hasFormat(*Buffer))
51 Result.reset(new RawInstrProfReader64(std::move(Buffer)));
52 else if (RawInstrProfReader32::hasFormat(*Buffer))
53 Result.reset(new RawInstrProfReader32(std::move(Buffer)));
55 Result.reset(new TextInstrProfReader(std::move(Buffer)));
57 // Initialize the reader and return the result.
58 return initializeReader(*Result);
61 error_code IndexedInstrProfReader::create(
62 std::string Path, std::unique_ptr<IndexedInstrProfReader> &Result) {
63 // Set up the buffer to read.
64 std::unique_ptr<MemoryBuffer> Buffer;
65 if (error_code EC = setupMemoryBuffer(Path, Buffer))
69 if (!IndexedInstrProfReader::hasFormat(*Buffer))
70 return instrprof_error::bad_magic;
71 Result.reset(new IndexedInstrProfReader(std::move(Buffer)));
73 // Initialize the reader and return the result.
74 return initializeReader(*Result);
77 void InstrProfIterator::Increment() {
78 if (Reader->readNextRecord(Record))
79 *this = InstrProfIterator();
82 error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
84 while (!Line.is_at_end() && Line->empty())
86 // If we hit EOF while looking for a name, we're done.
88 return error(instrprof_error::eof);
90 // Read the function name.
91 Record.Name = *Line++;
93 // Read the function hash.
95 return error(instrprof_error::truncated);
96 if ((Line++)->getAsInteger(10, Record.Hash))
97 return error(instrprof_error::malformed);
99 // Read the number of counters.
100 uint64_t NumCounters;
101 if (Line.is_at_end())
102 return error(instrprof_error::truncated);
103 if ((Line++)->getAsInteger(10, NumCounters))
104 return error(instrprof_error::malformed);
105 if (NumCounters == 0)
106 return error(instrprof_error::malformed);
108 // Read each counter and fill our internal storage with the values.
110 Counts.reserve(NumCounters);
111 for (uint64_t I = 0; I < NumCounters; ++I) {
112 if (Line.is_at_end())
113 return error(instrprof_error::truncated);
115 if ((Line++)->getAsInteger(10, Count))
116 return error(instrprof_error::malformed);
117 Counts.push_back(Count);
119 // Give the record a reference to our internal counter storage.
120 Record.Counts = Counts;
125 template <class IntPtrT>
126 static uint64_t getRawMagic();
129 uint64_t getRawMagic<uint64_t>() {
131 uint64_t(255) << 56 |
132 uint64_t('l') << 48 |
133 uint64_t('p') << 40 |
134 uint64_t('r') << 32 |
135 uint64_t('o') << 24 |
136 uint64_t('f') << 16 |
142 uint64_t getRawMagic<uint32_t>() {
144 uint64_t(255) << 56 |
145 uint64_t('l') << 48 |
146 uint64_t('p') << 40 |
147 uint64_t('r') << 32 |
148 uint64_t('o') << 24 |
149 uint64_t('f') << 16 |
154 template <class IntPtrT>
155 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
156 if (DataBuffer.getBufferSize() < sizeof(uint64_t))
159 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
160 return getRawMagic<IntPtrT>() == Magic ||
161 sys::SwapByteOrder(getRawMagic<IntPtrT>()) == Magic;
164 template <class IntPtrT>
165 error_code RawInstrProfReader<IntPtrT>::readHeader() {
166 if (!hasFormat(*DataBuffer))
167 return error(instrprof_error::bad_magic);
168 if (DataBuffer->getBufferSize() < sizeof(RawHeader))
169 return error(instrprof_error::bad_header);
171 reinterpret_cast<const RawHeader *>(DataBuffer->getBufferStart());
172 ShouldSwapBytes = Header->Magic != getRawMagic<IntPtrT>();
173 return readHeader(*Header);
176 template <class IntPtrT>
177 error_code RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
178 const char *End = DataBuffer->getBufferEnd();
179 // Skip zero padding between profiles.
180 while (CurrentPos != End && *CurrentPos == 0)
182 // If there's nothing left, we're done.
183 if (CurrentPos == End)
184 return instrprof_error::eof;
185 // If there isn't enough space for another header, this is probably just
186 // garbage at the end of the file.
187 if (CurrentPos + sizeof(RawHeader) > End)
188 return instrprof_error::malformed;
189 // The magic should have the same byte order as in the previous header.
190 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
191 if (Magic != swap(getRawMagic<IntPtrT>()))
192 return instrprof_error::bad_magic;
194 // There's another profile to read, so we need to process the header.
195 auto *Header = reinterpret_cast<const RawHeader *>(CurrentPos);
196 return readHeader(*Header);
199 static uint64_t getRawVersion() {
203 template <class IntPtrT>
204 error_code RawInstrProfReader<IntPtrT>::readHeader(const RawHeader &Header) {
205 if (swap(Header.Version) != getRawVersion())
206 return error(instrprof_error::unsupported_version);
208 CountersDelta = swap(Header.CountersDelta);
209 NamesDelta = swap(Header.NamesDelta);
210 auto DataSize = swap(Header.DataSize);
211 auto CountersSize = swap(Header.CountersSize);
212 auto NamesSize = swap(Header.NamesSize);
214 ptrdiff_t DataOffset = sizeof(RawHeader);
215 ptrdiff_t CountersOffset = DataOffset + sizeof(ProfileData) * DataSize;
216 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
217 size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize;
219 auto *Start = reinterpret_cast<const char *>(&Header);
220 if (Start + ProfileSize > DataBuffer->getBufferEnd())
221 return error(instrprof_error::bad_header);
223 Data = reinterpret_cast<const ProfileData *>(Start + DataOffset);
224 DataEnd = Data + DataSize;
225 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
226 NamesStart = Start + NamesOffset;
227 ProfileEnd = Start + ProfileSize;
232 template <class IntPtrT>
234 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
236 if (error_code EC = readNextHeader(ProfileEnd))
240 StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize));
241 uint32_t NumCounters = swap(Data->NumCounters);
242 if (NumCounters == 0)
243 return error(instrprof_error::malformed);
244 auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr), NumCounters);
247 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
248 if (RawName.data() < NamesStart ||
249 RawName.data() + RawName.size() > DataBuffer->getBufferEnd() ||
250 RawCounts.data() < CountersStart ||
251 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
252 return error(instrprof_error::malformed);
254 // Store the data in Record, byte-swapping as necessary.
255 Record.Hash = swap(Data->FuncHash);
256 Record.Name = RawName;
257 if (ShouldSwapBytes) {
259 Counts.reserve(RawCounts.size());
260 for (uint64_t Count : RawCounts)
261 Counts.push_back(swap(Count));
262 Record.Counts = Counts;
264 Record.Counts = RawCounts;
272 template class RawInstrProfReader<uint32_t>;
273 template class RawInstrProfReader<uint64_t>;
276 InstrProfLookupTrait::hash_value_type
277 InstrProfLookupTrait::ComputeHash(StringRef K) {
278 return IndexedInstrProf::ComputeHash(HashType, K);
281 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
282 if (DataBuffer.getBufferSize() < 8)
284 using namespace support;
286 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
287 return Magic == IndexedInstrProf::Magic;
290 error_code IndexedInstrProfReader::readHeader() {
291 const unsigned char *Start =
292 (const unsigned char *)DataBuffer->getBufferStart();
293 const unsigned char *Cur = Start;
294 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
295 return error(instrprof_error::truncated);
297 using namespace support;
299 // Check the magic number.
300 uint64_t Magic = endian::readNext<uint64_t, little, unaligned>(Cur);
301 if (Magic != IndexedInstrProf::Magic)
302 return error(instrprof_error::bad_magic);
305 uint64_t Version = endian::readNext<uint64_t, little, unaligned>(Cur);
306 if (Version != IndexedInstrProf::Version)
307 return error(instrprof_error::unsupported_version);
309 // Read the maximal function count.
310 MaxFunctionCount = endian::readNext<uint64_t, little, unaligned>(Cur);
312 // Read the hash type and start offset.
313 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
314 endian::readNext<uint64_t, little, unaligned>(Cur));
315 if (HashType > IndexedInstrProf::HashT::Last)
316 return error(instrprof_error::unsupported_hash_type);
317 uint64_t HashOffset = endian::readNext<uint64_t, little, unaligned>(Cur);
319 // The rest of the file is an on disk hash table.
320 Index.reset(InstrProfReaderIndex::Create(Start + HashOffset, Cur, Start,
321 InstrProfLookupTrait(HashType)));
322 // Set up our iterator for readNextRecord.
323 RecordIterator = Index->data_begin();
328 error_code IndexedInstrProfReader::getFunctionCounts(
329 StringRef FuncName, uint64_t &FuncHash, std::vector<uint64_t> &Counts) {
330 const auto &Iter = Index->find(FuncName);
331 if (Iter == Index->end())
332 return error(instrprof_error::unknown_function);
334 // Found it. Make sure it's valid before giving back a result.
335 const InstrProfRecord &Record = *Iter;
336 if (Record.Name.empty())
337 return error(instrprof_error::malformed);
338 FuncHash = Record.Hash;
339 Counts = Record.Counts;
343 error_code IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) {
344 // Are we out of records?
345 if (RecordIterator == Index->data_end())
346 return error(instrprof_error::eof);
348 // Read the next one.
349 Record = *RecordIterator;
351 if (Record.Name.empty())
352 return error(instrprof_error::malformed);