1 //===- InstrProfReader.cpp - Instrumented profiling reader ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains support for reading profiling data for clang's 10 // instrumentation based PGO and coverage. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ProfileData/InstrProfReader.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/IR/ProfileSummary.h" 21 #include "llvm/ProfileData/InstrProf.h" 22 #include "llvm/ProfileData/ProfileCommon.h" 23 #include "llvm/Support/Endian.h" 24 #include "llvm/Support/Error.h" 25 #include "llvm/Support/ErrorOr.h" 26 #include "llvm/Support/MemoryBuffer.h" 27 #include "llvm/Support/SwapByteOrder.h" 28 #include "llvm/Support/SymbolRemappingReader.h" 29 #include <algorithm> 30 #include <cctype> 31 #include <cstddef> 32 #include <cstdint> 33 #include <limits> 34 #include <memory> 35 #include <system_error> 36 #include <utility> 37 #include <vector> 38 39 using namespace llvm; 40 41 static Expected<std::unique_ptr<MemoryBuffer>> 42 setupMemoryBuffer(const Twine &Path) { 43 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 44 MemoryBuffer::getFileOrSTDIN(Path, /*IsText=*/true); 45 if (std::error_code EC = BufferOrErr.getError()) 46 return errorCodeToError(EC); 47 return std::move(BufferOrErr.get()); 48 } 49 50 static Error initializeReader(InstrProfReader &Reader) { 51 return Reader.readHeader(); 52 } 53 54 Expected<std::unique_ptr<InstrProfReader>> 55 InstrProfReader::create(const Twine &Path, 56 const InstrProfCorrelator *Correlator) { 57 // Set up the buffer to read. 58 auto BufferOrError = setupMemoryBuffer(Path); 59 if (Error E = BufferOrError.takeError()) 60 return std::move(E); 61 return InstrProfReader::create(std::move(BufferOrError.get()), Correlator); 62 } 63 64 Expected<std::unique_ptr<InstrProfReader>> 65 InstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer, 66 const InstrProfCorrelator *Correlator) { 67 // Sanity check the buffer. 68 if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint64_t>::max()) 69 return make_error<InstrProfError>(instrprof_error::too_large); 70 71 if (Buffer->getBufferSize() == 0) 72 return make_error<InstrProfError>(instrprof_error::empty_raw_profile); 73 74 std::unique_ptr<InstrProfReader> Result; 75 // Create the reader. 76 if (IndexedInstrProfReader::hasFormat(*Buffer)) 77 Result.reset(new IndexedInstrProfReader(std::move(Buffer))); 78 else if (RawInstrProfReader64::hasFormat(*Buffer)) 79 Result.reset(new RawInstrProfReader64(std::move(Buffer), Correlator)); 80 else if (RawInstrProfReader32::hasFormat(*Buffer)) 81 Result.reset(new RawInstrProfReader32(std::move(Buffer), Correlator)); 82 else if (TextInstrProfReader::hasFormat(*Buffer)) 83 Result.reset(new TextInstrProfReader(std::move(Buffer))); 84 else 85 return make_error<InstrProfError>(instrprof_error::unrecognized_format); 86 87 // Initialize the reader and return the result. 88 if (Error E = initializeReader(*Result)) 89 return std::move(E); 90 91 return std::move(Result); 92 } 93 94 Expected<std::unique_ptr<IndexedInstrProfReader>> 95 IndexedInstrProfReader::create(const Twine &Path, const Twine &RemappingPath) { 96 // Set up the buffer to read. 97 auto BufferOrError = setupMemoryBuffer(Path); 98 if (Error E = BufferOrError.takeError()) 99 return std::move(E); 100 101 // Set up the remapping buffer if requested. 102 std::unique_ptr<MemoryBuffer> RemappingBuffer; 103 std::string RemappingPathStr = RemappingPath.str(); 104 if (!RemappingPathStr.empty()) { 105 auto RemappingBufferOrError = setupMemoryBuffer(RemappingPathStr); 106 if (Error E = RemappingBufferOrError.takeError()) 107 return std::move(E); 108 RemappingBuffer = std::move(RemappingBufferOrError.get()); 109 } 110 111 return IndexedInstrProfReader::create(std::move(BufferOrError.get()), 112 std::move(RemappingBuffer)); 113 } 114 115 Expected<std::unique_ptr<IndexedInstrProfReader>> 116 IndexedInstrProfReader::create(std::unique_ptr<MemoryBuffer> Buffer, 117 std::unique_ptr<MemoryBuffer> RemappingBuffer) { 118 if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint64_t>::max()) 119 return make_error<InstrProfError>(instrprof_error::too_large); 120 121 // Create the reader. 122 if (!IndexedInstrProfReader::hasFormat(*Buffer)) 123 return make_error<InstrProfError>(instrprof_error::bad_magic); 124 auto Result = std::make_unique<IndexedInstrProfReader>( 125 std::move(Buffer), std::move(RemappingBuffer)); 126 127 // Initialize the reader and return the result. 128 if (Error E = initializeReader(*Result)) 129 return std::move(E); 130 131 return std::move(Result); 132 } 133 134 void InstrProfIterator::Increment() { 135 if (auto E = Reader->readNextRecord(Record)) { 136 // Handle errors in the reader. 137 InstrProfError::take(std::move(E)); 138 *this = InstrProfIterator(); 139 } 140 } 141 142 bool TextInstrProfReader::hasFormat(const MemoryBuffer &Buffer) { 143 // Verify that this really looks like plain ASCII text by checking a 144 // 'reasonable' number of characters (up to profile magic size). 145 size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t)); 146 StringRef buffer = Buffer.getBufferStart(); 147 return count == 0 || 148 std::all_of(buffer.begin(), buffer.begin() + count, 149 [](char c) { return isPrint(c) || isSpace(c); }); 150 } 151 152 // Read the profile variant flag from the header: ":FE" means this is a FE 153 // generated profile. ":IR" means this is an IR level profile. Other strings 154 // with a leading ':' will be reported an error format. 155 Error TextInstrProfReader::readHeader() { 156 Symtab.reset(new InstrProfSymtab()); 157 158 while (Line->startswith(":")) { 159 StringRef Str = Line->substr(1); 160 if (Str.equals_insensitive("ir")) 161 ProfileKind |= InstrProfKind::IR; 162 else if (Str.equals_insensitive("fe")) 163 ProfileKind |= InstrProfKind::FE; 164 else if (Str.equals_insensitive("csir")) { 165 ProfileKind |= InstrProfKind::IR; 166 ProfileKind |= InstrProfKind::CS; 167 } else if (Str.equals_insensitive("entry_first")) 168 ProfileKind |= InstrProfKind::BB; 169 else if (Str.equals_insensitive("not_entry_first")) 170 ProfileKind &= ~InstrProfKind::BB; 171 else 172 return error(instrprof_error::bad_header); 173 ++Line; 174 } 175 return success(); 176 } 177 178 Error 179 TextInstrProfReader::readValueProfileData(InstrProfRecord &Record) { 180 181 #define CHECK_LINE_END(Line) \ 182 if (Line.is_at_end()) \ 183 return error(instrprof_error::truncated); 184 #define READ_NUM(Str, Dst) \ 185 if ((Str).getAsInteger(10, (Dst))) \ 186 return error(instrprof_error::malformed); 187 #define VP_READ_ADVANCE(Val) \ 188 CHECK_LINE_END(Line); \ 189 uint32_t Val; \ 190 READ_NUM((*Line), (Val)); \ 191 Line++; 192 193 if (Line.is_at_end()) 194 return success(); 195 196 uint32_t NumValueKinds; 197 if (Line->getAsInteger(10, NumValueKinds)) { 198 // No value profile data 199 return success(); 200 } 201 if (NumValueKinds == 0 || NumValueKinds > IPVK_Last + 1) 202 return error(instrprof_error::malformed, 203 "number of value kinds is invalid"); 204 Line++; 205 206 for (uint32_t VK = 0; VK < NumValueKinds; VK++) { 207 VP_READ_ADVANCE(ValueKind); 208 if (ValueKind > IPVK_Last) 209 return error(instrprof_error::malformed, "value kind is invalid"); 210 ; 211 VP_READ_ADVANCE(NumValueSites); 212 if (!NumValueSites) 213 continue; 214 215 Record.reserveSites(VK, NumValueSites); 216 for (uint32_t S = 0; S < NumValueSites; S++) { 217 VP_READ_ADVANCE(NumValueData); 218 219 std::vector<InstrProfValueData> CurrentValues; 220 for (uint32_t V = 0; V < NumValueData; V++) { 221 CHECK_LINE_END(Line); 222 std::pair<StringRef, StringRef> VD = Line->rsplit(':'); 223 uint64_t TakenCount, Value; 224 if (ValueKind == IPVK_IndirectCallTarget) { 225 if (InstrProfSymtab::isExternalSymbol(VD.first)) { 226 Value = 0; 227 } else { 228 if (Error E = Symtab->addFuncName(VD.first)) 229 return E; 230 Value = IndexedInstrProf::ComputeHash(VD.first); 231 } 232 } else { 233 READ_NUM(VD.first, Value); 234 } 235 READ_NUM(VD.second, TakenCount); 236 CurrentValues.push_back({Value, TakenCount}); 237 Line++; 238 } 239 Record.addValueData(ValueKind, S, CurrentValues.data(), NumValueData, 240 nullptr); 241 } 242 } 243 return success(); 244 245 #undef CHECK_LINE_END 246 #undef READ_NUM 247 #undef VP_READ_ADVANCE 248 } 249 250 Error TextInstrProfReader::readNextRecord(NamedInstrProfRecord &Record) { 251 // Skip empty lines and comments. 252 while (!Line.is_at_end() && (Line->empty() || Line->startswith("#"))) 253 ++Line; 254 // If we hit EOF while looking for a name, we're done. 255 if (Line.is_at_end()) { 256 return error(instrprof_error::eof); 257 } 258 259 // Read the function name. 260 Record.Name = *Line++; 261 if (Error E = Symtab->addFuncName(Record.Name)) 262 return error(std::move(E)); 263 264 // Read the function hash. 265 if (Line.is_at_end()) 266 return error(instrprof_error::truncated); 267 if ((Line++)->getAsInteger(0, Record.Hash)) 268 return error(instrprof_error::malformed, 269 "function hash is not a valid integer"); 270 271 // Read the number of counters. 272 uint64_t NumCounters; 273 if (Line.is_at_end()) 274 return error(instrprof_error::truncated); 275 if ((Line++)->getAsInteger(10, NumCounters)) 276 return error(instrprof_error::malformed, 277 "number of counters is not a valid integer"); 278 if (NumCounters == 0) 279 return error(instrprof_error::malformed, "number of counters is zero"); 280 281 // Read each counter and fill our internal storage with the values. 282 Record.Clear(); 283 Record.Counts.reserve(NumCounters); 284 for (uint64_t I = 0; I < NumCounters; ++I) { 285 if (Line.is_at_end()) 286 return error(instrprof_error::truncated); 287 uint64_t Count; 288 if ((Line++)->getAsInteger(10, Count)) 289 return error(instrprof_error::malformed, "count is invalid"); 290 Record.Counts.push_back(Count); 291 } 292 293 // Check if value profile data exists and read it if so. 294 if (Error E = readValueProfileData(Record)) 295 return error(std::move(E)); 296 297 return success(); 298 } 299 300 template <class IntPtrT> 301 bool RawInstrProfReader<IntPtrT>::hasFormat(const MemoryBuffer &DataBuffer) { 302 if (DataBuffer.getBufferSize() < sizeof(uint64_t)) 303 return false; 304 uint64_t Magic = 305 *reinterpret_cast<const uint64_t *>(DataBuffer.getBufferStart()); 306 return RawInstrProf::getMagic<IntPtrT>() == Magic || 307 sys::getSwappedBytes(RawInstrProf::getMagic<IntPtrT>()) == Magic; 308 } 309 310 template <class IntPtrT> 311 Error RawInstrProfReader<IntPtrT>::readHeader() { 312 if (!hasFormat(*DataBuffer)) 313 return error(instrprof_error::bad_magic); 314 if (DataBuffer->getBufferSize() < sizeof(RawInstrProf::Header)) 315 return error(instrprof_error::bad_header); 316 auto *Header = reinterpret_cast<const RawInstrProf::Header *>( 317 DataBuffer->getBufferStart()); 318 ShouldSwapBytes = Header->Magic != RawInstrProf::getMagic<IntPtrT>(); 319 return readHeader(*Header); 320 } 321 322 template <class IntPtrT> 323 Error RawInstrProfReader<IntPtrT>::readNextHeader(const char *CurrentPos) { 324 const char *End = DataBuffer->getBufferEnd(); 325 // Skip zero padding between profiles. 326 while (CurrentPos != End && *CurrentPos == 0) 327 ++CurrentPos; 328 // If there's nothing left, we're done. 329 if (CurrentPos == End) 330 return make_error<InstrProfError>(instrprof_error::eof); 331 // If there isn't enough space for another header, this is probably just 332 // garbage at the end of the file. 333 if (CurrentPos + sizeof(RawInstrProf::Header) > End) 334 return make_error<InstrProfError>(instrprof_error::malformed, 335 "not enough space for another header"); 336 // The writer ensures each profile is padded to start at an aligned address. 337 if (reinterpret_cast<size_t>(CurrentPos) % alignof(uint64_t)) 338 return make_error<InstrProfError>(instrprof_error::malformed, 339 "insufficient padding"); 340 // The magic should have the same byte order as in the previous header. 341 uint64_t Magic = *reinterpret_cast<const uint64_t *>(CurrentPos); 342 if (Magic != swap(RawInstrProf::getMagic<IntPtrT>())) 343 return make_error<InstrProfError>(instrprof_error::bad_magic); 344 345 // There's another profile to read, so we need to process the header. 346 auto *Header = reinterpret_cast<const RawInstrProf::Header *>(CurrentPos); 347 return readHeader(*Header); 348 } 349 350 template <class IntPtrT> 351 Error RawInstrProfReader<IntPtrT>::createSymtab(InstrProfSymtab &Symtab) { 352 if (Error E = Symtab.create(StringRef(NamesStart, NamesEnd - NamesStart))) 353 return error(std::move(E)); 354 for (const RawInstrProf::ProfileData<IntPtrT> *I = Data; I != DataEnd; ++I) { 355 const IntPtrT FPtr = swap(I->FunctionPointer); 356 if (!FPtr) 357 continue; 358 Symtab.mapAddress(FPtr, I->NameRef); 359 } 360 return success(); 361 } 362 363 template <class IntPtrT> 364 Error RawInstrProfReader<IntPtrT>::readHeader( 365 const RawInstrProf::Header &Header) { 366 Version = swap(Header.Version); 367 if (GET_VERSION(Version) != RawInstrProf::Version) 368 return error(instrprof_error::unsupported_version); 369 if (useDebugInfoCorrelate() && !Correlator) 370 return error(instrprof_error::missing_debug_info_for_correlation); 371 if (!useDebugInfoCorrelate() && Correlator) 372 return error(instrprof_error::unexpected_debug_info_for_correlation); 373 374 BinaryIdsSize = swap(Header.BinaryIdsSize); 375 if (BinaryIdsSize % sizeof(uint64_t)) 376 return error(instrprof_error::bad_header); 377 378 CountersDelta = swap(Header.CountersDelta); 379 NamesDelta = swap(Header.NamesDelta); 380 auto NumData = swap(Header.DataSize); 381 auto PaddingBytesBeforeCounters = swap(Header.PaddingBytesBeforeCounters); 382 auto CountersSize = swap(Header.CountersSize) * getCounterTypeSize(); 383 auto PaddingBytesAfterCounters = swap(Header.PaddingBytesAfterCounters); 384 auto NamesSize = swap(Header.NamesSize); 385 ValueKindLast = swap(Header.ValueKindLast); 386 387 auto DataSize = NumData * sizeof(RawInstrProf::ProfileData<IntPtrT>); 388 auto PaddingSize = getNumPaddingBytes(NamesSize); 389 390 // Profile data starts after profile header and binary ids if exist. 391 ptrdiff_t DataOffset = sizeof(RawInstrProf::Header) + BinaryIdsSize; 392 ptrdiff_t CountersOffset = DataOffset + DataSize + PaddingBytesBeforeCounters; 393 ptrdiff_t NamesOffset = 394 CountersOffset + CountersSize + PaddingBytesAfterCounters; 395 ptrdiff_t ValueDataOffset = NamesOffset + NamesSize + PaddingSize; 396 397 auto *Start = reinterpret_cast<const char *>(&Header); 398 if (Start + ValueDataOffset > DataBuffer->getBufferEnd()) 399 return error(instrprof_error::bad_header); 400 401 if (Correlator) { 402 // These sizes in the raw file are zero because we constructed them in the 403 // Correlator. 404 assert(DataSize == 0 && NamesSize == 0); 405 assert(CountersDelta == 0 && NamesDelta == 0); 406 Data = Correlator->getDataPointer(); 407 DataEnd = Data + Correlator->getDataSize(); 408 NamesStart = Correlator->getNamesPointer(); 409 NamesEnd = NamesStart + Correlator->getNamesSize(); 410 } else { 411 Data = reinterpret_cast<const RawInstrProf::ProfileData<IntPtrT> *>( 412 Start + DataOffset); 413 DataEnd = Data + NumData; 414 NamesStart = Start + NamesOffset; 415 NamesEnd = NamesStart + NamesSize; 416 } 417 418 // Binary ids start just after the header. 419 BinaryIdsStart = 420 reinterpret_cast<const uint8_t *>(&Header) + sizeof(RawInstrProf::Header); 421 CountersStart = Start + CountersOffset; 422 CountersEnd = CountersStart + CountersSize; 423 ValueDataStart = reinterpret_cast<const uint8_t *>(Start + ValueDataOffset); 424 425 const uint8_t *BufferEnd = (const uint8_t *)DataBuffer->getBufferEnd(); 426 if (BinaryIdsStart + BinaryIdsSize > BufferEnd) 427 return error(instrprof_error::bad_header); 428 429 std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>(); 430 if (Error E = createSymtab(*NewSymtab.get())) 431 return E; 432 433 Symtab = std::move(NewSymtab); 434 return success(); 435 } 436 437 template <class IntPtrT> 438 Error RawInstrProfReader<IntPtrT>::readName(NamedInstrProfRecord &Record) { 439 Record.Name = getName(Data->NameRef); 440 return success(); 441 } 442 443 template <class IntPtrT> 444 Error RawInstrProfReader<IntPtrT>::readFuncHash(NamedInstrProfRecord &Record) { 445 Record.Hash = swap(Data->FuncHash); 446 return success(); 447 } 448 449 template <class IntPtrT> 450 Error RawInstrProfReader<IntPtrT>::readRawCounts( 451 InstrProfRecord &Record) { 452 uint32_t NumCounters = swap(Data->NumCounters); 453 if (NumCounters == 0) 454 return error(instrprof_error::malformed, "number of counters is zero"); 455 456 ptrdiff_t CounterBaseOffset = swap(Data->CounterPtr) - CountersDelta; 457 if (CounterBaseOffset < 0) 458 return error( 459 instrprof_error::malformed, 460 ("counter offset " + Twine(CounterBaseOffset) + " is negative").str()); 461 462 if (CounterBaseOffset >= CountersEnd - CountersStart) 463 return error(instrprof_error::malformed, 464 ("counter offset " + Twine(CounterBaseOffset) + 465 " is greater than the maximum counter offset " + 466 Twine(CountersEnd - CountersStart - 1)) 467 .str()); 468 469 uint64_t MaxNumCounters = 470 (CountersEnd - (CountersStart + CounterBaseOffset)) / 471 getCounterTypeSize(); 472 if (NumCounters > MaxNumCounters) 473 return error(instrprof_error::malformed, 474 ("number of counters " + Twine(NumCounters) + 475 " is greater than the maximum number of counters " + 476 Twine(MaxNumCounters)) 477 .str()); 478 479 Record.Counts.clear(); 480 Record.Counts.reserve(NumCounters); 481 for (uint32_t I = 0; I < NumCounters; I++) { 482 const char *Ptr = 483 CountersStart + CounterBaseOffset + I * getCounterTypeSize(); 484 if (hasSingleByteCoverage()) { 485 // A value of zero signifies the block is covered. 486 Record.Counts.push_back(*Ptr == 0 ? 1 : 0); 487 } else { 488 const auto *CounterValue = reinterpret_cast<const uint64_t *>(Ptr); 489 Record.Counts.push_back(swap(*CounterValue)); 490 } 491 } 492 493 return success(); 494 } 495 496 template <class IntPtrT> 497 Error RawInstrProfReader<IntPtrT>::readValueProfilingData( 498 InstrProfRecord &Record) { 499 Record.clearValueData(); 500 CurValueDataSize = 0; 501 // Need to match the logic in value profile dumper code in compiler-rt: 502 uint32_t NumValueKinds = 0; 503 for (uint32_t I = 0; I < IPVK_Last + 1; I++) 504 NumValueKinds += (Data->NumValueSites[I] != 0); 505 506 if (!NumValueKinds) 507 return success(); 508 509 Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr = 510 ValueProfData::getValueProfData( 511 ValueDataStart, (const unsigned char *)DataBuffer->getBufferEnd(), 512 getDataEndianness()); 513 514 if (Error E = VDataPtrOrErr.takeError()) 515 return E; 516 517 // Note that besides deserialization, this also performs the conversion for 518 // indirect call targets. The function pointers from the raw profile are 519 // remapped into function name hashes. 520 VDataPtrOrErr.get()->deserializeTo(Record, Symtab.get()); 521 CurValueDataSize = VDataPtrOrErr.get()->getSize(); 522 return success(); 523 } 524 525 template <class IntPtrT> 526 Error RawInstrProfReader<IntPtrT>::readNextRecord(NamedInstrProfRecord &Record) { 527 if (atEnd()) 528 // At this point, ValueDataStart field points to the next header. 529 if (Error E = readNextHeader(getNextHeaderPos())) 530 return error(std::move(E)); 531 532 // Read name ad set it in Record. 533 if (Error E = readName(Record)) 534 return error(std::move(E)); 535 536 // Read FuncHash and set it in Record. 537 if (Error E = readFuncHash(Record)) 538 return error(std::move(E)); 539 540 // Read raw counts and set Record. 541 if (Error E = readRawCounts(Record)) 542 return error(std::move(E)); 543 544 // Read value data and set Record. 545 if (Error E = readValueProfilingData(Record)) 546 return error(std::move(E)); 547 548 // Iterate. 549 advanceData(); 550 return success(); 551 } 552 553 static size_t RoundUp(size_t size, size_t align) { 554 return (size + align - 1) & ~(align - 1); 555 } 556 557 template <class IntPtrT> 558 Error RawInstrProfReader<IntPtrT>::printBinaryIds(raw_ostream &OS) { 559 if (BinaryIdsSize == 0) 560 return success(); 561 562 OS << "Binary IDs: \n"; 563 const uint8_t *BI = BinaryIdsStart; 564 const uint8_t *BIEnd = BinaryIdsStart + BinaryIdsSize; 565 while (BI < BIEnd) { 566 size_t Remaining = BIEnd - BI; 567 568 // There should be enough left to read the binary ID size field. 569 if (Remaining < sizeof(uint64_t)) 570 return make_error<InstrProfError>( 571 instrprof_error::malformed, 572 "not enough data to read binary id length"); 573 574 uint64_t BinaryIdLen = swap(*reinterpret_cast<const uint64_t *>(BI)); 575 576 // There should be enough left to read the binary ID size field, and the 577 // binary ID. 578 if (Remaining < sizeof(BinaryIdLen) + BinaryIdLen) 579 return make_error<InstrProfError>( 580 instrprof_error::malformed, "not enough data to read binary id data"); 581 582 // Increment by binary id length data type size. 583 BI += sizeof(BinaryIdLen); 584 if (BI > (const uint8_t *)DataBuffer->getBufferEnd()) 585 return make_error<InstrProfError>( 586 instrprof_error::malformed, 587 "binary id that is read is bigger than buffer size"); 588 589 for (uint64_t I = 0; I < BinaryIdLen; I++) 590 OS << format("%02x", BI[I]); 591 OS << "\n"; 592 593 // Increment by binary id data length, rounded to the next 8 bytes. This 594 // accounts for the zero-padding after each build ID. 595 BI += RoundUp(BinaryIdLen, sizeof(uint64_t)); 596 if (BI > (const uint8_t *)DataBuffer->getBufferEnd()) 597 return make_error<InstrProfError>(instrprof_error::malformed); 598 } 599 600 return success(); 601 } 602 603 namespace llvm { 604 605 template class RawInstrProfReader<uint32_t>; 606 template class RawInstrProfReader<uint64_t>; 607 608 } // end namespace llvm 609 610 InstrProfLookupTrait::hash_value_type 611 InstrProfLookupTrait::ComputeHash(StringRef K) { 612 return IndexedInstrProf::ComputeHash(HashType, K); 613 } 614 615 using data_type = InstrProfLookupTrait::data_type; 616 using offset_type = InstrProfLookupTrait::offset_type; 617 618 bool InstrProfLookupTrait::readValueProfilingData( 619 const unsigned char *&D, const unsigned char *const End) { 620 Expected<std::unique_ptr<ValueProfData>> VDataPtrOrErr = 621 ValueProfData::getValueProfData(D, End, ValueProfDataEndianness); 622 623 if (VDataPtrOrErr.takeError()) 624 return false; 625 626 VDataPtrOrErr.get()->deserializeTo(DataBuffer.back(), nullptr); 627 D += VDataPtrOrErr.get()->TotalSize; 628 629 return true; 630 } 631 632 data_type InstrProfLookupTrait::ReadData(StringRef K, const unsigned char *D, 633 offset_type N) { 634 using namespace support; 635 636 // Check if the data is corrupt. If so, don't try to read it. 637 if (N % sizeof(uint64_t)) 638 return data_type(); 639 640 DataBuffer.clear(); 641 std::vector<uint64_t> CounterBuffer; 642 643 const unsigned char *End = D + N; 644 while (D < End) { 645 // Read hash. 646 if (D + sizeof(uint64_t) >= End) 647 return data_type(); 648 uint64_t Hash = endian::readNext<uint64_t, little, unaligned>(D); 649 650 // Initialize number of counters for GET_VERSION(FormatVersion) == 1. 651 uint64_t CountsSize = N / sizeof(uint64_t) - 1; 652 // If format version is different then read the number of counters. 653 if (GET_VERSION(FormatVersion) != IndexedInstrProf::ProfVersion::Version1) { 654 if (D + sizeof(uint64_t) > End) 655 return data_type(); 656 CountsSize = endian::readNext<uint64_t, little, unaligned>(D); 657 } 658 // Read counter values. 659 if (D + CountsSize * sizeof(uint64_t) > End) 660 return data_type(); 661 662 CounterBuffer.clear(); 663 CounterBuffer.reserve(CountsSize); 664 for (uint64_t J = 0; J < CountsSize; ++J) 665 CounterBuffer.push_back(endian::readNext<uint64_t, little, unaligned>(D)); 666 667 DataBuffer.emplace_back(K, Hash, std::move(CounterBuffer)); 668 669 // Read value profiling data. 670 if (GET_VERSION(FormatVersion) > IndexedInstrProf::ProfVersion::Version2 && 671 !readValueProfilingData(D, End)) { 672 DataBuffer.clear(); 673 return data_type(); 674 } 675 } 676 return DataBuffer; 677 } 678 679 template <typename HashTableImpl> 680 Error InstrProfReaderIndex<HashTableImpl>::getRecords( 681 StringRef FuncName, ArrayRef<NamedInstrProfRecord> &Data) { 682 auto Iter = HashTable->find(FuncName); 683 if (Iter == HashTable->end()) 684 return make_error<InstrProfError>(instrprof_error::unknown_function); 685 686 Data = (*Iter); 687 if (Data.empty()) 688 return make_error<InstrProfError>(instrprof_error::malformed, 689 "profile data is empty"); 690 691 return Error::success(); 692 } 693 694 template <typename HashTableImpl> 695 Error InstrProfReaderIndex<HashTableImpl>::getRecords( 696 ArrayRef<NamedInstrProfRecord> &Data) { 697 if (atEnd()) 698 return make_error<InstrProfError>(instrprof_error::eof); 699 700 Data = *RecordIterator; 701 702 if (Data.empty()) 703 return make_error<InstrProfError>(instrprof_error::malformed, 704 "profile data is empty"); 705 706 return Error::success(); 707 } 708 709 template <typename HashTableImpl> 710 InstrProfReaderIndex<HashTableImpl>::InstrProfReaderIndex( 711 const unsigned char *Buckets, const unsigned char *const Payload, 712 const unsigned char *const Base, IndexedInstrProf::HashT HashType, 713 uint64_t Version) { 714 FormatVersion = Version; 715 HashTable.reset(HashTableImpl::Create( 716 Buckets, Payload, Base, 717 typename HashTableImpl::InfoType(HashType, Version))); 718 RecordIterator = HashTable->data_begin(); 719 } 720 721 namespace { 722 /// A remapper that does not apply any remappings. 723 class InstrProfReaderNullRemapper : public InstrProfReaderRemapper { 724 InstrProfReaderIndexBase &Underlying; 725 726 public: 727 InstrProfReaderNullRemapper(InstrProfReaderIndexBase &Underlying) 728 : Underlying(Underlying) {} 729 730 Error getRecords(StringRef FuncName, 731 ArrayRef<NamedInstrProfRecord> &Data) override { 732 return Underlying.getRecords(FuncName, Data); 733 } 734 }; 735 } // namespace 736 737 /// A remapper that applies remappings based on a symbol remapping file. 738 template <typename HashTableImpl> 739 class llvm::InstrProfReaderItaniumRemapper 740 : public InstrProfReaderRemapper { 741 public: 742 InstrProfReaderItaniumRemapper( 743 std::unique_ptr<MemoryBuffer> RemapBuffer, 744 InstrProfReaderIndex<HashTableImpl> &Underlying) 745 : RemapBuffer(std::move(RemapBuffer)), Underlying(Underlying) { 746 } 747 748 /// Extract the original function name from a PGO function name. 749 static StringRef extractName(StringRef Name) { 750 // We can have multiple :-separated pieces; there can be pieces both 751 // before and after the mangled name. Find the first part that starts 752 // with '_Z'; we'll assume that's the mangled name we want. 753 std::pair<StringRef, StringRef> Parts = {StringRef(), Name}; 754 while (true) { 755 Parts = Parts.second.split(':'); 756 if (Parts.first.startswith("_Z")) 757 return Parts.first; 758 if (Parts.second.empty()) 759 return Name; 760 } 761 } 762 763 /// Given a mangled name extracted from a PGO function name, and a new 764 /// form for that mangled name, reconstitute the name. 765 static void reconstituteName(StringRef OrigName, StringRef ExtractedName, 766 StringRef Replacement, 767 SmallVectorImpl<char> &Out) { 768 Out.reserve(OrigName.size() + Replacement.size() - ExtractedName.size()); 769 Out.insert(Out.end(), OrigName.begin(), ExtractedName.begin()); 770 Out.insert(Out.end(), Replacement.begin(), Replacement.end()); 771 Out.insert(Out.end(), ExtractedName.end(), OrigName.end()); 772 } 773 774 Error populateRemappings() override { 775 if (Error E = Remappings.read(*RemapBuffer)) 776 return E; 777 for (StringRef Name : Underlying.HashTable->keys()) { 778 StringRef RealName = extractName(Name); 779 if (auto Key = Remappings.insert(RealName)) { 780 // FIXME: We could theoretically map the same equivalence class to 781 // multiple names in the profile data. If that happens, we should 782 // return NamedInstrProfRecords from all of them. 783 MappedNames.insert({Key, RealName}); 784 } 785 } 786 return Error::success(); 787 } 788 789 Error getRecords(StringRef FuncName, 790 ArrayRef<NamedInstrProfRecord> &Data) override { 791 StringRef RealName = extractName(FuncName); 792 if (auto Key = Remappings.lookup(RealName)) { 793 StringRef Remapped = MappedNames.lookup(Key); 794 if (!Remapped.empty()) { 795 if (RealName.begin() == FuncName.begin() && 796 RealName.end() == FuncName.end()) 797 FuncName = Remapped; 798 else { 799 // Try rebuilding the name from the given remapping. 800 SmallString<256> Reconstituted; 801 reconstituteName(FuncName, RealName, Remapped, Reconstituted); 802 Error E = Underlying.getRecords(Reconstituted, Data); 803 if (!E) 804 return E; 805 806 // If we failed because the name doesn't exist, fall back to asking 807 // about the original name. 808 if (Error Unhandled = handleErrors( 809 std::move(E), [](std::unique_ptr<InstrProfError> Err) { 810 return Err->get() == instrprof_error::unknown_function 811 ? Error::success() 812 : Error(std::move(Err)); 813 })) 814 return Unhandled; 815 } 816 } 817 } 818 return Underlying.getRecords(FuncName, Data); 819 } 820 821 private: 822 /// The memory buffer containing the remapping configuration. Remappings 823 /// holds pointers into this buffer. 824 std::unique_ptr<MemoryBuffer> RemapBuffer; 825 826 /// The mangling remapper. 827 SymbolRemappingReader Remappings; 828 829 /// Mapping from mangled name keys to the name used for the key in the 830 /// profile data. 831 /// FIXME: Can we store a location within the on-disk hash table instead of 832 /// redoing lookup? 833 DenseMap<SymbolRemappingReader::Key, StringRef> MappedNames; 834 835 /// The real profile data reader. 836 InstrProfReaderIndex<HashTableImpl> &Underlying; 837 }; 838 839 bool IndexedInstrProfReader::hasFormat(const MemoryBuffer &DataBuffer) { 840 using namespace support; 841 842 if (DataBuffer.getBufferSize() < 8) 843 return false; 844 uint64_t Magic = 845 endian::read<uint64_t, little, aligned>(DataBuffer.getBufferStart()); 846 // Verify that it's magical. 847 return Magic == IndexedInstrProf::Magic; 848 } 849 850 const unsigned char * 851 IndexedInstrProfReader::readSummary(IndexedInstrProf::ProfVersion Version, 852 const unsigned char *Cur, bool UseCS) { 853 using namespace IndexedInstrProf; 854 using namespace support; 855 856 if (Version >= IndexedInstrProf::Version4) { 857 const IndexedInstrProf::Summary *SummaryInLE = 858 reinterpret_cast<const IndexedInstrProf::Summary *>(Cur); 859 uint64_t NFields = 860 endian::byte_swap<uint64_t, little>(SummaryInLE->NumSummaryFields); 861 uint64_t NEntries = 862 endian::byte_swap<uint64_t, little>(SummaryInLE->NumCutoffEntries); 863 uint32_t SummarySize = 864 IndexedInstrProf::Summary::getSize(NFields, NEntries); 865 std::unique_ptr<IndexedInstrProf::Summary> SummaryData = 866 IndexedInstrProf::allocSummary(SummarySize); 867 868 const uint64_t *Src = reinterpret_cast<const uint64_t *>(SummaryInLE); 869 uint64_t *Dst = reinterpret_cast<uint64_t *>(SummaryData.get()); 870 for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++) 871 Dst[I] = endian::byte_swap<uint64_t, little>(Src[I]); 872 873 SummaryEntryVector DetailedSummary; 874 for (unsigned I = 0; I < SummaryData->NumCutoffEntries; I++) { 875 const IndexedInstrProf::Summary::Entry &Ent = SummaryData->getEntry(I); 876 DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount, 877 Ent.NumBlocks); 878 } 879 std::unique_ptr<llvm::ProfileSummary> &Summary = 880 UseCS ? this->CS_Summary : this->Summary; 881 882 // initialize InstrProfSummary using the SummaryData from disk. 883 Summary = std::make_unique<ProfileSummary>( 884 UseCS ? ProfileSummary::PSK_CSInstr : ProfileSummary::PSK_Instr, 885 DetailedSummary, SummaryData->get(Summary::TotalBlockCount), 886 SummaryData->get(Summary::MaxBlockCount), 887 SummaryData->get(Summary::MaxInternalBlockCount), 888 SummaryData->get(Summary::MaxFunctionCount), 889 SummaryData->get(Summary::TotalNumBlocks), 890 SummaryData->get(Summary::TotalNumFunctions)); 891 return Cur + SummarySize; 892 } else { 893 // The older versions do not support a profile summary. This just computes 894 // an empty summary, which will not result in accurate hot/cold detection. 895 // We would need to call addRecord for all NamedInstrProfRecords to get the 896 // correct summary. However, this version is old (prior to early 2016) and 897 // has not been supporting an accurate summary for several years. 898 InstrProfSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs); 899 Summary = Builder.getSummary(); 900 return Cur; 901 } 902 } 903 904 Error IndexedInstrProfReader::readHeader() { 905 using namespace support; 906 907 const unsigned char *Start = 908 (const unsigned char *)DataBuffer->getBufferStart(); 909 const unsigned char *Cur = Start; 910 if ((const unsigned char *)DataBuffer->getBufferEnd() - Cur < 24) 911 return error(instrprof_error::truncated); 912 913 auto *Header = reinterpret_cast<const IndexedInstrProf::Header *>(Cur); 914 Cur += sizeof(IndexedInstrProf::Header); 915 916 // Check the magic number. 917 uint64_t Magic = endian::byte_swap<uint64_t, little>(Header->Magic); 918 if (Magic != IndexedInstrProf::Magic) 919 return error(instrprof_error::bad_magic); 920 921 // Read the version. 922 uint64_t FormatVersion = endian::byte_swap<uint64_t, little>(Header->Version); 923 if (GET_VERSION(FormatVersion) > 924 IndexedInstrProf::ProfVersion::CurrentVersion) 925 return error(instrprof_error::unsupported_version); 926 927 Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur, 928 /* UseCS */ false); 929 if (FormatVersion & VARIANT_MASK_CSIR_PROF) 930 Cur = readSummary((IndexedInstrProf::ProfVersion)FormatVersion, Cur, 931 /* UseCS */ true); 932 933 // Read the hash type and start offset. 934 IndexedInstrProf::HashT HashType = static_cast<IndexedInstrProf::HashT>( 935 endian::byte_swap<uint64_t, little>(Header->HashType)); 936 if (HashType > IndexedInstrProf::HashT::Last) 937 return error(instrprof_error::unsupported_hash_type); 938 939 uint64_t HashOffset = endian::byte_swap<uint64_t, little>(Header->HashOffset); 940 941 // The rest of the file is an on disk hash table. 942 auto IndexPtr = 943 std::make_unique<InstrProfReaderIndex<OnDiskHashTableImplV3>>( 944 Start + HashOffset, Cur, Start, HashType, FormatVersion); 945 946 // Load the remapping table now if requested. 947 if (RemappingBuffer) { 948 Remapper = std::make_unique< 949 InstrProfReaderItaniumRemapper<OnDiskHashTableImplV3>>( 950 std::move(RemappingBuffer), *IndexPtr); 951 if (Error E = Remapper->populateRemappings()) 952 return E; 953 } else { 954 Remapper = std::make_unique<InstrProfReaderNullRemapper>(*IndexPtr); 955 } 956 Index = std::move(IndexPtr); 957 958 return success(); 959 } 960 961 InstrProfSymtab &IndexedInstrProfReader::getSymtab() { 962 if (Symtab.get()) 963 return *Symtab.get(); 964 965 std::unique_ptr<InstrProfSymtab> NewSymtab = std::make_unique<InstrProfSymtab>(); 966 if (Error E = Index->populateSymtab(*NewSymtab.get())) { 967 consumeError(error(InstrProfError::take(std::move(E)))); 968 } 969 970 Symtab = std::move(NewSymtab); 971 return *Symtab.get(); 972 } 973 974 Expected<InstrProfRecord> 975 IndexedInstrProfReader::getInstrProfRecord(StringRef FuncName, 976 uint64_t FuncHash) { 977 ArrayRef<NamedInstrProfRecord> Data; 978 Error Err = Remapper->getRecords(FuncName, Data); 979 if (Err) 980 return std::move(Err); 981 // Found it. Look for counters with the right hash. 982 for (const NamedInstrProfRecord &I : Data) { 983 // Check for a match and fill the vector if there is one. 984 if (I.Hash == FuncHash) 985 return std::move(I); 986 } 987 return error(instrprof_error::hash_mismatch); 988 } 989 990 Error IndexedInstrProfReader::getFunctionCounts(StringRef FuncName, 991 uint64_t FuncHash, 992 std::vector<uint64_t> &Counts) { 993 Expected<InstrProfRecord> Record = getInstrProfRecord(FuncName, FuncHash); 994 if (Error E = Record.takeError()) 995 return error(std::move(E)); 996 997 Counts = Record.get().Counts; 998 return success(); 999 } 1000 1001 Error IndexedInstrProfReader::readNextRecord(NamedInstrProfRecord &Record) { 1002 ArrayRef<NamedInstrProfRecord> Data; 1003 1004 Error E = Index->getRecords(Data); 1005 if (E) 1006 return error(std::move(E)); 1007 1008 Record = Data[RecordIndex++]; 1009 if (RecordIndex >= Data.size()) { 1010 Index->advanceToNextKey(); 1011 RecordIndex = 0; 1012 } 1013 return success(); 1014 } 1015 1016 void InstrProfReader::accumulateCounts(CountSumOrPercent &Sum, bool IsCS) { 1017 uint64_t NumFuncs = 0; 1018 for (const auto &Func : *this) { 1019 if (isIRLevelProfile()) { 1020 bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash); 1021 if (FuncIsCS != IsCS) 1022 continue; 1023 } 1024 Func.accumulateCounts(Sum); 1025 ++NumFuncs; 1026 } 1027 Sum.NumEntries = NumFuncs; 1028 } 1029