1 //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===// 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 implements the class that reads LLVM sample profiles. It 11 // supports three file formats: text, binary and gcov. 12 // 13 // The textual representation is useful for debugging and testing purposes. The 14 // binary representation is more compact, resulting in smaller file sizes. 15 // 16 // The gcov encoding is the one generated by GCC's AutoFDO profile creation 17 // tool (https://github.com/google/autofdo) 18 // 19 // All three encodings can be used interchangeably as an input sample profile. 20 // 21 //===----------------------------------------------------------------------===// 22 23 #include "llvm/ProfileData/SampleProfReader.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/Support/Debug.h" 27 #include "llvm/Support/ErrorOr.h" 28 #include "llvm/Support/LEB128.h" 29 #include "llvm/Support/LineIterator.h" 30 #include "llvm/Support/MemoryBuffer.h" 31 32 using namespace llvm::sampleprof; 33 using namespace llvm; 34 35 /// \brief Print the samples collected for a function on stream \p OS. 36 /// 37 /// \param OS Stream to emit the output to. 38 void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const { 39 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size() 40 << " sampled lines\n"; 41 for (const auto &SI : BodySamples) { 42 LineLocation Loc = SI.first; 43 const SampleRecord &Sample = SI.second; 44 OS.indent(Indent); 45 OS << "line offset: " << Loc.LineOffset 46 << ", discriminator: " << Loc.Discriminator 47 << ", number of samples: " << Sample.getSamples(); 48 if (Sample.hasCalls()) { 49 OS << ", calls:"; 50 for (const auto &I : Sample.getCallTargets()) 51 OS << " " << I.first() << ":" << I.second; 52 } 53 OS << "\n"; 54 } 55 for (const auto &CS : CallsiteSamples) { 56 CallsiteLocation Loc = CS.first; 57 const FunctionSamples &CalleeSamples = CS.second; 58 OS.indent(Indent); 59 OS << "line offset: " << Loc.LineOffset 60 << ", discriminator: " << Loc.Discriminator 61 << ", inlined callee: " << Loc.CalleeName << ": "; 62 CalleeSamples.print(OS, Indent + 2); 63 } 64 } 65 66 /// \brief Dump the function profile for \p FName. 67 /// 68 /// \param FName Name of the function to print. 69 /// \param OS Stream to emit the output to. 70 void SampleProfileReader::dumpFunctionProfile(StringRef FName, 71 raw_ostream &OS) { 72 OS << "Function: " << FName << ": "; 73 Profiles[FName].print(OS); 74 } 75 76 /// \brief Dump all the function profiles found on stream \p OS. 77 void SampleProfileReader::dump(raw_ostream &OS) { 78 for (const auto &I : Profiles) 79 dumpFunctionProfile(I.getKey(), OS); 80 } 81 82 /// \brief Parse \p Input as function head. 83 /// 84 /// Parse one line of \p Input, and update function name in \p FName, 85 /// function's total sample count in \p NumSamples, function's entry 86 /// count in \p NumHeadSamples. 87 /// 88 /// \returns true if parsing is successful. 89 static bool ParseHead(const StringRef &Input, StringRef &FName, 90 uint64_t &NumSamples, uint64_t &NumHeadSamples) { 91 if (Input[0] == ' ') 92 return false; 93 size_t n2 = Input.rfind(':'); 94 size_t n1 = Input.rfind(':', n2 - 1); 95 FName = Input.substr(0, n1); 96 if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples)) 97 return false; 98 if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples)) 99 return false; 100 return true; 101 } 102 103 104 /// \brief Returns true if line offset \p L is legal (only has 16 bits). 105 static bool isOffsetLegal(unsigned L) { 106 return (L & 0xffff) == L; 107 } 108 109 /// \brief Parse \p Input as line sample. 110 /// 111 /// \param Input input line. 112 /// \param IsCallsite true if the line represents an inlined callsite. 113 /// \param Depth the depth of the inline stack. 114 /// \param NumSamples total samples of the line/inlined callsite. 115 /// \param LineOffset line offset to the start of the function. 116 /// \param Discriminator discriminator of the line. 117 /// \param TargetCountMap map from indirect call target to count. 118 /// 119 /// returns true if parsing is successful. 120 static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth, 121 uint64_t &NumSamples, uint32_t &LineOffset, 122 uint32_t &Discriminator, StringRef &CalleeName, 123 DenseMap<StringRef, uint64_t> &TargetCountMap) { 124 for (Depth = 0; Input[Depth] == ' '; Depth++) 125 ; 126 if (Depth == 0) 127 return false; 128 129 size_t n1 = Input.find(':'); 130 StringRef Loc = Input.substr(Depth, n1 - Depth); 131 size_t n2 = Loc.find('.'); 132 if (n2 == StringRef::npos) { 133 if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset)) 134 return false; 135 Discriminator = 0; 136 } else { 137 if (Loc.substr(0, n2).getAsInteger(10, LineOffset)) 138 return false; 139 if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator)) 140 return false; 141 } 142 143 StringRef Rest = Input.substr(n1 + 2); 144 if (Rest[0] >= '0' && Rest[0] <= '9') { 145 IsCallsite = false; 146 size_t n3 = Rest.find(' '); 147 if (n3 == StringRef::npos) { 148 if (Rest.getAsInteger(10, NumSamples)) 149 return false; 150 } else { 151 if (Rest.substr(0, n3).getAsInteger(10, NumSamples)) 152 return false; 153 } 154 while (n3 != StringRef::npos) { 155 n3 += Rest.substr(n3).find_first_not_of(' '); 156 Rest = Rest.substr(n3); 157 n3 = Rest.find(' '); 158 StringRef pair = Rest; 159 if (n3 != StringRef::npos) { 160 pair = Rest.substr(0, n3); 161 } 162 size_t n4 = pair.find(':'); 163 uint64_t count; 164 if (pair.substr(n4 + 1).getAsInteger(10, count)) 165 return false; 166 TargetCountMap[pair.substr(0, n4)] = count; 167 } 168 } else { 169 IsCallsite = true; 170 size_t n3 = Rest.find_last_of(':'); 171 CalleeName = Rest.substr(0, n3); 172 if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples)) 173 return false; 174 } 175 return true; 176 } 177 178 /// \brief Load samples from a text file. 179 /// 180 /// See the documentation at the top of the file for an explanation of 181 /// the expected format. 182 /// 183 /// \returns true if the file was loaded successfully, false otherwise. 184 std::error_code SampleProfileReaderText::read() { 185 line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#'); 186 187 InlineCallStack InlineStack; 188 189 for (; !LineIt.is_at_eof(); ++LineIt) { 190 if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#') 191 continue; 192 // Read the header of each function. 193 // 194 // Note that for function identifiers we are actually expecting 195 // mangled names, but we may not always get them. This happens when 196 // the compiler decides not to emit the function (e.g., it was inlined 197 // and removed). In this case, the binary will not have the linkage 198 // name for the function, so the profiler will emit the function's 199 // unmangled name, which may contain characters like ':' and '>' in its 200 // name (member functions, templates, etc). 201 // 202 // The only requirement we place on the identifier, then, is that it 203 // should not begin with a number. 204 if ((*LineIt)[0] != ' ') { 205 uint64_t NumSamples, NumHeadSamples; 206 StringRef FName; 207 if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) { 208 reportError(LineIt.line_number(), 209 "Expected 'mangled_name:NUM:NUM', found " + *LineIt); 210 return sampleprof_error::malformed; 211 } 212 Profiles[FName] = FunctionSamples(); 213 FunctionSamples &FProfile = Profiles[FName]; 214 FProfile.addTotalSamples(NumSamples); 215 FProfile.addHeadSamples(NumHeadSamples); 216 InlineStack.clear(); 217 InlineStack.push_back(&FProfile); 218 } else { 219 uint64_t NumSamples; 220 StringRef FName; 221 DenseMap<StringRef, uint64_t> TargetCountMap; 222 bool IsCallsite; 223 uint32_t Depth, LineOffset, Discriminator; 224 if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset, 225 Discriminator, FName, TargetCountMap)) { 226 reportError(LineIt.line_number(), 227 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " + 228 *LineIt); 229 return sampleprof_error::malformed; 230 } 231 if (IsCallsite) { 232 while (InlineStack.size() > Depth) { 233 InlineStack.pop_back(); 234 } 235 FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt( 236 CallsiteLocation(LineOffset, Discriminator, FName)); 237 FSamples.addTotalSamples(NumSamples); 238 InlineStack.push_back(&FSamples); 239 } else { 240 while (InlineStack.size() > Depth) { 241 InlineStack.pop_back(); 242 } 243 FunctionSamples &FProfile = *InlineStack.back(); 244 for (const auto &name_count : TargetCountMap) { 245 FProfile.addCalledTargetSamples(LineOffset, Discriminator, 246 name_count.first, name_count.second); 247 } 248 FProfile.addBodySamples(LineOffset, Discriminator, NumSamples); 249 } 250 } 251 } 252 253 return sampleprof_error::success; 254 } 255 256 template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() { 257 unsigned NumBytesRead = 0; 258 std::error_code EC; 259 uint64_t Val = decodeULEB128(Data, &NumBytesRead); 260 261 if (Val > std::numeric_limits<T>::max()) 262 EC = sampleprof_error::malformed; 263 else if (Data + NumBytesRead > End) 264 EC = sampleprof_error::truncated; 265 else 266 EC = sampleprof_error::success; 267 268 if (EC) { 269 reportError(0, EC.message()); 270 return EC; 271 } 272 273 Data += NumBytesRead; 274 return static_cast<T>(Val); 275 } 276 277 ErrorOr<StringRef> SampleProfileReaderBinary::readString() { 278 std::error_code EC; 279 StringRef Str(reinterpret_cast<const char *>(Data)); 280 if (Data + Str.size() + 1 > End) { 281 EC = sampleprof_error::truncated; 282 reportError(0, EC.message()); 283 return EC; 284 } 285 286 Data += Str.size() + 1; 287 return Str; 288 } 289 290 ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() { 291 std::error_code EC; 292 auto Idx = readNumber<uint32_t>(); 293 if (std::error_code EC = Idx.getError()) 294 return EC; 295 if (*Idx >= NameTable.size()) 296 return sampleprof_error::truncated_name_table; 297 return NameTable[*Idx]; 298 } 299 300 std::error_code 301 SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) { 302 auto NumSamples = readNumber<uint64_t>(); 303 if (std::error_code EC = NumSamples.getError()) 304 return EC; 305 FProfile.addTotalSamples(*NumSamples); 306 307 // Read the samples in the body. 308 auto NumRecords = readNumber<uint32_t>(); 309 if (std::error_code EC = NumRecords.getError()) 310 return EC; 311 312 for (uint32_t I = 0; I < *NumRecords; ++I) { 313 auto LineOffset = readNumber<uint64_t>(); 314 if (std::error_code EC = LineOffset.getError()) 315 return EC; 316 317 if (!isOffsetLegal(*LineOffset)) { 318 return std::error_code(); 319 } 320 321 auto Discriminator = readNumber<uint64_t>(); 322 if (std::error_code EC = Discriminator.getError()) 323 return EC; 324 325 auto NumSamples = readNumber<uint64_t>(); 326 if (std::error_code EC = NumSamples.getError()) 327 return EC; 328 329 auto NumCalls = readNumber<uint32_t>(); 330 if (std::error_code EC = NumCalls.getError()) 331 return EC; 332 333 for (uint32_t J = 0; J < *NumCalls; ++J) { 334 auto CalledFunction(readStringFromTable()); 335 if (std::error_code EC = CalledFunction.getError()) 336 return EC; 337 338 auto CalledFunctionSamples = readNumber<uint64_t>(); 339 if (std::error_code EC = CalledFunctionSamples.getError()) 340 return EC; 341 342 FProfile.addCalledTargetSamples(*LineOffset, *Discriminator, 343 *CalledFunction, *CalledFunctionSamples); 344 } 345 346 FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples); 347 } 348 349 // Read all the samples for inlined function calls. 350 auto NumCallsites = readNumber<uint32_t>(); 351 if (std::error_code EC = NumCallsites.getError()) 352 return EC; 353 354 for (uint32_t J = 0; J < *NumCallsites; ++J) { 355 auto LineOffset = readNumber<uint64_t>(); 356 if (std::error_code EC = LineOffset.getError()) 357 return EC; 358 359 auto Discriminator = readNumber<uint64_t>(); 360 if (std::error_code EC = Discriminator.getError()) 361 return EC; 362 363 auto FName(readStringFromTable()); 364 if (std::error_code EC = FName.getError()) 365 return EC; 366 367 FunctionSamples &CalleeProfile = FProfile.functionSamplesAt( 368 CallsiteLocation(*LineOffset, *Discriminator, *FName)); 369 if (std::error_code EC = readProfile(CalleeProfile)) 370 return EC; 371 } 372 373 return sampleprof_error::success; 374 } 375 376 std::error_code SampleProfileReaderBinary::read() { 377 while (!at_eof()) { 378 auto NumHeadSamples = readNumber<uint64_t>(); 379 if (std::error_code EC = NumHeadSamples.getError()) 380 return EC; 381 382 auto FName(readStringFromTable()); 383 if (std::error_code EC = FName.getError()) 384 return EC; 385 386 Profiles[*FName] = FunctionSamples(); 387 FunctionSamples &FProfile = Profiles[*FName]; 388 389 FProfile.addHeadSamples(*NumHeadSamples); 390 391 if (std::error_code EC = readProfile(FProfile)) 392 return EC; 393 } 394 395 return sampleprof_error::success; 396 } 397 398 std::error_code SampleProfileReaderBinary::readHeader() { 399 Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()); 400 End = Data + Buffer->getBufferSize(); 401 402 // Read and check the magic identifier. 403 auto Magic = readNumber<uint64_t>(); 404 if (std::error_code EC = Magic.getError()) 405 return EC; 406 else if (*Magic != SPMagic()) 407 return sampleprof_error::bad_magic; 408 409 // Read the version number. 410 auto Version = readNumber<uint64_t>(); 411 if (std::error_code EC = Version.getError()) 412 return EC; 413 else if (*Version != SPVersion()) 414 return sampleprof_error::unsupported_version; 415 416 // Read the name table. 417 auto Size = readNumber<uint32_t>(); 418 if (std::error_code EC = Size.getError()) 419 return EC; 420 NameTable.reserve(*Size); 421 for (uint32_t I = 0; I < *Size; ++I) { 422 auto Name(readString()); 423 if (std::error_code EC = Name.getError()) 424 return EC; 425 NameTable.push_back(*Name); 426 } 427 428 return sampleprof_error::success; 429 } 430 431 bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) { 432 const uint8_t *Data = 433 reinterpret_cast<const uint8_t *>(Buffer.getBufferStart()); 434 uint64_t Magic = decodeULEB128(Data); 435 return Magic == SPMagic(); 436 } 437 438 std::error_code SampleProfileReaderGCC::skipNextWord() { 439 uint32_t dummy; 440 if (!GcovBuffer.readInt(dummy)) 441 return sampleprof_error::truncated; 442 return sampleprof_error::success; 443 } 444 445 template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() { 446 if (sizeof(T) <= sizeof(uint32_t)) { 447 uint32_t Val; 448 if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max()) 449 return static_cast<T>(Val); 450 } else if (sizeof(T) <= sizeof(uint64_t)) { 451 uint64_t Val; 452 if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max()) 453 return static_cast<T>(Val); 454 } 455 456 std::error_code EC = sampleprof_error::malformed; 457 reportError(0, EC.message()); 458 return EC; 459 } 460 461 ErrorOr<StringRef> SampleProfileReaderGCC::readString() { 462 StringRef Str; 463 if (!GcovBuffer.readString(Str)) 464 return sampleprof_error::truncated; 465 return Str; 466 } 467 468 std::error_code SampleProfileReaderGCC::readHeader() { 469 // Read the magic identifier. 470 if (!GcovBuffer.readGCDAFormat()) 471 return sampleprof_error::unrecognized_format; 472 473 // Read the version number. Note - the GCC reader does not validate this 474 // version, but the profile creator generates v704. 475 GCOV::GCOVVersion version; 476 if (!GcovBuffer.readGCOVVersion(version)) 477 return sampleprof_error::unrecognized_format; 478 479 if (version != GCOV::V704) 480 return sampleprof_error::unsupported_version; 481 482 // Skip the empty integer. 483 if (std::error_code EC = skipNextWord()) 484 return EC; 485 486 return sampleprof_error::success; 487 } 488 489 std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) { 490 uint32_t Tag; 491 if (!GcovBuffer.readInt(Tag)) 492 return sampleprof_error::truncated; 493 494 if (Tag != Expected) 495 return sampleprof_error::malformed; 496 497 if (std::error_code EC = skipNextWord()) 498 return EC; 499 500 return sampleprof_error::success; 501 } 502 503 std::error_code SampleProfileReaderGCC::readNameTable() { 504 if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames)) 505 return EC; 506 507 uint32_t Size; 508 if (!GcovBuffer.readInt(Size)) 509 return sampleprof_error::truncated; 510 511 for (uint32_t I = 0; I < Size; ++I) { 512 StringRef Str; 513 if (!GcovBuffer.readString(Str)) 514 return sampleprof_error::truncated; 515 Names.push_back(Str); 516 } 517 518 return sampleprof_error::success; 519 } 520 521 std::error_code SampleProfileReaderGCC::readFunctionProfiles() { 522 if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction)) 523 return EC; 524 525 uint32_t NumFunctions; 526 if (!GcovBuffer.readInt(NumFunctions)) 527 return sampleprof_error::truncated; 528 529 InlineCallStack Stack; 530 for (uint32_t I = 0; I < NumFunctions; ++I) 531 if (std::error_code EC = readOneFunctionProfile(Stack, true, 0)) 532 return EC; 533 534 return sampleprof_error::success; 535 } 536 537 std::error_code SampleProfileReaderGCC::readOneFunctionProfile( 538 const InlineCallStack &InlineStack, bool Update, uint32_t Offset) { 539 uint64_t HeadCount = 0; 540 if (InlineStack.size() == 0) 541 if (!GcovBuffer.readInt64(HeadCount)) 542 return sampleprof_error::truncated; 543 544 uint32_t NameIdx; 545 if (!GcovBuffer.readInt(NameIdx)) 546 return sampleprof_error::truncated; 547 548 StringRef Name(Names[NameIdx]); 549 550 uint32_t NumPosCounts; 551 if (!GcovBuffer.readInt(NumPosCounts)) 552 return sampleprof_error::truncated; 553 554 uint32_t NumCallsites; 555 if (!GcovBuffer.readInt(NumCallsites)) 556 return sampleprof_error::truncated; 557 558 FunctionSamples *FProfile = nullptr; 559 if (InlineStack.size() == 0) { 560 // If this is a top function that we have already processed, do not 561 // update its profile again. This happens in the presence of 562 // function aliases. Since these aliases share the same function 563 // body, there will be identical replicated profiles for the 564 // original function. In this case, we simply not bother updating 565 // the profile of the original function. 566 FProfile = &Profiles[Name]; 567 FProfile->addHeadSamples(HeadCount); 568 if (FProfile->getTotalSamples() > 0) 569 Update = false; 570 } else { 571 // Otherwise, we are reading an inlined instance. The top of the 572 // inline stack contains the profile of the caller. Insert this 573 // callee in the caller's CallsiteMap. 574 FunctionSamples *CallerProfile = InlineStack.front(); 575 uint32_t LineOffset = Offset >> 16; 576 uint32_t Discriminator = Offset & 0xffff; 577 FProfile = &CallerProfile->functionSamplesAt( 578 CallsiteLocation(LineOffset, Discriminator, Name)); 579 } 580 581 for (uint32_t I = 0; I < NumPosCounts; ++I) { 582 uint32_t Offset; 583 if (!GcovBuffer.readInt(Offset)) 584 return sampleprof_error::truncated; 585 586 uint32_t NumTargets; 587 if (!GcovBuffer.readInt(NumTargets)) 588 return sampleprof_error::truncated; 589 590 uint64_t Count; 591 if (!GcovBuffer.readInt64(Count)) 592 return sampleprof_error::truncated; 593 594 // The line location is encoded in the offset as: 595 // high 16 bits: line offset to the start of the function. 596 // low 16 bits: discriminator. 597 uint32_t LineOffset = Offset >> 16; 598 uint32_t Discriminator = Offset & 0xffff; 599 600 InlineCallStack NewStack; 601 NewStack.push_back(FProfile); 602 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end()); 603 if (Update) { 604 // Walk up the inline stack, adding the samples on this line to 605 // the total sample count of the callers in the chain. 606 for (auto CallerProfile : NewStack) 607 CallerProfile->addTotalSamples(Count); 608 609 // Update the body samples for the current profile. 610 FProfile->addBodySamples(LineOffset, Discriminator, Count); 611 } 612 613 // Process the list of functions called at an indirect call site. 614 // These are all the targets that a function pointer (or virtual 615 // function) resolved at runtime. 616 for (uint32_t J = 0; J < NumTargets; J++) { 617 uint32_t HistVal; 618 if (!GcovBuffer.readInt(HistVal)) 619 return sampleprof_error::truncated; 620 621 if (HistVal != HIST_TYPE_INDIR_CALL_TOPN) 622 return sampleprof_error::malformed; 623 624 uint64_t TargetIdx; 625 if (!GcovBuffer.readInt64(TargetIdx)) 626 return sampleprof_error::truncated; 627 StringRef TargetName(Names[TargetIdx]); 628 629 uint64_t TargetCount; 630 if (!GcovBuffer.readInt64(TargetCount)) 631 return sampleprof_error::truncated; 632 633 if (Update) { 634 FunctionSamples &TargetProfile = Profiles[TargetName]; 635 TargetProfile.addCalledTargetSamples(LineOffset, Discriminator, 636 TargetName, TargetCount); 637 } 638 } 639 } 640 641 // Process all the inlined callers into the current function. These 642 // are all the callsites that were inlined into this function. 643 for (uint32_t I = 0; I < NumCallsites; I++) { 644 // The offset is encoded as: 645 // high 16 bits: line offset to the start of the function. 646 // low 16 bits: discriminator. 647 uint32_t Offset; 648 if (!GcovBuffer.readInt(Offset)) 649 return sampleprof_error::truncated; 650 InlineCallStack NewStack; 651 NewStack.push_back(FProfile); 652 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end()); 653 if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset)) 654 return EC; 655 } 656 657 return sampleprof_error::success; 658 } 659 660 /// \brief Read a GCC AutoFDO profile. 661 /// 662 /// This format is generated by the Linux Perf conversion tool at 663 /// https://github.com/google/autofdo. 664 std::error_code SampleProfileReaderGCC::read() { 665 // Read the string table. 666 if (std::error_code EC = readNameTable()) 667 return EC; 668 669 // Read the source profile. 670 if (std::error_code EC = readFunctionProfiles()) 671 return EC; 672 673 return sampleprof_error::success; 674 } 675 676 bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) { 677 StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart())); 678 return Magic == "adcg*704"; 679 } 680 681 /// \brief Prepare a memory buffer for the contents of \p Filename. 682 /// 683 /// \returns an error code indicating the status of the buffer. 684 static ErrorOr<std::unique_ptr<MemoryBuffer>> 685 setupMemoryBuffer(std::string Filename) { 686 auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename); 687 if (std::error_code EC = BufferOrErr.getError()) 688 return EC; 689 auto Buffer = std::move(BufferOrErr.get()); 690 691 // Sanity check the file. 692 if (Buffer->getBufferSize() > std::numeric_limits<uint32_t>::max()) 693 return sampleprof_error::too_large; 694 695 return std::move(Buffer); 696 } 697 698 /// \brief Create a sample profile reader based on the format of the input file. 699 /// 700 /// \param Filename The file to open. 701 /// 702 /// \param Reader The reader to instantiate according to \p Filename's format. 703 /// 704 /// \param C The LLVM context to use to emit diagnostics. 705 /// 706 /// \returns an error code indicating the status of the created reader. 707 ErrorOr<std::unique_ptr<SampleProfileReader>> 708 SampleProfileReader::create(StringRef Filename, LLVMContext &C) { 709 auto BufferOrError = setupMemoryBuffer(Filename); 710 if (std::error_code EC = BufferOrError.getError()) 711 return EC; 712 713 auto Buffer = std::move(BufferOrError.get()); 714 std::unique_ptr<SampleProfileReader> Reader; 715 if (SampleProfileReaderBinary::hasFormat(*Buffer)) 716 Reader.reset(new SampleProfileReaderBinary(std::move(Buffer), C)); 717 else if (SampleProfileReaderGCC::hasFormat(*Buffer)) 718 Reader.reset(new SampleProfileReaderGCC(std::move(Buffer), C)); 719 else 720 Reader.reset(new SampleProfileReaderText(std::move(Buffer), C)); 721 722 if (std::error_code EC = Reader->readHeader()) 723 return EC; 724 725 return std::move(Reader); 726 } 727