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"
24 static std::error_code
25 setupMemoryBuffer(std::string Path, std::unique_ptr<MemoryBuffer> &Buffer) {
26 if (std::error_code EC = MemoryBuffer::getFileOrSTDIN(Path, Buffer))
29 // Sanity check the file.
30 if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
31 return instrprof_error::too_large;
32 return instrprof_error::success;
35 static std::error_code initializeReader(InstrProfReader &Reader) {
36 return Reader.readHeader();
40 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 (std::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 std::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 (std::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 std::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 std::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>
178 RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
179 const char *End = DataBuffer->getBufferEnd();
180 // Skip zero padding between profiles.
181 while (CurrentPos != End && *CurrentPos == 0)
183 // If there's nothing left, we're done.
184 if (CurrentPos == End)
185 return instrprof_error::eof;
186 // If there isn't enough space for another header, this is probably just
187 // garbage at the end of the file.
188 if (CurrentPos + sizeof(RawHeader) > End)
189 return instrprof_error::malformed;
190 // The magic should have the same byte order as in the previous header.
191 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
192 if (Magic != swap(getRawMagic<IntPtrT>()))
193 return instrprof_error::bad_magic;
195 // There's another profile to read, so we need to process the header.
196 auto *Header = reinterpret_cast<const RawHeader *>(CurrentPos);
197 return readHeader(*Header);
200 static uint64_t getRawVersion() {
204 template <class IntPtrT>
206 RawInstrProfReader<IntPtrT>::readHeader(const RawHeader &Header) {
207 if (swap(Header.Version) != getRawVersion())
208 return error(instrprof_error::unsupported_version);
210 CountersDelta = swap(Header.CountersDelta);
211 NamesDelta = swap(Header.NamesDelta);
212 auto DataSize = swap(Header.DataSize);
213 auto CountersSize = swap(Header.CountersSize);
214 auto NamesSize = swap(Header.NamesSize);
216 ptrdiff_t DataOffset = sizeof(RawHeader);
217 ptrdiff_t CountersOffset = DataOffset + sizeof(ProfileData) * DataSize;
218 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
219 size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize;
221 auto *Start = reinterpret_cast<const char *>(&Header);
222 if (Start + ProfileSize > DataBuffer->getBufferEnd())
223 return error(instrprof_error::bad_header);
225 Data = reinterpret_cast<const ProfileData *>(Start + DataOffset);
226 DataEnd = Data + DataSize;
227 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
228 NamesStart = Start + NamesOffset;
229 ProfileEnd = Start + ProfileSize;
234 template <class IntPtrT>
236 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
238 if (std::error_code EC = readNextHeader(ProfileEnd))
242 StringRef RawName(getName(Data->NamePtr), swap(Data->NameSize));
243 uint32_t NumCounters = swap(Data->NumCounters);
244 if (NumCounters == 0)
245 return error(instrprof_error::malformed);
246 auto RawCounts = makeArrayRef(getCounter(Data->CounterPtr), NumCounters);
249 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
250 if (RawName.data() < NamesStart ||
251 RawName.data() + RawName.size() > DataBuffer->getBufferEnd() ||
252 RawCounts.data() < CountersStart ||
253 RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
254 return error(instrprof_error::malformed);
256 // Store the data in Record, byte-swapping as necessary.
257 Record.Hash = swap(Data->FuncHash);
258 Record.Name = RawName;
259 if (ShouldSwapBytes) {
261 Counts.reserve(RawCounts.size());
262 for (uint64_t Count : RawCounts)
263 Counts.push_back(swap(Count));
264 Record.Counts = Counts;
266 Record.Counts = RawCounts;
274 template class RawInstrProfReader<uint32_t>;
275 template class RawInstrProfReader<uint64_t>;
278 InstrProfLookupTrait::hash_value_type
279 InstrProfLookupTrait::ComputeHash(StringRef K) {
280 return IndexedInstrProf::ComputeHash(HashType, K);
283 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
284 if (DataBuffer.getBufferSize() < 8)
286 using namespace support;
288 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
289 return Magic == IndexedInstrProf::Magic;
292 std::error_code IndexedInstrProfReader::readHeader() {
293 const unsigned char *Start =
294 (const unsigned char *)DataBuffer->getBufferStart();
295 const unsigned char *Cur = Start;
296 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
297 return error(instrprof_error::truncated);
299 using namespace support;
301 // Check the magic number.
302 uint64_t Magic = endian::readNext<uint64_t, little, unaligned>(Cur);
303 if (Magic != IndexedInstrProf::Magic)
304 return error(instrprof_error::bad_magic);
307 uint64_t Version = endian::readNext<uint64_t, little, unaligned>(Cur);
308 if (Version != IndexedInstrProf::Version)
309 return error(instrprof_error::unsupported_version);
311 // Read the maximal function count.
312 MaxFunctionCount = endian::readNext<uint64_t, little, unaligned>(Cur);
314 // Read the hash type and start offset.
315 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
316 endian::readNext<uint64_t, little, unaligned>(Cur));
317 if (HashType > IndexedInstrProf::HashT::Last)
318 return error(instrprof_error::unsupported_hash_type);
319 uint64_t HashOffset = endian::readNext<uint64_t, little, unaligned>(Cur);
321 // The rest of the file is an on disk hash table.
322 Index.reset(InstrProfReaderIndex::Create(Start + HashOffset, Cur, Start,
323 InstrProfLookupTrait(HashType)));
324 // Set up our iterator for readNextRecord.
325 RecordIterator = Index->data_begin();
330 std::error_code IndexedInstrProfReader::getFunctionCounts(
331 StringRef FuncName, uint64_t &FuncHash, std::vector<uint64_t> &Counts) {
332 const auto &Iter = Index->find(FuncName);
333 if (Iter == Index->end())
334 return error(instrprof_error::unknown_function);
336 // Found it. Make sure it's valid before giving back a result.
337 const InstrProfRecord &Record = *Iter;
338 if (Record.Name.empty())
339 return error(instrprof_error::malformed);
340 FuncHash = Record.Hash;
341 Counts = Record.Counts;
346 IndexedInstrProfReader::readNextRecord(InstrProfRecord &Record) {
347 // Are we out of records?
348 if (RecordIterator == Index->data_end())
349 return error(instrprof_error::eof);
351 // Read the next one.
352 Record = *RecordIterator;
354 if (Record.Name.empty())
355 return error(instrprof_error::malformed);