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 auto DataSize = swap(Header.DataSize); 210 auto CountersSize = swap(Header.CountersSize); 211 auto NamesSize = swap(Header.NamesSize); 212 213 ptrdiff_t DataOffset = sizeof(RawInstrProf::Header); 214 ptrdiff_t CountersOffset = 215 DataOffset + sizeof(RawInstrProf::ProfileData<IntPtrT>) * DataSize; 216 ptrdiff_t NamesOffset = CountersOffset + sizeof(uint64_t) * CountersSize; 217 size_t ProfileSize = NamesOffset + sizeof(char) * NamesSize; 218 219 auto *Start = reinterpret_cast<const char *>(&Header); 220 if (Start + ProfileSize > DataBuffer->getBufferEnd()) 221 return error(instrprof_error::bad_header); 222 223 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>( 224 Start + DataOffset); 225 DataEnd = Data + DataSize; 226 CountersStart = reinterpret_cast<const uint64_t *>(Start + CountersOffset); 227 NamesStart = Start + NamesOffset; 228 ProfileEnd = Start + ProfileSize; 229 230 return success(); 231 } 232 233 template <class IntPtrT> 234 std::error_code RawInstrProfReader<IntPtrT>::readName(InstrProfRecord &Record) { 235 Record.Name = StringRef(getName(Data->NamePtr), swap(Data->NameSize)); 236 if (Record.Name.data() < NamesStart || 237 Record.Name.data() + Record.Name.size() > DataBuffer->getBufferEnd()) 238 return error(instrprof_error::malformed); 239 240 return success(); 241 } 242 243 template <class IntPtrT> 244 std::error_code RawInstrProfReader<IntPtrT>::readFuncHash( 245 InstrProfRecord &Record) { 246 Record.Hash = swap(Data->FuncHash); 247 return success(); 248 } 249 250 template <class IntPtrT> 251 std::error_code RawInstrProfReader<IntPtrT>::readRawCounts( 252 InstrProfRecord &Record) { 253 uint32_t NumCounters = swap(Data->NumCounters); 254 IntPtrT CounterPtr = Data->CounterPtr; 255 if (NumCounters == 0) 256 return error(instrprof_error::malformed); 257 258 auto RawCounts = makeArrayRef(getCounter(CounterPtr), NumCounters); 259 auto *NamesStartAsCounter = reinterpret_cast<const uint64_t *>(NamesStart); 260 261 // Check bounds. 262 if (RawCounts.data() < CountersStart || 263 RawCounts.data() + RawCounts.size() > NamesStartAsCounter) 264 return error(instrprof_error::malformed); 265 266 if (ShouldSwapBytes) { 267 Record.Counts.clear(); 268 Record.Counts.reserve(RawCounts.size()); 269 for (uint64_t Count : RawCounts) 270 Record.Counts.push_back(swap(Count)); 271 } else 272 Record.Counts = RawCounts; 273 274 return success(); 275 } 276 277 template <class IntPtrT> 278 std::error_code 279 RawInstrProfReader<IntPtrT>::readNextRecord(InstrProfRecord &Record) { 280 if (atEnd()) 281 if (std::error_code EC = readNextHeader(ProfileEnd)) 282 return EC; 283 284 // Read name ad set it in Record. 285 if (std::error_code EC = readName(Record)) 286 return EC; 287 288 // Read FuncHash and set it in Record. 289 if (std::error_code EC = readFuncHash(Record)) 290 return EC; 291 292 // Read raw counts and set Record. 293 if (std::error_code EC = readRawCounts(Record)) 294 return EC; 295 296 // Iterate. 297 advanceData(); 298 return success(); 299 } 300 301 namespace llvm { 302 template class RawInstrProfReader<uint32_t>; 303 template class RawInstrProfReader<uint64_t>; 304 } 305 306 InstrProfLookupTrait::hash_value_type 307 InstrProfLookupTrait::ComputeHash(StringRef K) { 308 return IndexedInstrProf::ComputeHash(HashType, K); 309 } 310 311 typedef InstrProfLookupTrait::data_type data_type; 312 typedef InstrProfLookupTrait::offset_type offset_type; 313 314 bool InstrProfLookupTrait::ReadValueProfilingData( 315 const unsigned char *&D, const unsigned char *const End) { 316 ErrorOr<std::unique_ptr<IndexedInstrProf::ValueProfData>> VDataPtrOrErr = 317 IndexedInstrProf::ValueProfData::getValueProfData( 318 D, End, ValueProfDataEndianness); 319 320 if (VDataPtrOrErr.getError()) 321 return false; 322 323 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), &HashKeys); 324 D += VDataPtrOrErr.get()->TotalSize; 325 326 return true; 327 } 328 329 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D, 330 offset_type N) { 331 // Check if the data is corrupt. If so, don't try to read it. 332 if (N % sizeof(uint64_t)) 333 return data_type(); 334 335 DataBuffer.clear(); 336 std::vector<uint64_t> CounterBuffer; 337 338 using namespace support; 339 const unsigned char *End = D + N; 340 while (D < End) { 341 // Read hash. 342 if (D + sizeof(uint64_t) >= End) 343 return data_type(); 344 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D); 345 346 // Initialize number of counters for FormatVersion == 1. 347 uint64_t CountsSize = N / sizeof(uint64_t) - 1; 348 // If format version is different then read the number of counters. 349 if (FormatVersion != 1) { 350 if (D + sizeof(uint64_t) > End) 351 return data_type(); 352 CountsSize = endian::readNext<uint64_t, little, unaligned>(D); 353 } 354 // Read counter values. 355 if (D + CountsSize * sizeof(uint64_t) > End) 356 return data_type(); 357 358 CounterBuffer.clear(); 359 CounterBuffer.reserve(CountsSize); 360 for (uint64_t J = 0; J < CountsSize; ++J) 361 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D)); 362 363 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer)); 364 365 // Read value profiling data. 366 if (FormatVersion > 2 && !ReadValueProfilingData(D, End)) { 367 DataBuffer.clear(); 368 return data_type(); 369 } 370 } 371 return DataBuffer; 372 } 373 374 std::error_code 375 InstrProfReaderIndex::getRecords(StringRef FuncName, 376 ArrayRef<InstrProfRecord> &Data) { 377 auto Iter = Index->find(FuncName); 378 if (Iter == Index->end()) 379 return instrprof_error::unknown_function; 380 381 Data = (*Iter); 382 if (Data.empty()) 383 return instrprof_error::malformed; 384 385 return instrprof_error::success; 386 } 387 388 std::error_code InstrProfReaderIndex::getRecords( 389 ArrayRef<InstrProfRecord> &Data) { 390 if (atEnd()) return instrprof_error::eof; 391 392 Data = *RecordIterator; 393 394 if (Data.empty()) return instrprof_error::malformed; 395 396 return instrprof_error::success; 397 } 398 399 void InstrProfReaderIndex::Init(const unsigned char *Buckets, 400 const unsigned char *const Payload, 401 const unsigned char *const Base, 402 IndexedInstrProf::HashT HashType, 403 uint64_t Version) { 404 FormatVersion = Version; 405 Index.reset(IndexType::Create(Buckets, Payload, Base, 406 InstrProfLookupTrait(HashType, Version))); 407 // Form the map of hash values to const char* keys in profiling data. 408 std::vector<std::pair<uint64_t, const char *>> HashKeys; 409 for (auto Key : Index->keys()) { 410 const char *KeyTableRef = StringTable.insertString(Key); 411 HashKeys.push_back(std::make_pair(ComputeHash(HashType, Key), KeyTableRef)); 412 } 413 std::sort(HashKeys.begin(), HashKeys.end(), less_first()); 414 HashKeys.erase(std::unique(HashKeys.begin(), HashKeys.end()), HashKeys.end()); 415 // Set the hash key map for the InstrLookupTrait 416 Index->getInfoObj().setHashKeys(std::move(HashKeys)); 417 RecordIterator = Index->data_begin(); 418 } 419 420 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) { 421 if (DataBuffer.getBufferSize() < 8) 422 return false; 423 using namespace support; 424 uint64_t Magic = 425 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart()); 426 // Verify that it's magical. 427 return Magic == IndexedInstrProf::Magic; 428 } 429 430 std::error_code IndexedInstrProfReader::readHeader() { 431 const unsigned char *Start = 432 (const unsigned char *)DataBuffer->getBufferStart(); 433 const unsigned char *Cur = Start; 434 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24) 435 return error(instrprof_error::truncated); 436 437 using namespace support; 438 439 auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur); 440 Cur += sizeof(IndexedInstrProf::Header); 441 442 // Check the magic number. 443 uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic); 444 if (Magic != IndexedInstrProf::Magic) 445 return error(instrprof_error::bad_magic); 446 447 // Read the version. 448 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version); 449 if (FormatVersion > IndexedInstrProf::Version) 450 return error(instrprof_error::unsupported_version); 451 452 // Read the maximal function count. 453 MaxFunctionCount = 454 endian::byte_swap<uint64_t, little>(Header->MaxFunctionCount); 455 456 // Read the hash type and start offset. 457 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>( 458 endian::byte_swap<uint64_t, little>(Header->HashType)); 459 if (HashType > IndexedInstrProf::HashT::Last) 460 return error(instrprof_error::unsupported_hash_type); 461 462 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset); 463 464 // The rest of the file is an on disk hash table. 465 Index.Init(Start + HashOffset, Cur, Start, HashType, FormatVersion); 466 467 return success(); 468 } 469 470 ErrorOr<InstrProfRecord> 471 IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName, 472 uint64_t FuncHash) { 473 ArrayRef<InstrProfRecord> Data; 474 std::error_code EC = Index.getRecords(FuncName, Data); 475 if (EC != instrprof_error::success) 476 return EC; 477 // Found it. Look for counters with the right hash. 478 for (unsigned I = 0, E = Data.size(); I < E; ++I) { 479 // Check for a match and fill the vector if there is one. 480 if (Data[I].Hash == FuncHash) { 481 return std::move(Data[I]); 482 } 483 } 484 return error(instrprof_error::hash_mismatch); 485 } 486 487 std::error_code 488 IndexedInstrProfReader::getFunctionCounts(StringRef FuncName, uint64_t FuncHash, 489 std::vector<uint64_t> &Counts) { 490 ErrorOr<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash); 491 if (std::error_code EC = Record.getError()) 492 return EC; 493 494 Counts = Record.get().Counts; 495 return success(); 496 } 497 498 std::error_code IndexedInstrProfReader::readNextRecord( 499 InstrProfRecord &Record) { 500 static unsigned RecordIndex = 0; 501 502 ArrayRef<InstrProfRecord> Data; 503 504 std::error_code EC = Index.getRecords(Data); 505 if (EC != instrprof_error::success) 506 return error(EC); 507 508 Record = Data[RecordIndex++]; 509 if (RecordIndex >= Data.size()) { 510 Index.advanceToNextKey(); 511 RecordIndex = 0; 512 } 513 return success(); 514 } 515