10b8fa781d7369d12a7c78747809bc732c0c4501
[oota-llvm.git] / lib / ProfileData / InstrProfReader.cpp
1 //=-- InstrProfReader.cpp - Instrumented profiling reader -------------------=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for reading profiling data for clang's
11 // instrumentation based PGO and coverage.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ProfileData/InstrProfReader.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include <cassert>
18
19 using namespace llvm;
20
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())
26     return EC;
27   return std::move(BufferOrErr.get());
28 }
29
30 static std::error_code initializeReader(InstrProfReader &Reader) {
31   return Reader.readHeader();
32 }
33
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())
39     return EC;
40   return InstrProfReader::create(std::move(BufferOrError.get()));
41 }
42
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;
48
49   std::unique_ptr<InstrProfReader> Result;
50   // Create the reader.
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)));
59   else
60     return instrprof_error::unrecognized_format;
61
62   // Initialize the reader and return the result.
63   if (std::error_code EC = initializeReader(*Result))
64     return EC;
65
66   return std::move(Result);
67 }
68
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())
74     return EC;
75   return IndexedInstrProfReader::create(std::move(BufferOrError.get()));
76 }
77
78
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;
84
85   // Create the reader.
86   if (!IndexedInstrProfReader::hasFormat(*Buffer))
87     return instrprof_error::bad_magic;
88   auto Result = llvm::make_unique<IndexedInstrProfReader>(std::move(Buffer));
89
90   // Initialize the reader and return the result.
91   if (std::error_code EC = initializeReader(*Result))
92     return EC;
93
94   return std::move(Result);
95 }
96
97 void InstrProfIterator::Increment() {
98   if (Reader->readNextRecord(Record))
99     *this = InstrProfIterator();
100 }
101
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();
107   return count == 0 || std::all_of(buffer.begin(), buffer.begin() + count,
108     [](char c) { return ::isprint(c) || ::isspace(c); });
109 }
110
111 std::error_code TextInstrProfReader::readNextRecord(InstrProfRecord &Record) {
112   // Skip empty lines and comments.
113   while (!Line.is_at_end() && (Line->empty() || Line->startswith("#")))
114     ++Line;
115   // If we hit EOF while looking for a name, we're done.
116   if (Line.is_at_end())
117     return error(instrprof_error::eof);
118
119   // Read the function name.
120   Record.Name = *Line++;
121
122   // Read the function hash.
123   if (Line.is_at_end())
124     return error(instrprof_error::truncated);
125   if ((Line++)->getAsInteger(0, Record.Hash))
126     return error(instrprof_error::malformed);
127
128   // Read the number of counters.
129   uint64_t NumCounters;
130   if (Line.is_at_end())
131     return error(instrprof_error::truncated);
132   if ((Line++)->getAsInteger(10, NumCounters))
133     return error(instrprof_error::malformed);
134   if (NumCounters == 0)
135     return error(instrprof_error::malformed);
136
137   // Read each counter and fill our internal storage with the values.
138   Record.Counts.clear();
139   Record.Counts.reserve(NumCounters);
140   for (uint64_t I = 0; I < NumCounters; ++I) {
141     if (Line.is_at_end())
142       return error(instrprof_error::truncated);
143     uint64_t Count;
144     if ((Line++)->getAsInteger(10, Count))
145       return error(instrprof_error::malformed);
146     Record.Counts.push_back(Count);
147   }
148
149   return success();
150 }
151
152 template <class IntPtrT>
153 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) {
154   if (DataBuffer.getBufferSize() < sizeof(uint64_t))
155     return false;
156   uint64_t Magic =
157     *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart());
158   return RawInstrProf::getMagic<IntPtrT>() == Magic ||
159          sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic;
160 }
161
162 template <class IntPtrT>
163 std::error_code RawInstrProfReader<IntPtrT>::readHeader() {
164   if (!hasFormat(*DataBuffer))
165     return error(instrprof_error::bad_magic);
166   if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header))
167     return error(instrprof_error::bad_header);
168   auto *Header = reinterpret_cast<const RawInstrProf::Header *>(
169       DataBuffer->getBufferStart());
170   ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>();
171   return readHeader(*Header);
172 }
173
174 template <class IntPtrT>
175 std::error_code
176 RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) {
177   const char *End = DataBuffer->getBufferEnd();
178   // Skip zero padding between profiles.
179   while (CurrentPos != End && *CurrentPos == 0)
180     ++CurrentPos;
181   // If there's nothing left, we're done.
182   if (CurrentPos == End)
183     return instrprof_error::eof;
184   // If there isn't enough space for another header, this is probably just
185   // garbage at the end of the file.
186   if (CurrentPos + sizeof(RawInstrProf::Header) > End)
187     return instrprof_error::malformed;
188   // The writer ensures each profile is padded to start at an aligned address.
189   if (reinterpret_cast<size_t>(CurrentPos) % alignOf<uint64_t>())
190     return instrprof_error::malformed;
191   // The magic should have the same byte order as in the previous header.
192   uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos);
193   if (Magic != swap(RawInstrProf::getMagic<IntPtrT>()))
194     return instrprof_error::bad_magic;
195
196   // There's another profile to read, so we need to process the header.
197   auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos);
198   return readHeader(*Header);
199 }
200
201 template <class IntPtrT>
202 std::error_code RawInstrProfReader<IntPtrT>::readHeader(
203     const RawInstrProf::Header &Header) {
204   if (swap(Header.Version) != RawInstrProf::Version)
205     return error(instrprof_error::unsupported_version);
206
207   CountersDelta = swap(Header.CountersDelta);
208   NamesDelta = swap(Header.NamesDelta);
209   ValueDataDelta = swap(Header.ValueDataDelta);
210   auto DataSize = swap(Header.DataSize);
211   auto CountersSize = swap(Header.CountersSize);
212   auto NamesSize = swap(Header.NamesSize);
213   auto ValueDataSize = swap(Header.ValueDataSize);
214   ValueKindLast = swap(Header.ValueKindLast);
215
216   auto DataSizeInBytes = DataSize * sizeof(RawInstrProf::ProfileData<IntPtrT>);
217   auto PaddingSize = getNumPaddingBytes(NamesSize);
218
219   ptrdiff_t DataOffset = sizeof(RawInstrProf::Header);
220   ptrdiff_t CountersOffset = DataOffset + DataSizeInBytes;
221   ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize;
222   ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize;
223   size_t ProfileSize = ValueDataOffset + ValueDataSize;
224
225   auto *Start = reinterpret_cast<const char *>(&Header);
226   if (Start + ProfileSize > DataBuffer->getBufferEnd())
227     return error(instrprof_error::bad_header);
228
229   Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>(
230       Start + DataOffset);
231   DataEnd = Data + DataSize;
232   CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset);
233   NamesStart = Start + NamesOffset;
234   ValueDataStart = reinterpret_cast<const uint8_t*>(Start + ValueDataOffset);
235   ProfileEnd = Start + ProfileSize;
236
237   FunctionPtrToNameMap.clear();
238   for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) {
239     const IntPtrT FPtr = swap(I->FunctionPointer);
240     if (!FPtr)
241       continue;
242     StringRef FunctionName(getName(I->NamePtr), swap(I->NameSize));
243     const char* NameEntryPtr = StringTable.insertString(FunctionName);
244     FunctionPtrToNameMap.push_back(std::pair<const IntPtrT, const char*>
245                                    (FPtr, NameEntryPtr));
246   }
247   std::sort(FunctionPtrToNameMap.begin(), FunctionPtrToNameMap.end(), less_first());
248   FunctionPtrToNameMap.erase(std::unique(FunctionPtrToNameMap.begin(),
249                                          FunctionPtrToNameMap.end()),
250                                          FunctionPtrToNameMap.end());
251   return success();
252 }
253
254 template <class IntPtrT>
255 std::error_code RawInstrProfReader<IntPtrT>::readName(InstrProfRecord &Record) {
256   Record.Name = StringRef(getName(Data->NamePtr), swap(Data->NameSize));
257   if (Record.Name.data() < NamesStart ||
258       Record.Name.data() + Record.Name.size() >
259           reinterpret_cast<const char *>(ValueDataStart))
260     return error(instrprof_error::malformed);
261   return success();
262 }
263
264 template <class IntPtrT>
265 std::error_code RawInstrProfReader<IntPtrT>::readFuncHash(
266     InstrProfRecord &Record) {
267   Record.Hash = swap(Data->FuncHash);
268   return success();
269 }
270
271 template <class IntPtrT>
272 std::error_code RawInstrProfReader<IntPtrT>::readRawCounts(
273     InstrProfRecord &Record) {
274   uint32_t NumCounters = swap(Data->NumCounters);
275   IntPtrT CounterPtr = Data->CounterPtr;
276   if (NumCounters == 0)
277     return error(instrprof_error::malformed);
278
279   auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters);
280   auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart);
281
282   // Check bounds.
283   if (RawCounts.data() < CountersStart ||
284       RawCounts.data() + RawCounts.size() > NamesStartAsCounter)
285     return error(instrprof_error::malformed);
286
287   if (ShouldSwapBytes) {
288     Record.Counts.clear();
289     Record.Counts.reserve(RawCounts.size());
290     for (uint64_t Count : RawCounts)
291       Record.Counts.push_back(swap(Count));
292   } else
293     Record.Counts = RawCounts;
294
295   return success();
296 }
297
298 template <class IntPtrT>
299 std::error_code
300 RawInstrProfReader<IntPtrT>::readValueProfilingData(InstrProfRecord &Record) {
301
302   Record.clearValueData();
303   if (!Data->Values || (ValueDataDelta == 0))
304     return success();
305
306   ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
307       ValueProfData::getValueProfData(getValueDataCounts(Data->Values),
308                                       (const unsigned char *)ProfileEnd,
309                                       getDataEndianness());
310
311   if (VDataPtrOrErr.getError())
312     return VDataPtrOrErr.getError();
313
314   VDataPtrOrErr.get()->deserializeTo(Record, &FunctionPtrToNameMap);
315   return success();
316 }
317
318 template <class IntPtrT>
319 std::error_code
320 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) {
321   if (atEnd())
322     if (std::error_code EC = readNextHeader(ProfileEnd))
323       return EC;
324
325   // Read name ad set it in Record.
326   if (std::error_code EC = readName(Record))
327     return EC;
328
329   // Read FuncHash and set it in Record.
330   if (std::error_code EC = readFuncHash(Record))
331     return EC;
332
333   // Read raw counts and set Record.
334   if (std::error_code EC = readRawCounts(Record))
335     return EC;
336
337   // Read value data and set Record.
338   if (std::error_code EC = readValueProfilingData(Record))
339     return EC;
340
341   // Iterate.
342   advanceData();
343   return success();
344 }
345
346 namespace llvm {
347 template class RawInstrProfReader<uint32_t>;
348 template class RawInstrProfReader<uint64_t>;
349 }
350
351 InstrProfLookupTrait::hash_value_type
352 InstrProfLookupTrait::ComputeHash(StringRef K) {
353   return IndexedInstrProf::ComputeHash(HashType, K);
354 }
355
356 typedef InstrProfLookupTrait::data_type data_type;
357 typedef InstrProfLookupTrait::offset_type offset_type;
358
359 bool InstrProfLookupTrait::readValueProfilingData(
360     const unsigned char *&D, const unsigned char *const End) {
361   ErrorOr<std::unique_ptr<ValueProfData>> VDataPtrOrErr =
362       ValueProfData::getValueProfData(D, End, ValueProfDataEndianness);
363
364   if (VDataPtrOrErr.getError())
365     return false;
366
367   VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), &HashKeys);
368   D += VDataPtrOrErr.get()->TotalSize;
369
370   return true;
371 }
372
373 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D,
374                                          offset_type N) {
375   // Check if the data is corrupt. If so, don't try to read it.
376   if (N % sizeof(uint64_t))
377     return data_type();
378
379   DataBuffer.clear();
380   std::vector<uint64_t> CounterBuffer;
381
382   using namespace support;
383   const unsigned char *End = D + N;
384   while (D < End) {
385     // Read hash.
386     if (D + sizeof(uint64_t) >= End)
387       return data_type();
388     uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D);
389
390     // Initialize number of counters for FormatVersion == 1.
391     uint64_t CountsSize = N / sizeof(uint64_t) - 1;
392     // If format version is different then read the number of counters.
393     if (FormatVersion != 1) {
394       if (D + sizeof(uint64_t) > End)
395         return data_type();
396       CountsSize = endian::readNext<uint64_t, little, unaligned>(D);
397     }
398     // Read counter values.
399     if (D + CountsSize * sizeof(uint64_t) > End)
400       return data_type();
401
402     CounterBuffer.clear();
403     CounterBuffer.reserve(CountsSize);
404     for (uint64_t J = 0; J < CountsSize; ++J)
405       CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D));
406
407     DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer));
408
409     // Read value profiling data.
410     if (FormatVersion > 2 && !readValueProfilingData(D, End)) {
411       DataBuffer.clear();
412       return data_type();
413     }
414   }
415   return DataBuffer;
416 }
417
418 template <typename HashTableImpl>
419 std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
420     StringRef FuncName, ArrayRef<InstrProfRecord> &Data) {
421   auto Iter = HashTable->find(FuncName);
422   if (Iter == HashTable->end())
423     return instrprof_error::unknown_function;
424
425   Data = (*Iter);
426   if (Data.empty())
427     return instrprof_error::malformed;
428
429   return instrprof_error::success;
430 }
431
432 template <typename HashTableImpl>
433 std::error_code InstrProfReaderIndex<HashTableImpl>::getRecords(
434     ArrayRef<InstrProfRecord> &Data) {
435   if (atEnd())
436     return instrprof_error::eof;
437
438   Data = *RecordIterator;
439
440   if (Data.empty())
441     return instrprof_error::malformed;
442
443   return instrprof_error::success;
444 }
445
446 template <typename HashTableImpl>
447 InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex(
448     const unsigned char *Buckets, const unsigned char *const Payload,
449     const unsigned char *const Base, IndexedInstrProf::HashT HashType,
450     uint64_t Version) {
451   FormatVersion = Version;
452   HashTable.reset(HashTableImpl::Create(
453       Buckets, Payload, Base,
454       typename HashTableImpl::InfoType(HashType, Version)));
455   // Form the map of hash values to const char* keys in profiling data.
456   std::vector<std::pair<uint64_t, const char *>> HashKeys;
457   for (auto Key : HashTable->keys()) {
458     const char *KeyTableRef = StringTable.insertString(Key);
459     HashKeys.push_back(std::make_pair(ComputeHash(HashType, Key), KeyTableRef));
460   }
461   std::sort(HashKeys.begin(), HashKeys.end(), less_first());
462   HashKeys.erase(std::unique(HashKeys.begin(), HashKeys.end()), HashKeys.end());
463   // Set the hash key map for the InstrLookupTrait
464   HashTable->getInfoObj().setHashKeys(std::move(HashKeys));
465   RecordIterator = HashTable->data_begin();
466 }
467
468 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) {
469   if (DataBuffer.getBufferSize() < 8)
470     return false;
471   using namespace support;
472   uint64_t Magic =
473       endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart());
474   // Verify that it's magical.
475   return Magic == IndexedInstrProf::Magic;
476 }
477
478 std::error_code IndexedInstrProfReader::readHeader() {
479   const unsigned char *Start =
480       (const unsigned char *)DataBuffer->getBufferStart();
481   const unsigned char *Cur = Start;
482   if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24)
483     return error(instrprof_error::truncated);
484
485   using namespace support;
486
487   auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur);
488   Cur += sizeof(IndexedInstrProf::Header);
489
490   // Check the magic number.
491   uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic);
492   if (Magic != IndexedInstrProf::Magic)
493     return error(instrprof_error::bad_magic);
494
495   // Read the version.
496   uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version);
497   if (FormatVersion > IndexedInstrProf::Version)
498     return error(instrprof_error::unsupported_version);
499
500   // Read the maximal function count.
501   MaxFunctionCount =
502       endian::byte_swap<uint64_t, little>(Header->MaxFunctionCount);
503
504   // Read the hash type and start offset.
505   IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>(
506       endian::byte_swap<uint64_t, little>(Header->HashType));
507   if (HashType > IndexedInstrProf::HashT::Last)
508     return error(instrprof_error::unsupported_hash_type);
509
510   uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset);
511
512   // The rest of the file is an on disk hash table.
513   InstrProfReaderIndexBase *IndexPtr = nullptr;
514   IndexPtr = new InstrProfReaderIndex<OnDiskHashTableImplV3>(
515       Start + HashOffset, Cur, Start, HashType, FormatVersion);
516   Index.reset(IndexPtr);
517   return success();
518 }
519
520 ErrorOr<InstrProfRecord>
521 IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName,
522                                            uint64_t FuncHash) {
523   ArrayRef<InstrProfRecord> Data;
524   std::error_code EC = Index->getRecords(FuncName, Data);
525   if (EC != instrprof_error::success)
526     return EC;
527   // Found it. Look for counters with the right hash.
528   for (unsigned I = 0, E = Data.size(); I < E; ++I) {
529     // Check for a match and fill the vector if there is one.
530     if (Data[I].Hash == FuncHash) {
531       return std::move(Data[I]);
532     }
533   }
534   return error(instrprof_error::hash_mismatch);
535 }
536
537 std::error_code
538 IndexedInstrProfReader::getFunctionCounts(StringRef FuncName, uint64_t FuncHash,
539                                           std::vector<uint64_t> &Counts) {
540   ErrorOr<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash);
541   if (std::error_code EC = Record.getError())
542     return EC;
543
544   Counts = Record.get().Counts;
545   return success();
546 }
547
548 std::error_code IndexedInstrProfReader::readNextRecord(
549     InstrProfRecord &Record) {
550   static unsigned RecordIndex = 0;
551
552   ArrayRef<InstrProfRecord> Data;
553
554   std::error_code EC = Index->getRecords(Data);
555   if (EC != instrprof_error::success)
556     return error(EC);
557
558   Record = Data[RecordIndex++];
559   if (RecordIndex >= Data.size()) {
560     Index->advanceToNextKey();
561     RecordIndex = 0;
562   }
563   return success();
564 }