1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===// 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 // llvm-profdata merges .profdata files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/SmallSet.h" 14 #include "llvm/ADT/SmallVector.h" 15 #include "llvm/ADT/StringRef.h" 16 #include "llvm/IR/LLVMContext.h" 17 #include "llvm/ProfileData/InstrProfReader.h" 18 #include "llvm/ProfileData/InstrProfWriter.h" 19 #include "llvm/ProfileData/ProfileCommon.h" 20 #include "llvm/ProfileData/SampleProfReader.h" 21 #include "llvm/ProfileData/SampleProfWriter.h" 22 #include "llvm/Support/CommandLine.h" 23 #include "llvm/Support/Discriminator.h" 24 #include "llvm/Support/Errc.h" 25 #include "llvm/Support/FileSystem.h" 26 #include "llvm/Support/Format.h" 27 #include "llvm/Support/FormattedStream.h" 28 #include "llvm/Support/InitLLVM.h" 29 #include "llvm/Support/MemoryBuffer.h" 30 #include "llvm/Support/Path.h" 31 #include "llvm/Support/ThreadPool.h" 32 #include "llvm/Support/Threading.h" 33 #include "llvm/Support/WithColor.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include <algorithm> 36 37 using namespace llvm; 38 39 enum ProfileFormat { 40 PF_None = 0, 41 PF_Text, 42 PF_Compact_Binary, 43 PF_Ext_Binary, 44 PF_GCC, 45 PF_Binary 46 }; 47 48 static void warn(Twine Message, std::string Whence = "", 49 std::string Hint = "") { 50 WithColor::warning(); 51 if (!Whence.empty()) 52 errs() << Whence << ": "; 53 errs() << Message << "\n"; 54 if (!Hint.empty()) 55 WithColor::note() << Hint << "\n"; 56 } 57 58 static void warn(Error E, StringRef Whence = "") { 59 if (E.isA<InstrProfError>()) { 60 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) { 61 warn(IPE.message(), std::string(Whence), std::string("")); 62 }); 63 } 64 } 65 66 static void exitWithError(Twine Message, std::string Whence = "", 67 std::string Hint = "") { 68 WithColor::error(); 69 if (!Whence.empty()) 70 errs() << Whence << ": "; 71 errs() << Message << "\n"; 72 if (!Hint.empty()) 73 WithColor::note() << Hint << "\n"; 74 ::exit(1); 75 } 76 77 static void exitWithError(Error E, StringRef Whence = "") { 78 if (E.isA<InstrProfError>()) { 79 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) { 80 instrprof_error instrError = IPE.get(); 81 StringRef Hint = ""; 82 if (instrError == instrprof_error::unrecognized_format) { 83 // Hint for common error of forgetting --sample for sample profiles. 84 Hint = "Perhaps you forgot to use the --sample option?"; 85 } 86 exitWithError(IPE.message(), std::string(Whence), std::string(Hint)); 87 }); 88 } 89 90 exitWithError(toString(std::move(E)), std::string(Whence)); 91 } 92 93 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") { 94 exitWithError(EC.message(), std::string(Whence)); 95 } 96 97 namespace { 98 enum ProfileKinds { instr, sample }; 99 enum FailureMode { failIfAnyAreInvalid, failIfAllAreInvalid }; 100 } 101 102 static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC, 103 StringRef Whence = "") { 104 if (FailMode == failIfAnyAreInvalid) 105 exitWithErrorCode(EC, Whence); 106 else 107 warn(EC.message(), std::string(Whence)); 108 } 109 110 static void handleMergeWriterError(Error E, StringRef WhenceFile = "", 111 StringRef WhenceFunction = "", 112 bool ShowHint = true) { 113 if (!WhenceFile.empty()) 114 errs() << WhenceFile << ": "; 115 if (!WhenceFunction.empty()) 116 errs() << WhenceFunction << ": "; 117 118 auto IPE = instrprof_error::success; 119 E = handleErrors(std::move(E), 120 [&IPE](std::unique_ptr<InstrProfError> E) -> Error { 121 IPE = E->get(); 122 return Error(std::move(E)); 123 }); 124 errs() << toString(std::move(E)) << "\n"; 125 126 if (ShowHint) { 127 StringRef Hint = ""; 128 if (IPE != instrprof_error::success) { 129 switch (IPE) { 130 case instrprof_error::hash_mismatch: 131 case instrprof_error::count_mismatch: 132 case instrprof_error::value_site_count_mismatch: 133 Hint = "Make sure that all profile data to be merged is generated " 134 "from the same binary."; 135 break; 136 default: 137 break; 138 } 139 } 140 141 if (!Hint.empty()) 142 errs() << Hint << "\n"; 143 } 144 } 145 146 namespace { 147 /// A remapper from original symbol names to new symbol names based on a file 148 /// containing a list of mappings from old name to new name. 149 class SymbolRemapper { 150 std::unique_ptr<MemoryBuffer> File; 151 DenseMap<StringRef, StringRef> RemappingTable; 152 153 public: 154 /// Build a SymbolRemapper from a file containing a list of old/new symbols. 155 static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) { 156 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile); 157 if (!BufOrError) 158 exitWithErrorCode(BufOrError.getError(), InputFile); 159 160 auto Remapper = std::make_unique<SymbolRemapper>(); 161 Remapper->File = std::move(BufOrError.get()); 162 163 for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#'); 164 !LineIt.is_at_eof(); ++LineIt) { 165 std::pair<StringRef, StringRef> Parts = LineIt->split(' '); 166 if (Parts.first.empty() || Parts.second.empty() || 167 Parts.second.count(' ')) { 168 exitWithError("unexpected line in remapping file", 169 (InputFile + ":" + Twine(LineIt.line_number())).str(), 170 "expected 'old_symbol new_symbol'"); 171 } 172 Remapper->RemappingTable.insert(Parts); 173 } 174 return Remapper; 175 } 176 177 /// Attempt to map the given old symbol into a new symbol. 178 /// 179 /// \return The new symbol, or \p Name if no such symbol was found. 180 StringRef operator()(StringRef Name) { 181 StringRef New = RemappingTable.lookup(Name); 182 return New.empty() ? Name : New; 183 } 184 }; 185 } 186 187 struct WeightedFile { 188 std::string Filename; 189 uint64_t Weight; 190 }; 191 typedef SmallVector<WeightedFile, 5> WeightedFileVector; 192 193 /// Keep track of merged data and reported errors. 194 struct WriterContext { 195 std::mutex Lock; 196 InstrProfWriter Writer; 197 std::vector<std::pair<Error, std::string>> Errors; 198 std::mutex &ErrLock; 199 SmallSet<instrprof_error, 4> &WriterErrorCodes; 200 201 WriterContext(bool IsSparse, std::mutex &ErrLock, 202 SmallSet<instrprof_error, 4> &WriterErrorCodes) 203 : Lock(), Writer(IsSparse), Errors(), ErrLock(ErrLock), 204 WriterErrorCodes(WriterErrorCodes) {} 205 }; 206 207 /// Computer the overlap b/w profile BaseFilename and TestFileName, 208 /// and store the program level result to Overlap. 209 static void overlapInput(const std::string &BaseFilename, 210 const std::string &TestFilename, WriterContext *WC, 211 OverlapStats &Overlap, 212 const OverlapFuncFilters &FuncFilter, 213 raw_fd_ostream &OS, bool IsCS) { 214 auto ReaderOrErr = InstrProfReader::create(TestFilename); 215 if (Error E = ReaderOrErr.takeError()) { 216 // Skip the empty profiles by returning sliently. 217 instrprof_error IPE = InstrProfError::take(std::move(E)); 218 if (IPE != instrprof_error::empty_raw_profile) 219 WC->Errors.emplace_back(make_error<InstrProfError>(IPE), TestFilename); 220 return; 221 } 222 223 auto Reader = std::move(ReaderOrErr.get()); 224 for (auto &I : *Reader) { 225 OverlapStats FuncOverlap(OverlapStats::FunctionLevel); 226 FuncOverlap.setFuncInfo(I.Name, I.Hash); 227 228 WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter); 229 FuncOverlap.dump(OS); 230 } 231 } 232 233 /// Load an input into a writer context. 234 static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper, 235 WriterContext *WC) { 236 std::unique_lock<std::mutex> CtxGuard{WC->Lock}; 237 238 // Copy the filename, because llvm::ThreadPool copied the input "const 239 // WeightedFile &" by value, making a reference to the filename within it 240 // invalid outside of this packaged task. 241 std::string Filename = Input.Filename; 242 243 auto ReaderOrErr = InstrProfReader::create(Input.Filename); 244 if (Error E = ReaderOrErr.takeError()) { 245 // Skip the empty profiles by returning sliently. 246 instrprof_error IPE = InstrProfError::take(std::move(E)); 247 if (IPE != instrprof_error::empty_raw_profile) 248 WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename); 249 return; 250 } 251 252 auto Reader = std::move(ReaderOrErr.get()); 253 bool IsIRProfile = Reader->isIRLevelProfile(); 254 bool HasCSIRProfile = Reader->hasCSIRLevelProfile(); 255 if (Error E = WC->Writer.setIsIRLevelProfile(IsIRProfile, HasCSIRProfile)) { 256 consumeError(std::move(E)); 257 WC->Errors.emplace_back( 258 make_error<StringError>( 259 "Merge IR generated profile with Clang generated profile.", 260 std::error_code()), 261 Filename); 262 return; 263 } 264 WC->Writer.setInstrEntryBBEnabled(Reader->instrEntryBBEnabled()); 265 266 for (auto &I : *Reader) { 267 if (Remapper) 268 I.Name = (*Remapper)(I.Name); 269 const StringRef FuncName = I.Name; 270 bool Reported = false; 271 WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) { 272 if (Reported) { 273 consumeError(std::move(E)); 274 return; 275 } 276 Reported = true; 277 // Only show hint the first time an error occurs. 278 instrprof_error IPE = InstrProfError::take(std::move(E)); 279 std::unique_lock<std::mutex> ErrGuard{WC->ErrLock}; 280 bool firstTime = WC->WriterErrorCodes.insert(IPE).second; 281 handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename, 282 FuncName, firstTime); 283 }); 284 } 285 if (Reader->hasError()) 286 if (Error E = Reader->getError()) 287 WC->Errors.emplace_back(std::move(E), Filename); 288 } 289 290 /// Merge the \p Src writer context into \p Dst. 291 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) { 292 for (auto &ErrorPair : Src->Errors) 293 Dst->Errors.push_back(std::move(ErrorPair)); 294 Src->Errors.clear(); 295 296 Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) { 297 instrprof_error IPE = InstrProfError::take(std::move(E)); 298 std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock}; 299 bool firstTime = Dst->WriterErrorCodes.insert(IPE).second; 300 if (firstTime) 301 warn(toString(make_error<InstrProfError>(IPE))); 302 }); 303 } 304 305 static void writeInstrProfile(StringRef OutputFilename, 306 ProfileFormat OutputFormat, 307 InstrProfWriter &Writer) { 308 std::error_code EC; 309 raw_fd_ostream Output(OutputFilename.data(), EC, 310 OutputFormat == PF_Text ? sys::fs::OF_TextWithCRLF 311 : sys::fs::OF_None); 312 if (EC) 313 exitWithErrorCode(EC, OutputFilename); 314 315 if (OutputFormat == PF_Text) { 316 if (Error E = Writer.writeText(Output)) 317 warn(std::move(E)); 318 } else { 319 if (Error E = Writer.write(Output)) 320 warn(std::move(E)); 321 } 322 } 323 324 static void mergeInstrProfile(const WeightedFileVector &Inputs, 325 SymbolRemapper *Remapper, 326 StringRef OutputFilename, 327 ProfileFormat OutputFormat, bool OutputSparse, 328 unsigned NumThreads, FailureMode FailMode) { 329 if (OutputFilename.compare("-") == 0) 330 exitWithError("Cannot write indexed profdata format to stdout."); 331 332 if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary && 333 OutputFormat != PF_Ext_Binary && OutputFormat != PF_Text) 334 exitWithError("Unknown format is specified."); 335 336 std::mutex ErrorLock; 337 SmallSet<instrprof_error, 4> WriterErrorCodes; 338 339 // If NumThreads is not specified, auto-detect a good default. 340 if (NumThreads == 0) 341 NumThreads = std::min(hardware_concurrency().compute_thread_count(), 342 unsigned((Inputs.size() + 1) / 2)); 343 // FIXME: There's a bug here, where setting NumThreads = Inputs.size() fails 344 // the merge_empty_profile.test because the InstrProfWriter.ProfileKind isn't 345 // merged, thus the emitted file ends up with a PF_Unknown kind. 346 347 // Initialize the writer contexts. 348 SmallVector<std::unique_ptr<WriterContext>, 4> Contexts; 349 for (unsigned I = 0; I < NumThreads; ++I) 350 Contexts.emplace_back(std::make_unique<WriterContext>( 351 OutputSparse, ErrorLock, WriterErrorCodes)); 352 353 if (NumThreads == 1) { 354 for (const auto &Input : Inputs) 355 loadInput(Input, Remapper, Contexts[0].get()); 356 } else { 357 ThreadPool Pool(hardware_concurrency(NumThreads)); 358 359 // Load the inputs in parallel (N/NumThreads serial steps). 360 unsigned Ctx = 0; 361 for (const auto &Input : Inputs) { 362 Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get()); 363 Ctx = (Ctx + 1) % NumThreads; 364 } 365 Pool.wait(); 366 367 // Merge the writer contexts together (~ lg(NumThreads) serial steps). 368 unsigned Mid = Contexts.size() / 2; 369 unsigned End = Contexts.size(); 370 assert(Mid > 0 && "Expected more than one context"); 371 do { 372 for (unsigned I = 0; I < Mid; ++I) 373 Pool.async(mergeWriterContexts, Contexts[I].get(), 374 Contexts[I + Mid].get()); 375 Pool.wait(); 376 if (End & 1) { 377 Pool.async(mergeWriterContexts, Contexts[0].get(), 378 Contexts[End - 1].get()); 379 Pool.wait(); 380 } 381 End = Mid; 382 Mid /= 2; 383 } while (Mid > 0); 384 } 385 386 // Handle deferred errors encountered during merging. If the number of errors 387 // is equal to the number of inputs the merge failed. 388 unsigned NumErrors = 0; 389 for (std::unique_ptr<WriterContext> &WC : Contexts) { 390 for (auto &ErrorPair : WC->Errors) { 391 ++NumErrors; 392 warn(toString(std::move(ErrorPair.first)), ErrorPair.second); 393 } 394 } 395 if (NumErrors == Inputs.size() || 396 (NumErrors > 0 && FailMode == failIfAnyAreInvalid)) 397 exitWithError("No profiles could be merged."); 398 399 writeInstrProfile(OutputFilename, OutputFormat, Contexts[0]->Writer); 400 } 401 402 /// The profile entry for a function in instrumentation profile. 403 struct InstrProfileEntry { 404 uint64_t MaxCount = 0; 405 float ZeroCounterRatio = 0.0; 406 InstrProfRecord *ProfRecord; 407 InstrProfileEntry(InstrProfRecord *Record); 408 InstrProfileEntry() = default; 409 }; 410 411 InstrProfileEntry::InstrProfileEntry(InstrProfRecord *Record) { 412 ProfRecord = Record; 413 uint64_t CntNum = Record->Counts.size(); 414 uint64_t ZeroCntNum = 0; 415 for (size_t I = 0; I < CntNum; ++I) { 416 MaxCount = std::max(MaxCount, Record->Counts[I]); 417 ZeroCntNum += !Record->Counts[I]; 418 } 419 ZeroCounterRatio = (float)ZeroCntNum / CntNum; 420 } 421 422 /// Either set all the counters in the instr profile entry \p IFE to -1 423 /// in order to drop the profile or scale up the counters in \p IFP to 424 /// be above hot threshold. We use the ratio of zero counters in the 425 /// profile of a function to decide the profile is helpful or harmful 426 /// for performance, and to choose whether to scale up or drop it. 427 static void updateInstrProfileEntry(InstrProfileEntry &IFE, 428 uint64_t HotInstrThreshold, 429 float ZeroCounterThreshold) { 430 InstrProfRecord *ProfRecord = IFE.ProfRecord; 431 if (!IFE.MaxCount || IFE.ZeroCounterRatio > ZeroCounterThreshold) { 432 // If all or most of the counters of the function are zero, the 433 // profile is unaccountable and shuld be dropped. Reset all the 434 // counters to be -1 and PGO profile-use will drop the profile. 435 // All counters being -1 also implies that the function is hot so 436 // PGO profile-use will also set the entry count metadata to be 437 // above hot threshold. 438 for (size_t I = 0; I < ProfRecord->Counts.size(); ++I) 439 ProfRecord->Counts[I] = -1; 440 return; 441 } 442 443 // Scale up the MaxCount to be multiple times above hot threshold. 444 const unsigned MultiplyFactor = 3; 445 uint64_t Numerator = HotInstrThreshold * MultiplyFactor; 446 uint64_t Denominator = IFE.MaxCount; 447 ProfRecord->scale(Numerator, Denominator, [&](instrprof_error E) { 448 warn(toString(make_error<InstrProfError>(E))); 449 }); 450 } 451 452 const uint64_t ColdPercentileIdx = 15; 453 const uint64_t HotPercentileIdx = 11; 454 455 using sampleprof::FSDiscriminatorPass; 456 457 // Internal options to set FSDiscriminatorPass. Used in merge and show 458 // commands. 459 static cl::opt<FSDiscriminatorPass> FSDiscriminatorPassOption( 460 "fs-discriminator-pass", cl::init(PassLast), cl::Hidden, 461 cl::desc("Zero out the discriminator bits for the FS discrimiantor " 462 "pass beyond this value. The enum values are defined in " 463 "Support/Discriminator.h"), 464 cl::values(clEnumVal(Base, "Use base discriminators only"), 465 clEnumVal(Pass1, "Use base and pass 1 discriminators"), 466 clEnumVal(Pass2, "Use base and pass 1-2 discriminators"), 467 clEnumVal(Pass3, "Use base and pass 1-3 discriminators"), 468 clEnumVal(PassLast, "Use all discriminator bits (default)"))); 469 470 static unsigned getDiscriminatorMask() { 471 return getN1Bits(getFSPassBitEnd(FSDiscriminatorPassOption.getValue())); 472 } 473 474 /// Adjust the instr profile in \p WC based on the sample profile in 475 /// \p Reader. 476 static void 477 adjustInstrProfile(std::unique_ptr<WriterContext> &WC, 478 std::unique_ptr<sampleprof::SampleProfileReader> &Reader, 479 unsigned SupplMinSizeThreshold, float ZeroCounterThreshold, 480 unsigned InstrProfColdThreshold) { 481 // Function to its entry in instr profile. 482 StringMap<InstrProfileEntry> InstrProfileMap; 483 InstrProfSummaryBuilder IPBuilder(ProfileSummaryBuilder::DefaultCutoffs); 484 for (auto &PD : WC->Writer.getProfileData()) { 485 // Populate IPBuilder. 486 for (const auto &PDV : PD.getValue()) { 487 InstrProfRecord Record = PDV.second; 488 IPBuilder.addRecord(Record); 489 } 490 491 // If a function has multiple entries in instr profile, skip it. 492 if (PD.getValue().size() != 1) 493 continue; 494 495 // Initialize InstrProfileMap. 496 InstrProfRecord *R = &PD.getValue().begin()->second; 497 InstrProfileMap[PD.getKey()] = InstrProfileEntry(R); 498 } 499 500 ProfileSummary InstrPS = *IPBuilder.getSummary(); 501 ProfileSummary SamplePS = Reader->getSummary(); 502 503 // Compute cold thresholds for instr profile and sample profile. 504 uint64_t ColdSampleThreshold = 505 ProfileSummaryBuilder::getEntryForPercentile( 506 SamplePS.getDetailedSummary(), 507 ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx]) 508 .MinCount; 509 uint64_t HotInstrThreshold = 510 ProfileSummaryBuilder::getEntryForPercentile( 511 InstrPS.getDetailedSummary(), 512 ProfileSummaryBuilder::DefaultCutoffs[HotPercentileIdx]) 513 .MinCount; 514 uint64_t ColdInstrThreshold = 515 InstrProfColdThreshold 516 ? InstrProfColdThreshold 517 : ProfileSummaryBuilder::getEntryForPercentile( 518 InstrPS.getDetailedSummary(), 519 ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx]) 520 .MinCount; 521 522 // Find hot/warm functions in sample profile which is cold in instr profile 523 // and adjust the profiles of those functions in the instr profile. 524 for (const auto &PD : Reader->getProfiles()) { 525 StringRef FName = PD.getKey(); 526 const sampleprof::FunctionSamples &FS = PD.getValue(); 527 auto It = InstrProfileMap.find(FName); 528 if (FS.getHeadSamples() > ColdSampleThreshold && 529 It != InstrProfileMap.end() && 530 It->second.MaxCount <= ColdInstrThreshold && 531 FS.getBodySamples().size() >= SupplMinSizeThreshold) { 532 updateInstrProfileEntry(It->second, HotInstrThreshold, 533 ZeroCounterThreshold); 534 } 535 } 536 } 537 538 /// The main function to supplement instr profile with sample profile. 539 /// \Inputs contains the instr profile. \p SampleFilename specifies the 540 /// sample profile. \p OutputFilename specifies the output profile name. 541 /// \p OutputFormat specifies the output profile format. \p OutputSparse 542 /// specifies whether to generate sparse profile. \p SupplMinSizeThreshold 543 /// specifies the minimal size for the functions whose profile will be 544 /// adjusted. \p ZeroCounterThreshold is the threshold to check whether 545 /// a function contains too many zero counters and whether its profile 546 /// should be dropped. \p InstrProfColdThreshold is the user specified 547 /// cold threshold which will override the cold threshold got from the 548 /// instr profile summary. 549 static void supplementInstrProfile( 550 const WeightedFileVector &Inputs, StringRef SampleFilename, 551 StringRef OutputFilename, ProfileFormat OutputFormat, bool OutputSparse, 552 unsigned SupplMinSizeThreshold, float ZeroCounterThreshold, 553 unsigned InstrProfColdThreshold) { 554 if (OutputFilename.compare("-") == 0) 555 exitWithError("Cannot write indexed profdata format to stdout."); 556 if (Inputs.size() != 1) 557 exitWithError("Expect one input to be an instr profile."); 558 if (Inputs[0].Weight != 1) 559 exitWithError("Expect instr profile doesn't have weight."); 560 561 StringRef InstrFilename = Inputs[0].Filename; 562 563 // Read sample profile. 564 LLVMContext Context; 565 auto ReaderOrErr = sampleprof::SampleProfileReader::create( 566 SampleFilename.str(), Context, FSDiscriminatorPassOption); 567 if (std::error_code EC = ReaderOrErr.getError()) 568 exitWithErrorCode(EC, SampleFilename); 569 auto Reader = std::move(ReaderOrErr.get()); 570 if (std::error_code EC = Reader->read()) 571 exitWithErrorCode(EC, SampleFilename); 572 573 // Read instr profile. 574 std::mutex ErrorLock; 575 SmallSet<instrprof_error, 4> WriterErrorCodes; 576 auto WC = std::make_unique<WriterContext>(OutputSparse, ErrorLock, 577 WriterErrorCodes); 578 loadInput(Inputs[0], nullptr, WC.get()); 579 if (WC->Errors.size() > 0) 580 exitWithError(std::move(WC->Errors[0].first), InstrFilename); 581 582 adjustInstrProfile(WC, Reader, SupplMinSizeThreshold, ZeroCounterThreshold, 583 InstrProfColdThreshold); 584 writeInstrProfile(OutputFilename, OutputFormat, WC->Writer); 585 } 586 587 /// Make a copy of the given function samples with all symbol names remapped 588 /// by the provided symbol remapper. 589 static sampleprof::FunctionSamples 590 remapSamples(const sampleprof::FunctionSamples &Samples, 591 SymbolRemapper &Remapper, sampleprof_error &Error) { 592 sampleprof::FunctionSamples Result; 593 Result.setName(Remapper(Samples.getName())); 594 Result.addTotalSamples(Samples.getTotalSamples()); 595 Result.addHeadSamples(Samples.getHeadSamples()); 596 for (const auto &BodySample : Samples.getBodySamples()) { 597 uint32_t MaskedDiscriminator = 598 BodySample.first.Discriminator & getDiscriminatorMask(); 599 Result.addBodySamples(BodySample.first.LineOffset, MaskedDiscriminator, 600 BodySample.second.getSamples()); 601 for (const auto &Target : BodySample.second.getCallTargets()) { 602 Result.addCalledTargetSamples(BodySample.first.LineOffset, 603 MaskedDiscriminator, 604 Remapper(Target.first()), Target.second); 605 } 606 } 607 for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) { 608 sampleprof::FunctionSamplesMap &Target = 609 Result.functionSamplesAt(CallsiteSamples.first); 610 for (const auto &Callsite : CallsiteSamples.second) { 611 sampleprof::FunctionSamples Remapped = 612 remapSamples(Callsite.second, Remapper, Error); 613 MergeResult(Error, 614 Target[std::string(Remapped.getName())].merge(Remapped)); 615 } 616 } 617 return Result; 618 } 619 620 static sampleprof::SampleProfileFormat FormatMap[] = { 621 sampleprof::SPF_None, 622 sampleprof::SPF_Text, 623 sampleprof::SPF_Compact_Binary, 624 sampleprof::SPF_Ext_Binary, 625 sampleprof::SPF_GCC, 626 sampleprof::SPF_Binary}; 627 628 static std::unique_ptr<MemoryBuffer> 629 getInputFileBuf(const StringRef &InputFile) { 630 if (InputFile == "") 631 return {}; 632 633 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile); 634 if (!BufOrError) 635 exitWithErrorCode(BufOrError.getError(), InputFile); 636 637 return std::move(*BufOrError); 638 } 639 640 static void populateProfileSymbolList(MemoryBuffer *Buffer, 641 sampleprof::ProfileSymbolList &PSL) { 642 if (!Buffer) 643 return; 644 645 SmallVector<StringRef, 32> SymbolVec; 646 StringRef Data = Buffer->getBuffer(); 647 Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 648 649 for (StringRef symbol : SymbolVec) 650 PSL.add(symbol); 651 } 652 653 static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer, 654 ProfileFormat OutputFormat, 655 MemoryBuffer *Buffer, 656 sampleprof::ProfileSymbolList &WriterList, 657 bool CompressAllSections, bool UseMD5, 658 bool GenPartialProfile) { 659 populateProfileSymbolList(Buffer, WriterList); 660 if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary) 661 warn("Profile Symbol list is not empty but the output format is not " 662 "ExtBinary format. The list will be lost in the output. "); 663 664 Writer.setProfileSymbolList(&WriterList); 665 666 if (CompressAllSections) { 667 if (OutputFormat != PF_Ext_Binary) 668 warn("-compress-all-section is ignored. Specify -extbinary to enable it"); 669 else 670 Writer.setToCompressAllSections(); 671 } 672 if (UseMD5) { 673 if (OutputFormat != PF_Ext_Binary) 674 warn("-use-md5 is ignored. Specify -extbinary to enable it"); 675 else 676 Writer.setUseMD5(); 677 } 678 if (GenPartialProfile) { 679 if (OutputFormat != PF_Ext_Binary) 680 warn("-gen-partial-profile is ignored. Specify -extbinary to enable it"); 681 else 682 Writer.setPartialProfile(); 683 } 684 } 685 686 static void 687 mergeSampleProfile(const WeightedFileVector &Inputs, SymbolRemapper *Remapper, 688 StringRef OutputFilename, ProfileFormat OutputFormat, 689 StringRef ProfileSymbolListFile, bool CompressAllSections, 690 bool UseMD5, bool GenPartialProfile, 691 bool SampleMergeColdContext, bool SampleTrimColdContext, 692 bool SampleColdContextFrameDepth, FailureMode FailMode) { 693 using namespace sampleprof; 694 StringMap<FunctionSamples> ProfileMap; 695 SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers; 696 LLVMContext Context; 697 sampleprof::ProfileSymbolList WriterList; 698 Optional<bool> ProfileIsProbeBased; 699 Optional<bool> ProfileIsCS; 700 for (const auto &Input : Inputs) { 701 auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context, 702 FSDiscriminatorPassOption); 703 if (std::error_code EC = ReaderOrErr.getError()) { 704 warnOrExitGivenError(FailMode, EC, Input.Filename); 705 continue; 706 } 707 708 // We need to keep the readers around until after all the files are 709 // read so that we do not lose the function names stored in each 710 // reader's memory. The function names are needed to write out the 711 // merged profile map. 712 Readers.push_back(std::move(ReaderOrErr.get())); 713 const auto Reader = Readers.back().get(); 714 if (std::error_code EC = Reader->read()) { 715 warnOrExitGivenError(FailMode, EC, Input.Filename); 716 Readers.pop_back(); 717 continue; 718 } 719 720 StringMap<FunctionSamples> &Profiles = Reader->getProfiles(); 721 if (ProfileIsProbeBased.hasValue() && 722 ProfileIsProbeBased != FunctionSamples::ProfileIsProbeBased) 723 exitWithError( 724 "cannot merge probe-based profile with non-probe-based profile"); 725 ProfileIsProbeBased = FunctionSamples::ProfileIsProbeBased; 726 if (ProfileIsCS.hasValue() && ProfileIsCS != FunctionSamples::ProfileIsCS) 727 exitWithError("cannot merge CS profile with non-CS profile"); 728 ProfileIsCS = FunctionSamples::ProfileIsCS; 729 for (StringMap<FunctionSamples>::iterator I = Profiles.begin(), 730 E = Profiles.end(); 731 I != E; ++I) { 732 sampleprof_error Result = sampleprof_error::success; 733 FunctionSamples Remapped = 734 Remapper ? remapSamples(I->second, *Remapper, Result) 735 : FunctionSamples(); 736 FunctionSamples &Samples = Remapper ? Remapped : I->second; 737 StringRef FName = Samples.getNameWithContext(); 738 MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight)); 739 if (Result != sampleprof_error::success) { 740 std::error_code EC = make_error_code(Result); 741 handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName); 742 } 743 } 744 745 std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList = 746 Reader->getProfileSymbolList(); 747 if (ReaderList) 748 WriterList.merge(*ReaderList); 749 } 750 751 if (ProfileIsCS && (SampleMergeColdContext || SampleTrimColdContext)) { 752 // Use threshold calculated from profile summary unless specified. 753 SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs); 754 auto Summary = Builder.computeSummaryForProfiles(ProfileMap); 755 uint64_t SampleProfColdThreshold = 756 ProfileSummaryBuilder::getColdCountThreshold( 757 (Summary->getDetailedSummary())); 758 759 // Trim and merge cold context profile using cold threshold above; 760 SampleContextTrimmer(ProfileMap) 761 .trimAndMergeColdContextProfiles( 762 SampleProfColdThreshold, SampleTrimColdContext, 763 SampleMergeColdContext, SampleColdContextFrameDepth); 764 } 765 766 auto WriterOrErr = 767 SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]); 768 if (std::error_code EC = WriterOrErr.getError()) 769 exitWithErrorCode(EC, OutputFilename); 770 771 auto Writer = std::move(WriterOrErr.get()); 772 // WriterList will have StringRef refering to string in Buffer. 773 // Make sure Buffer lives as long as WriterList. 774 auto Buffer = getInputFileBuf(ProfileSymbolListFile); 775 handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList, 776 CompressAllSections, UseMD5, GenPartialProfile); 777 if (std::error_code EC = Writer->write(ProfileMap)) 778 exitWithErrorCode(std::move(EC)); 779 } 780 781 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) { 782 StringRef WeightStr, FileName; 783 std::tie(WeightStr, FileName) = WeightedFilename.split(','); 784 785 uint64_t Weight; 786 if (WeightStr.getAsInteger(10, Weight) || Weight < 1) 787 exitWithError("Input weight must be a positive integer."); 788 789 return {std::string(FileName), Weight}; 790 } 791 792 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) { 793 StringRef Filename = WF.Filename; 794 uint64_t Weight = WF.Weight; 795 796 // If it's STDIN just pass it on. 797 if (Filename == "-") { 798 WNI.push_back({std::string(Filename), Weight}); 799 return; 800 } 801 802 llvm::sys::fs::file_status Status; 803 llvm::sys::fs::status(Filename, Status); 804 if (!llvm::sys::fs::exists(Status)) 805 exitWithErrorCode(make_error_code(errc::no_such_file_or_directory), 806 Filename); 807 // If it's a source file, collect it. 808 if (llvm::sys::fs::is_regular_file(Status)) { 809 WNI.push_back({std::string(Filename), Weight}); 810 return; 811 } 812 813 if (llvm::sys::fs::is_directory(Status)) { 814 std::error_code EC; 815 for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E; 816 F != E && !EC; F.increment(EC)) { 817 if (llvm::sys::fs::is_regular_file(F->path())) { 818 addWeightedInput(WNI, {F->path(), Weight}); 819 } 820 } 821 if (EC) 822 exitWithErrorCode(EC, Filename); 823 } 824 } 825 826 static void parseInputFilenamesFile(MemoryBuffer *Buffer, 827 WeightedFileVector &WFV) { 828 if (!Buffer) 829 return; 830 831 SmallVector<StringRef, 8> Entries; 832 StringRef Data = Buffer->getBuffer(); 833 Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 834 for (const StringRef &FileWeightEntry : Entries) { 835 StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r"); 836 // Skip comments. 837 if (SanitizedEntry.startswith("#")) 838 continue; 839 // If there's no comma, it's an unweighted profile. 840 else if (SanitizedEntry.find(',') == StringRef::npos) 841 addWeightedInput(WFV, {std::string(SanitizedEntry), 1}); 842 else 843 addWeightedInput(WFV, parseWeightedFile(SanitizedEntry)); 844 } 845 } 846 847 static int merge_main(int argc, const char *argv[]) { 848 cl::list<std::string> InputFilenames(cl::Positional, 849 cl::desc("<filename...>")); 850 cl::list<std::string> WeightedInputFilenames("weighted-input", 851 cl::desc("<weight>,<filename>")); 852 cl::opt<std::string> InputFilenamesFile( 853 "input-files", cl::init(""), 854 cl::desc("Path to file containing newline-separated " 855 "[<weight>,]<filename> entries")); 856 cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"), 857 cl::aliasopt(InputFilenamesFile)); 858 cl::opt<bool> DumpInputFileList( 859 "dump-input-file-list", cl::init(false), cl::Hidden, 860 cl::desc("Dump the list of input files and their weights, then exit")); 861 cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"), 862 cl::desc("Symbol remapping file")); 863 cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"), 864 cl::aliasopt(RemappingFile)); 865 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), 866 cl::init("-"), cl::Required, 867 cl::desc("Output file")); 868 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), 869 cl::aliasopt(OutputFilename)); 870 cl::opt<ProfileKinds> ProfileKind( 871 cl::desc("Profile kind:"), cl::init(instr), 872 cl::values(clEnumVal(instr, "Instrumentation profile (default)"), 873 clEnumVal(sample, "Sample profile"))); 874 cl::opt<ProfileFormat> OutputFormat( 875 cl::desc("Format of output profile"), cl::init(PF_Binary), 876 cl::values( 877 clEnumValN(PF_Binary, "binary", "Binary encoding (default)"), 878 clEnumValN(PF_Compact_Binary, "compbinary", 879 "Compact binary encoding"), 880 clEnumValN(PF_Ext_Binary, "extbinary", "Extensible binary encoding"), 881 clEnumValN(PF_Text, "text", "Text encoding"), 882 clEnumValN(PF_GCC, "gcc", 883 "GCC encoding (only meaningful for -sample)"))); 884 cl::opt<FailureMode> FailureMode( 885 "failure-mode", cl::init(failIfAnyAreInvalid), cl::desc("Failure mode:"), 886 cl::values(clEnumValN(failIfAnyAreInvalid, "any", 887 "Fail if any profile is invalid."), 888 clEnumValN(failIfAllAreInvalid, "all", 889 "Fail only if all profiles are invalid."))); 890 cl::opt<bool> OutputSparse("sparse", cl::init(false), 891 cl::desc("Generate a sparse profile (only meaningful for -instr)")); 892 cl::opt<unsigned> NumThreads( 893 "num-threads", cl::init(0), 894 cl::desc("Number of merge threads to use (default: autodetect)")); 895 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"), 896 cl::aliasopt(NumThreads)); 897 cl::opt<std::string> ProfileSymbolListFile( 898 "prof-sym-list", cl::init(""), 899 cl::desc("Path to file containing the list of function symbols " 900 "used to populate profile symbol list")); 901 cl::opt<bool> CompressAllSections( 902 "compress-all-sections", cl::init(false), cl::Hidden, 903 cl::desc("Compress all sections when writing the profile (only " 904 "meaningful for -extbinary)")); 905 cl::opt<bool> UseMD5( 906 "use-md5", cl::init(false), cl::Hidden, 907 cl::desc("Choose to use MD5 to represent string in name table (only " 908 "meaningful for -extbinary)")); 909 cl::opt<bool> SampleMergeColdContext( 910 "sample-merge-cold-context", cl::init(false), cl::Hidden, 911 cl::desc( 912 "Merge context sample profiles whose count is below cold threshold")); 913 cl::opt<bool> SampleTrimColdContext( 914 "sample-trim-cold-context", cl::init(false), cl::Hidden, 915 cl::desc( 916 "Trim context sample profiles whose count is below cold threshold")); 917 cl::opt<uint32_t> SampleColdContextFrameDepth( 918 "sample-frame-depth-for-cold-context", cl::init(1), cl::ZeroOrMore, 919 cl::desc("Keep the last K frames while merging cold profile. 1 means the " 920 "context-less base profile")); 921 cl::opt<bool> GenPartialProfile( 922 "gen-partial-profile", cl::init(false), cl::Hidden, 923 cl::desc("Generate a partial profile (only meaningful for -extbinary)")); 924 cl::opt<std::string> SupplInstrWithSample( 925 "supplement-instr-with-sample", cl::init(""), cl::Hidden, 926 cl::desc("Supplement an instr profile with sample profile, to correct " 927 "the profile unrepresentativeness issue. The sample " 928 "profile is the input of the flag. Output will be in instr " 929 "format (The flag only works with -instr)")); 930 cl::opt<float> ZeroCounterThreshold( 931 "zero-counter-threshold", cl::init(0.7), cl::Hidden, 932 cl::desc("For the function which is cold in instr profile but hot in " 933 "sample profile, if the ratio of the number of zero counters " 934 "divided by the the total number of counters is above the " 935 "threshold, the profile of the function will be regarded as " 936 "being harmful for performance and will be dropped.")); 937 cl::opt<unsigned> SupplMinSizeThreshold( 938 "suppl-min-size-threshold", cl::init(10), cl::Hidden, 939 cl::desc("If the size of a function is smaller than the threshold, " 940 "assume it can be inlined by PGO early inliner and it won't " 941 "be adjusted based on sample profile.")); 942 cl::opt<unsigned> InstrProfColdThreshold( 943 "instr-prof-cold-threshold", cl::init(0), cl::Hidden, 944 cl::desc("User specified cold threshold for instr profile which will " 945 "override the cold threshold got from profile summary.")); 946 947 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n"); 948 949 WeightedFileVector WeightedInputs; 950 for (StringRef Filename : InputFilenames) 951 addWeightedInput(WeightedInputs, {std::string(Filename), 1}); 952 for (StringRef WeightedFilename : WeightedInputFilenames) 953 addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename)); 954 955 // Make sure that the file buffer stays alive for the duration of the 956 // weighted input vector's lifetime. 957 auto Buffer = getInputFileBuf(InputFilenamesFile); 958 parseInputFilenamesFile(Buffer.get(), WeightedInputs); 959 960 if (WeightedInputs.empty()) 961 exitWithError("No input files specified. See " + 962 sys::path::filename(argv[0]) + " -help"); 963 964 if (DumpInputFileList) { 965 for (auto &WF : WeightedInputs) 966 outs() << WF.Weight << "," << WF.Filename << "\n"; 967 return 0; 968 } 969 970 std::unique_ptr<SymbolRemapper> Remapper; 971 if (!RemappingFile.empty()) 972 Remapper = SymbolRemapper::create(RemappingFile); 973 974 if (!SupplInstrWithSample.empty()) { 975 if (ProfileKind != instr) 976 exitWithError( 977 "-supplement-instr-with-sample can only work with -instr. "); 978 979 supplementInstrProfile(WeightedInputs, SupplInstrWithSample, OutputFilename, 980 OutputFormat, OutputSparse, SupplMinSizeThreshold, 981 ZeroCounterThreshold, InstrProfColdThreshold); 982 return 0; 983 } 984 985 if (ProfileKind == instr) 986 mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename, 987 OutputFormat, OutputSparse, NumThreads, FailureMode); 988 else 989 mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename, 990 OutputFormat, ProfileSymbolListFile, CompressAllSections, 991 UseMD5, GenPartialProfile, SampleMergeColdContext, 992 SampleTrimColdContext, SampleColdContextFrameDepth, 993 FailureMode); 994 995 return 0; 996 } 997 998 /// Computer the overlap b/w profile BaseFilename and profile TestFilename. 999 static void overlapInstrProfile(const std::string &BaseFilename, 1000 const std::string &TestFilename, 1001 const OverlapFuncFilters &FuncFilter, 1002 raw_fd_ostream &OS, bool IsCS) { 1003 std::mutex ErrorLock; 1004 SmallSet<instrprof_error, 4> WriterErrorCodes; 1005 WriterContext Context(false, ErrorLock, WriterErrorCodes); 1006 WeightedFile WeightedInput{BaseFilename, 1}; 1007 OverlapStats Overlap; 1008 Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS); 1009 if (E) 1010 exitWithError(std::move(E), "Error in getting profile count sums"); 1011 if (Overlap.Base.CountSum < 1.0f) { 1012 OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n"; 1013 exit(0); 1014 } 1015 if (Overlap.Test.CountSum < 1.0f) { 1016 OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n"; 1017 exit(0); 1018 } 1019 loadInput(WeightedInput, nullptr, &Context); 1020 overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS, 1021 IsCS); 1022 Overlap.dump(OS); 1023 } 1024 1025 namespace { 1026 struct SampleOverlapStats { 1027 StringRef BaseName; 1028 StringRef TestName; 1029 // Number of overlap units 1030 uint64_t OverlapCount; 1031 // Total samples of overlap units 1032 uint64_t OverlapSample; 1033 // Number of and total samples of units that only present in base or test 1034 // profile 1035 uint64_t BaseUniqueCount; 1036 uint64_t BaseUniqueSample; 1037 uint64_t TestUniqueCount; 1038 uint64_t TestUniqueSample; 1039 // Number of units and total samples in base or test profile 1040 uint64_t BaseCount; 1041 uint64_t BaseSample; 1042 uint64_t TestCount; 1043 uint64_t TestSample; 1044 // Number of and total samples of units that present in at least one profile 1045 uint64_t UnionCount; 1046 uint64_t UnionSample; 1047 // Weighted similarity 1048 double Similarity; 1049 // For SampleOverlapStats instances representing functions, weights of the 1050 // function in base and test profiles 1051 double BaseWeight; 1052 double TestWeight; 1053 1054 SampleOverlapStats() 1055 : OverlapCount(0), OverlapSample(0), BaseUniqueCount(0), 1056 BaseUniqueSample(0), TestUniqueCount(0), TestUniqueSample(0), 1057 BaseCount(0), BaseSample(0), TestCount(0), TestSample(0), UnionCount(0), 1058 UnionSample(0), Similarity(0.0), BaseWeight(0.0), TestWeight(0.0) {} 1059 }; 1060 } // end anonymous namespace 1061 1062 namespace { 1063 struct FuncSampleStats { 1064 uint64_t SampleSum; 1065 uint64_t MaxSample; 1066 uint64_t HotBlockCount; 1067 FuncSampleStats() : SampleSum(0), MaxSample(0), HotBlockCount(0) {} 1068 FuncSampleStats(uint64_t SampleSum, uint64_t MaxSample, 1069 uint64_t HotBlockCount) 1070 : SampleSum(SampleSum), MaxSample(MaxSample), 1071 HotBlockCount(HotBlockCount) {} 1072 }; 1073 } // end anonymous namespace 1074 1075 namespace { 1076 enum MatchStatus { MS_Match, MS_FirstUnique, MS_SecondUnique, MS_None }; 1077 1078 // Class for updating merging steps for two sorted maps. The class should be 1079 // instantiated with a map iterator type. 1080 template <class T> class MatchStep { 1081 public: 1082 MatchStep() = delete; 1083 1084 MatchStep(T FirstIter, T FirstEnd, T SecondIter, T SecondEnd) 1085 : FirstIter(FirstIter), FirstEnd(FirstEnd), SecondIter(SecondIter), 1086 SecondEnd(SecondEnd), Status(MS_None) {} 1087 1088 bool areBothFinished() const { 1089 return (FirstIter == FirstEnd && SecondIter == SecondEnd); 1090 } 1091 1092 bool isFirstFinished() const { return FirstIter == FirstEnd; } 1093 1094 bool isSecondFinished() const { return SecondIter == SecondEnd; } 1095 1096 /// Advance one step based on the previous match status unless the previous 1097 /// status is MS_None. Then update Status based on the comparison between two 1098 /// container iterators at the current step. If the previous status is 1099 /// MS_None, it means two iterators are at the beginning and no comparison has 1100 /// been made, so we simply update Status without advancing the iterators. 1101 void updateOneStep(); 1102 1103 T getFirstIter() const { return FirstIter; } 1104 1105 T getSecondIter() const { return SecondIter; } 1106 1107 MatchStatus getMatchStatus() const { return Status; } 1108 1109 private: 1110 // Current iterator and end iterator of the first container. 1111 T FirstIter; 1112 T FirstEnd; 1113 // Current iterator and end iterator of the second container. 1114 T SecondIter; 1115 T SecondEnd; 1116 // Match status of the current step. 1117 MatchStatus Status; 1118 }; 1119 } // end anonymous namespace 1120 1121 template <class T> void MatchStep<T>::updateOneStep() { 1122 switch (Status) { 1123 case MS_Match: 1124 ++FirstIter; 1125 ++SecondIter; 1126 break; 1127 case MS_FirstUnique: 1128 ++FirstIter; 1129 break; 1130 case MS_SecondUnique: 1131 ++SecondIter; 1132 break; 1133 case MS_None: 1134 break; 1135 } 1136 1137 // Update Status according to iterators at the current step. 1138 if (areBothFinished()) 1139 return; 1140 if (FirstIter != FirstEnd && 1141 (SecondIter == SecondEnd || FirstIter->first < SecondIter->first)) 1142 Status = MS_FirstUnique; 1143 else if (SecondIter != SecondEnd && 1144 (FirstIter == FirstEnd || SecondIter->first < FirstIter->first)) 1145 Status = MS_SecondUnique; 1146 else 1147 Status = MS_Match; 1148 } 1149 1150 // Return the sum of line/block samples, the max line/block sample, and the 1151 // number of line/block samples above the given threshold in a function 1152 // including its inlinees. 1153 static void getFuncSampleStats(const sampleprof::FunctionSamples &Func, 1154 FuncSampleStats &FuncStats, 1155 uint64_t HotThreshold) { 1156 for (const auto &L : Func.getBodySamples()) { 1157 uint64_t Sample = L.second.getSamples(); 1158 FuncStats.SampleSum += Sample; 1159 FuncStats.MaxSample = std::max(FuncStats.MaxSample, Sample); 1160 if (Sample >= HotThreshold) 1161 ++FuncStats.HotBlockCount; 1162 } 1163 1164 for (const auto &C : Func.getCallsiteSamples()) { 1165 for (const auto &F : C.second) 1166 getFuncSampleStats(F.second, FuncStats, HotThreshold); 1167 } 1168 } 1169 1170 /// Predicate that determines if a function is hot with a given threshold. We 1171 /// keep it separate from its callsites for possible extension in the future. 1172 static bool isFunctionHot(const FuncSampleStats &FuncStats, 1173 uint64_t HotThreshold) { 1174 // We intentionally compare the maximum sample count in a function with the 1175 // HotThreshold to get an approximate determination on hot functions. 1176 return (FuncStats.MaxSample >= HotThreshold); 1177 } 1178 1179 namespace { 1180 class SampleOverlapAggregator { 1181 public: 1182 SampleOverlapAggregator(const std::string &BaseFilename, 1183 const std::string &TestFilename, 1184 double LowSimilarityThreshold, double Epsilon, 1185 const OverlapFuncFilters &FuncFilter) 1186 : BaseFilename(BaseFilename), TestFilename(TestFilename), 1187 LowSimilarityThreshold(LowSimilarityThreshold), Epsilon(Epsilon), 1188 FuncFilter(FuncFilter) {} 1189 1190 /// Detect 0-sample input profile and report to output stream. This interface 1191 /// should be called after loadProfiles(). 1192 bool detectZeroSampleProfile(raw_fd_ostream &OS) const; 1193 1194 /// Write out function-level similarity statistics for functions specified by 1195 /// options --function, --value-cutoff, and --similarity-cutoff. 1196 void dumpFuncSimilarity(raw_fd_ostream &OS) const; 1197 1198 /// Write out program-level similarity and overlap statistics. 1199 void dumpProgramSummary(raw_fd_ostream &OS) const; 1200 1201 /// Write out hot-function and hot-block statistics for base_profile, 1202 /// test_profile, and their overlap. For both cases, the overlap HO is 1203 /// calculated as follows: 1204 /// Given the number of functions (or blocks) that are hot in both profiles 1205 /// HCommon and the number of functions (or blocks) that are hot in at 1206 /// least one profile HUnion, HO = HCommon / HUnion. 1207 void dumpHotFuncAndBlockOverlap(raw_fd_ostream &OS) const; 1208 1209 /// This function tries matching functions in base and test profiles. For each 1210 /// pair of matched functions, it aggregates the function-level 1211 /// similarity into a profile-level similarity. It also dump function-level 1212 /// similarity information of functions specified by --function, 1213 /// --value-cutoff, and --similarity-cutoff options. The program-level 1214 /// similarity PS is computed as follows: 1215 /// Given function-level similarity FS(A) for all function A, the 1216 /// weight of function A in base profile WB(A), and the weight of function 1217 /// A in test profile WT(A), compute PS(base_profile, test_profile) = 1218 /// sum_A(FS(A) * avg(WB(A), WT(A))) ranging in [0.0f to 1.0f] with 0.0 1219 /// meaning no-overlap. 1220 void computeSampleProfileOverlap(raw_fd_ostream &OS); 1221 1222 /// Initialize ProfOverlap with the sum of samples in base and test 1223 /// profiles. This function also computes and keeps the sum of samples and 1224 /// max sample counts of each function in BaseStats and TestStats for later 1225 /// use to avoid re-computations. 1226 void initializeSampleProfileOverlap(); 1227 1228 /// Load profiles specified by BaseFilename and TestFilename. 1229 std::error_code loadProfiles(); 1230 1231 private: 1232 SampleOverlapStats ProfOverlap; 1233 SampleOverlapStats HotFuncOverlap; 1234 SampleOverlapStats HotBlockOverlap; 1235 std::string BaseFilename; 1236 std::string TestFilename; 1237 std::unique_ptr<sampleprof::SampleProfileReader> BaseReader; 1238 std::unique_ptr<sampleprof::SampleProfileReader> TestReader; 1239 // BaseStats and TestStats hold FuncSampleStats for each function, with 1240 // function name as the key. 1241 StringMap<FuncSampleStats> BaseStats; 1242 StringMap<FuncSampleStats> TestStats; 1243 // Low similarity threshold in floating point number 1244 double LowSimilarityThreshold; 1245 // Block samples above BaseHotThreshold or TestHotThreshold are considered hot 1246 // for tracking hot blocks. 1247 uint64_t BaseHotThreshold; 1248 uint64_t TestHotThreshold; 1249 // A small threshold used to round the results of floating point accumulations 1250 // to resolve imprecision. 1251 const double Epsilon; 1252 std::multimap<double, SampleOverlapStats, std::greater<double>> 1253 FuncSimilarityDump; 1254 // FuncFilter carries specifications in options --value-cutoff and 1255 // --function. 1256 OverlapFuncFilters FuncFilter; 1257 // Column offsets for printing the function-level details table. 1258 static const unsigned int TestWeightCol = 15; 1259 static const unsigned int SimilarityCol = 30; 1260 static const unsigned int OverlapCol = 43; 1261 static const unsigned int BaseUniqueCol = 53; 1262 static const unsigned int TestUniqueCol = 67; 1263 static const unsigned int BaseSampleCol = 81; 1264 static const unsigned int TestSampleCol = 96; 1265 static const unsigned int FuncNameCol = 111; 1266 1267 /// Return a similarity of two line/block sample counters in the same 1268 /// function in base and test profiles. The line/block-similarity BS(i) is 1269 /// computed as follows: 1270 /// For an offsets i, given the sample count at i in base profile BB(i), 1271 /// the sample count at i in test profile BT(i), the sum of sample counts 1272 /// in this function in base profile SB, and the sum of sample counts in 1273 /// this function in test profile ST, compute BS(i) = 1.0 - fabs(BB(i)/SB - 1274 /// BT(i)/ST), ranging in [0.0f to 1.0f] with 0.0 meaning no-overlap. 1275 double computeBlockSimilarity(uint64_t BaseSample, uint64_t TestSample, 1276 const SampleOverlapStats &FuncOverlap) const; 1277 1278 void updateHotBlockOverlap(uint64_t BaseSample, uint64_t TestSample, 1279 uint64_t HotBlockCount); 1280 1281 void getHotFunctions(const StringMap<FuncSampleStats> &ProfStats, 1282 StringMap<FuncSampleStats> &HotFunc, 1283 uint64_t HotThreshold) const; 1284 1285 void computeHotFuncOverlap(); 1286 1287 /// This function updates statistics in FuncOverlap, HotBlockOverlap, and 1288 /// Difference for two sample units in a matched function according to the 1289 /// given match status. 1290 void updateOverlapStatsForFunction(uint64_t BaseSample, uint64_t TestSample, 1291 uint64_t HotBlockCount, 1292 SampleOverlapStats &FuncOverlap, 1293 double &Difference, MatchStatus Status); 1294 1295 /// This function updates statistics in FuncOverlap, HotBlockOverlap, and 1296 /// Difference for unmatched callees that only present in one profile in a 1297 /// matched caller function. 1298 void updateForUnmatchedCallee(const sampleprof::FunctionSamples &Func, 1299 SampleOverlapStats &FuncOverlap, 1300 double &Difference, MatchStatus Status); 1301 1302 /// This function updates sample overlap statistics of an overlap function in 1303 /// base and test profile. It also calculates a function-internal similarity 1304 /// FIS as follows: 1305 /// For offsets i that have samples in at least one profile in this 1306 /// function A, given BS(i) returned by computeBlockSimilarity(), compute 1307 /// FIS(A) = (2.0 - sum_i(1.0 - BS(i))) / 2, ranging in [0.0f to 1.0f] with 1308 /// 0.0 meaning no overlap. 1309 double computeSampleFunctionInternalOverlap( 1310 const sampleprof::FunctionSamples &BaseFunc, 1311 const sampleprof::FunctionSamples &TestFunc, 1312 SampleOverlapStats &FuncOverlap); 1313 1314 /// Function-level similarity (FS) is a weighted value over function internal 1315 /// similarity (FIS). This function computes a function's FS from its FIS by 1316 /// applying the weight. 1317 double weightForFuncSimilarity(double FuncSimilarity, uint64_t BaseFuncSample, 1318 uint64_t TestFuncSample) const; 1319 1320 /// The function-level similarity FS(A) for a function A is computed as 1321 /// follows: 1322 /// Compute a function-internal similarity FIS(A) by 1323 /// computeSampleFunctionInternalOverlap(). Then, with the weight of 1324 /// function A in base profile WB(A), and the weight of function A in test 1325 /// profile WT(A), compute FS(A) = FIS(A) * (1.0 - fabs(WB(A) - WT(A))) 1326 /// ranging in [0.0f to 1.0f] with 0.0 meaning no overlap. 1327 double 1328 computeSampleFunctionOverlap(const sampleprof::FunctionSamples *BaseFunc, 1329 const sampleprof::FunctionSamples *TestFunc, 1330 SampleOverlapStats *FuncOverlap, 1331 uint64_t BaseFuncSample, 1332 uint64_t TestFuncSample); 1333 1334 /// Profile-level similarity (PS) is a weighted aggregate over function-level 1335 /// similarities (FS). This method weights the FS value by the function 1336 /// weights in the base and test profiles for the aggregation. 1337 double weightByImportance(double FuncSimilarity, uint64_t BaseFuncSample, 1338 uint64_t TestFuncSample) const; 1339 }; 1340 } // end anonymous namespace 1341 1342 bool SampleOverlapAggregator::detectZeroSampleProfile( 1343 raw_fd_ostream &OS) const { 1344 bool HaveZeroSample = false; 1345 if (ProfOverlap.BaseSample == 0) { 1346 OS << "Sum of sample counts for profile " << BaseFilename << " is 0.\n"; 1347 HaveZeroSample = true; 1348 } 1349 if (ProfOverlap.TestSample == 0) { 1350 OS << "Sum of sample counts for profile " << TestFilename << " is 0.\n"; 1351 HaveZeroSample = true; 1352 } 1353 return HaveZeroSample; 1354 } 1355 1356 double SampleOverlapAggregator::computeBlockSimilarity( 1357 uint64_t BaseSample, uint64_t TestSample, 1358 const SampleOverlapStats &FuncOverlap) const { 1359 double BaseFrac = 0.0; 1360 double TestFrac = 0.0; 1361 if (FuncOverlap.BaseSample > 0) 1362 BaseFrac = static_cast<double>(BaseSample) / FuncOverlap.BaseSample; 1363 if (FuncOverlap.TestSample > 0) 1364 TestFrac = static_cast<double>(TestSample) / FuncOverlap.TestSample; 1365 return 1.0 - std::fabs(BaseFrac - TestFrac); 1366 } 1367 1368 void SampleOverlapAggregator::updateHotBlockOverlap(uint64_t BaseSample, 1369 uint64_t TestSample, 1370 uint64_t HotBlockCount) { 1371 bool IsBaseHot = (BaseSample >= BaseHotThreshold); 1372 bool IsTestHot = (TestSample >= TestHotThreshold); 1373 if (!IsBaseHot && !IsTestHot) 1374 return; 1375 1376 HotBlockOverlap.UnionCount += HotBlockCount; 1377 if (IsBaseHot) 1378 HotBlockOverlap.BaseCount += HotBlockCount; 1379 if (IsTestHot) 1380 HotBlockOverlap.TestCount += HotBlockCount; 1381 if (IsBaseHot && IsTestHot) 1382 HotBlockOverlap.OverlapCount += HotBlockCount; 1383 } 1384 1385 void SampleOverlapAggregator::getHotFunctions( 1386 const StringMap<FuncSampleStats> &ProfStats, 1387 StringMap<FuncSampleStats> &HotFunc, uint64_t HotThreshold) const { 1388 for (const auto &F : ProfStats) { 1389 if (isFunctionHot(F.second, HotThreshold)) 1390 HotFunc.try_emplace(F.first(), F.second); 1391 } 1392 } 1393 1394 void SampleOverlapAggregator::computeHotFuncOverlap() { 1395 StringMap<FuncSampleStats> BaseHotFunc; 1396 getHotFunctions(BaseStats, BaseHotFunc, BaseHotThreshold); 1397 HotFuncOverlap.BaseCount = BaseHotFunc.size(); 1398 1399 StringMap<FuncSampleStats> TestHotFunc; 1400 getHotFunctions(TestStats, TestHotFunc, TestHotThreshold); 1401 HotFuncOverlap.TestCount = TestHotFunc.size(); 1402 HotFuncOverlap.UnionCount = HotFuncOverlap.TestCount; 1403 1404 for (const auto &F : BaseHotFunc) { 1405 if (TestHotFunc.count(F.first())) 1406 ++HotFuncOverlap.OverlapCount; 1407 else 1408 ++HotFuncOverlap.UnionCount; 1409 } 1410 } 1411 1412 void SampleOverlapAggregator::updateOverlapStatsForFunction( 1413 uint64_t BaseSample, uint64_t TestSample, uint64_t HotBlockCount, 1414 SampleOverlapStats &FuncOverlap, double &Difference, MatchStatus Status) { 1415 assert(Status != MS_None && 1416 "Match status should be updated before updating overlap statistics"); 1417 if (Status == MS_FirstUnique) { 1418 TestSample = 0; 1419 FuncOverlap.BaseUniqueSample += BaseSample; 1420 } else if (Status == MS_SecondUnique) { 1421 BaseSample = 0; 1422 FuncOverlap.TestUniqueSample += TestSample; 1423 } else { 1424 ++FuncOverlap.OverlapCount; 1425 } 1426 1427 FuncOverlap.UnionSample += std::max(BaseSample, TestSample); 1428 FuncOverlap.OverlapSample += std::min(BaseSample, TestSample); 1429 Difference += 1430 1.0 - computeBlockSimilarity(BaseSample, TestSample, FuncOverlap); 1431 updateHotBlockOverlap(BaseSample, TestSample, HotBlockCount); 1432 } 1433 1434 void SampleOverlapAggregator::updateForUnmatchedCallee( 1435 const sampleprof::FunctionSamples &Func, SampleOverlapStats &FuncOverlap, 1436 double &Difference, MatchStatus Status) { 1437 assert((Status == MS_FirstUnique || Status == MS_SecondUnique) && 1438 "Status must be either of the two unmatched cases"); 1439 FuncSampleStats FuncStats; 1440 if (Status == MS_FirstUnique) { 1441 getFuncSampleStats(Func, FuncStats, BaseHotThreshold); 1442 updateOverlapStatsForFunction(FuncStats.SampleSum, 0, 1443 FuncStats.HotBlockCount, FuncOverlap, 1444 Difference, Status); 1445 } else { 1446 getFuncSampleStats(Func, FuncStats, TestHotThreshold); 1447 updateOverlapStatsForFunction(0, FuncStats.SampleSum, 1448 FuncStats.HotBlockCount, FuncOverlap, 1449 Difference, Status); 1450 } 1451 } 1452 1453 double SampleOverlapAggregator::computeSampleFunctionInternalOverlap( 1454 const sampleprof::FunctionSamples &BaseFunc, 1455 const sampleprof::FunctionSamples &TestFunc, 1456 SampleOverlapStats &FuncOverlap) { 1457 1458 using namespace sampleprof; 1459 1460 double Difference = 0; 1461 1462 // Accumulate Difference for regular line/block samples in the function. 1463 // We match them through sort-merge join algorithm because 1464 // FunctionSamples::getBodySamples() returns a map of sample counters ordered 1465 // by their offsets. 1466 MatchStep<BodySampleMap::const_iterator> BlockIterStep( 1467 BaseFunc.getBodySamples().cbegin(), BaseFunc.getBodySamples().cend(), 1468 TestFunc.getBodySamples().cbegin(), TestFunc.getBodySamples().cend()); 1469 BlockIterStep.updateOneStep(); 1470 while (!BlockIterStep.areBothFinished()) { 1471 uint64_t BaseSample = 1472 BlockIterStep.isFirstFinished() 1473 ? 0 1474 : BlockIterStep.getFirstIter()->second.getSamples(); 1475 uint64_t TestSample = 1476 BlockIterStep.isSecondFinished() 1477 ? 0 1478 : BlockIterStep.getSecondIter()->second.getSamples(); 1479 updateOverlapStatsForFunction(BaseSample, TestSample, 1, FuncOverlap, 1480 Difference, BlockIterStep.getMatchStatus()); 1481 1482 BlockIterStep.updateOneStep(); 1483 } 1484 1485 // Accumulate Difference for callsite lines in the function. We match 1486 // them through sort-merge algorithm because 1487 // FunctionSamples::getCallsiteSamples() returns a map of callsite records 1488 // ordered by their offsets. 1489 MatchStep<CallsiteSampleMap::const_iterator> CallsiteIterStep( 1490 BaseFunc.getCallsiteSamples().cbegin(), 1491 BaseFunc.getCallsiteSamples().cend(), 1492 TestFunc.getCallsiteSamples().cbegin(), 1493 TestFunc.getCallsiteSamples().cend()); 1494 CallsiteIterStep.updateOneStep(); 1495 while (!CallsiteIterStep.areBothFinished()) { 1496 MatchStatus CallsiteStepStatus = CallsiteIterStep.getMatchStatus(); 1497 assert(CallsiteStepStatus != MS_None && 1498 "Match status should be updated before entering loop body"); 1499 1500 if (CallsiteStepStatus != MS_Match) { 1501 auto Callsite = (CallsiteStepStatus == MS_FirstUnique) 1502 ? CallsiteIterStep.getFirstIter() 1503 : CallsiteIterStep.getSecondIter(); 1504 for (const auto &F : Callsite->second) 1505 updateForUnmatchedCallee(F.second, FuncOverlap, Difference, 1506 CallsiteStepStatus); 1507 } else { 1508 // There may be multiple inlinees at the same offset, so we need to try 1509 // matching all of them. This match is implemented through sort-merge 1510 // algorithm because callsite records at the same offset are ordered by 1511 // function names. 1512 MatchStep<FunctionSamplesMap::const_iterator> CalleeIterStep( 1513 CallsiteIterStep.getFirstIter()->second.cbegin(), 1514 CallsiteIterStep.getFirstIter()->second.cend(), 1515 CallsiteIterStep.getSecondIter()->second.cbegin(), 1516 CallsiteIterStep.getSecondIter()->second.cend()); 1517 CalleeIterStep.updateOneStep(); 1518 while (!CalleeIterStep.areBothFinished()) { 1519 MatchStatus CalleeStepStatus = CalleeIterStep.getMatchStatus(); 1520 if (CalleeStepStatus != MS_Match) { 1521 auto Callee = (CalleeStepStatus == MS_FirstUnique) 1522 ? CalleeIterStep.getFirstIter() 1523 : CalleeIterStep.getSecondIter(); 1524 updateForUnmatchedCallee(Callee->second, FuncOverlap, Difference, 1525 CalleeStepStatus); 1526 } else { 1527 // An inlined function can contain other inlinees inside, so compute 1528 // the Difference recursively. 1529 Difference += 2.0 - 2 * computeSampleFunctionInternalOverlap( 1530 CalleeIterStep.getFirstIter()->second, 1531 CalleeIterStep.getSecondIter()->second, 1532 FuncOverlap); 1533 } 1534 CalleeIterStep.updateOneStep(); 1535 } 1536 } 1537 CallsiteIterStep.updateOneStep(); 1538 } 1539 1540 // Difference reflects the total differences of line/block samples in this 1541 // function and ranges in [0.0f to 2.0f]. Take (2.0 - Difference) / 2 to 1542 // reflect the similarity between function profiles in [0.0f to 1.0f]. 1543 return (2.0 - Difference) / 2; 1544 } 1545 1546 double SampleOverlapAggregator::weightForFuncSimilarity( 1547 double FuncInternalSimilarity, uint64_t BaseFuncSample, 1548 uint64_t TestFuncSample) const { 1549 // Compute the weight as the distance between the function weights in two 1550 // profiles. 1551 double BaseFrac = 0.0; 1552 double TestFrac = 0.0; 1553 assert(ProfOverlap.BaseSample > 0 && 1554 "Total samples in base profile should be greater than 0"); 1555 BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample; 1556 assert(ProfOverlap.TestSample > 0 && 1557 "Total samples in test profile should be greater than 0"); 1558 TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample; 1559 double WeightDistance = std::fabs(BaseFrac - TestFrac); 1560 1561 // Take WeightDistance into the similarity. 1562 return FuncInternalSimilarity * (1 - WeightDistance); 1563 } 1564 1565 double 1566 SampleOverlapAggregator::weightByImportance(double FuncSimilarity, 1567 uint64_t BaseFuncSample, 1568 uint64_t TestFuncSample) const { 1569 1570 double BaseFrac = 0.0; 1571 double TestFrac = 0.0; 1572 assert(ProfOverlap.BaseSample > 0 && 1573 "Total samples in base profile should be greater than 0"); 1574 BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample / 2.0; 1575 assert(ProfOverlap.TestSample > 0 && 1576 "Total samples in test profile should be greater than 0"); 1577 TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample / 2.0; 1578 return FuncSimilarity * (BaseFrac + TestFrac); 1579 } 1580 1581 double SampleOverlapAggregator::computeSampleFunctionOverlap( 1582 const sampleprof::FunctionSamples *BaseFunc, 1583 const sampleprof::FunctionSamples *TestFunc, 1584 SampleOverlapStats *FuncOverlap, uint64_t BaseFuncSample, 1585 uint64_t TestFuncSample) { 1586 // Default function internal similarity before weighted, meaning two functions 1587 // has no overlap. 1588 const double DefaultFuncInternalSimilarity = 0; 1589 double FuncSimilarity; 1590 double FuncInternalSimilarity; 1591 1592 // If BaseFunc or TestFunc is nullptr, it means the functions do not overlap. 1593 // In this case, we use DefaultFuncInternalSimilarity as the function internal 1594 // similarity. 1595 if (!BaseFunc || !TestFunc) { 1596 FuncInternalSimilarity = DefaultFuncInternalSimilarity; 1597 } else { 1598 assert(FuncOverlap != nullptr && 1599 "FuncOverlap should be provided in this case"); 1600 FuncInternalSimilarity = computeSampleFunctionInternalOverlap( 1601 *BaseFunc, *TestFunc, *FuncOverlap); 1602 // Now, FuncInternalSimilarity may be a little less than 0 due to 1603 // imprecision of floating point accumulations. Make it zero if the 1604 // difference is below Epsilon. 1605 FuncInternalSimilarity = (std::fabs(FuncInternalSimilarity - 0) < Epsilon) 1606 ? 0 1607 : FuncInternalSimilarity; 1608 } 1609 FuncSimilarity = weightForFuncSimilarity(FuncInternalSimilarity, 1610 BaseFuncSample, TestFuncSample); 1611 return FuncSimilarity; 1612 } 1613 1614 void SampleOverlapAggregator::computeSampleProfileOverlap(raw_fd_ostream &OS) { 1615 using namespace sampleprof; 1616 1617 StringMap<const FunctionSamples *> BaseFuncProf; 1618 const auto &BaseProfiles = BaseReader->getProfiles(); 1619 for (const auto &BaseFunc : BaseProfiles) { 1620 BaseFuncProf.try_emplace(BaseFunc.second.getNameWithContext(), 1621 &(BaseFunc.second)); 1622 } 1623 ProfOverlap.UnionCount = BaseFuncProf.size(); 1624 1625 const auto &TestProfiles = TestReader->getProfiles(); 1626 for (const auto &TestFunc : TestProfiles) { 1627 SampleOverlapStats FuncOverlap; 1628 FuncOverlap.TestName = TestFunc.second.getNameWithContext(); 1629 assert(TestStats.count(FuncOverlap.TestName) && 1630 "TestStats should have records for all functions in test profile " 1631 "except inlinees"); 1632 FuncOverlap.TestSample = TestStats[FuncOverlap.TestName].SampleSum; 1633 1634 const auto Match = BaseFuncProf.find(FuncOverlap.TestName); 1635 if (Match == BaseFuncProf.end()) { 1636 const FuncSampleStats &FuncStats = TestStats[FuncOverlap.TestName]; 1637 ++ProfOverlap.TestUniqueCount; 1638 ProfOverlap.TestUniqueSample += FuncStats.SampleSum; 1639 FuncOverlap.TestUniqueSample = FuncStats.SampleSum; 1640 1641 updateHotBlockOverlap(0, FuncStats.SampleSum, FuncStats.HotBlockCount); 1642 1643 double FuncSimilarity = computeSampleFunctionOverlap( 1644 nullptr, nullptr, nullptr, 0, FuncStats.SampleSum); 1645 ProfOverlap.Similarity += 1646 weightByImportance(FuncSimilarity, 0, FuncStats.SampleSum); 1647 1648 ++ProfOverlap.UnionCount; 1649 ProfOverlap.UnionSample += FuncStats.SampleSum; 1650 } else { 1651 ++ProfOverlap.OverlapCount; 1652 1653 // Two functions match with each other. Compute function-level overlap and 1654 // aggregate them into profile-level overlap. 1655 FuncOverlap.BaseName = Match->second->getNameWithContext(); 1656 assert(BaseStats.count(FuncOverlap.BaseName) && 1657 "BaseStats should have records for all functions in base profile " 1658 "except inlinees"); 1659 FuncOverlap.BaseSample = BaseStats[FuncOverlap.BaseName].SampleSum; 1660 1661 FuncOverlap.Similarity = computeSampleFunctionOverlap( 1662 Match->second, &TestFunc.second, &FuncOverlap, FuncOverlap.BaseSample, 1663 FuncOverlap.TestSample); 1664 ProfOverlap.Similarity += 1665 weightByImportance(FuncOverlap.Similarity, FuncOverlap.BaseSample, 1666 FuncOverlap.TestSample); 1667 ProfOverlap.OverlapSample += FuncOverlap.OverlapSample; 1668 ProfOverlap.UnionSample += FuncOverlap.UnionSample; 1669 1670 // Accumulate the percentage of base unique and test unique samples into 1671 // ProfOverlap. 1672 ProfOverlap.BaseUniqueSample += FuncOverlap.BaseUniqueSample; 1673 ProfOverlap.TestUniqueSample += FuncOverlap.TestUniqueSample; 1674 1675 // Remove matched base functions for later reporting functions not found 1676 // in test profile. 1677 BaseFuncProf.erase(Match); 1678 } 1679 1680 // Print function-level similarity information if specified by options. 1681 assert(TestStats.count(FuncOverlap.TestName) && 1682 "TestStats should have records for all functions in test profile " 1683 "except inlinees"); 1684 if (TestStats[FuncOverlap.TestName].MaxSample >= FuncFilter.ValueCutoff || 1685 (Match != BaseFuncProf.end() && 1686 FuncOverlap.Similarity < LowSimilarityThreshold) || 1687 (Match != BaseFuncProf.end() && !FuncFilter.NameFilter.empty() && 1688 FuncOverlap.BaseName.find(FuncFilter.NameFilter) != 1689 FuncOverlap.BaseName.npos)) { 1690 assert(ProfOverlap.BaseSample > 0 && 1691 "Total samples in base profile should be greater than 0"); 1692 FuncOverlap.BaseWeight = 1693 static_cast<double>(FuncOverlap.BaseSample) / ProfOverlap.BaseSample; 1694 assert(ProfOverlap.TestSample > 0 && 1695 "Total samples in test profile should be greater than 0"); 1696 FuncOverlap.TestWeight = 1697 static_cast<double>(FuncOverlap.TestSample) / ProfOverlap.TestSample; 1698 FuncSimilarityDump.emplace(FuncOverlap.BaseWeight, FuncOverlap); 1699 } 1700 } 1701 1702 // Traverse through functions in base profile but not in test profile. 1703 for (const auto &F : BaseFuncProf) { 1704 assert(BaseStats.count(F.second->getNameWithContext()) && 1705 "BaseStats should have records for all functions in base profile " 1706 "except inlinees"); 1707 const FuncSampleStats &FuncStats = 1708 BaseStats[F.second->getNameWithContext()]; 1709 ++ProfOverlap.BaseUniqueCount; 1710 ProfOverlap.BaseUniqueSample += FuncStats.SampleSum; 1711 1712 updateHotBlockOverlap(FuncStats.SampleSum, 0, FuncStats.HotBlockCount); 1713 1714 double FuncSimilarity = computeSampleFunctionOverlap( 1715 nullptr, nullptr, nullptr, FuncStats.SampleSum, 0); 1716 ProfOverlap.Similarity += 1717 weightByImportance(FuncSimilarity, FuncStats.SampleSum, 0); 1718 1719 ProfOverlap.UnionSample += FuncStats.SampleSum; 1720 } 1721 1722 // Now, ProfSimilarity may be a little greater than 1 due to imprecision 1723 // of floating point accumulations. Make it 1.0 if the difference is below 1724 // Epsilon. 1725 ProfOverlap.Similarity = (std::fabs(ProfOverlap.Similarity - 1) < Epsilon) 1726 ? 1 1727 : ProfOverlap.Similarity; 1728 1729 computeHotFuncOverlap(); 1730 } 1731 1732 void SampleOverlapAggregator::initializeSampleProfileOverlap() { 1733 const auto &BaseProf = BaseReader->getProfiles(); 1734 for (const auto &I : BaseProf) { 1735 ++ProfOverlap.BaseCount; 1736 FuncSampleStats FuncStats; 1737 getFuncSampleStats(I.second, FuncStats, BaseHotThreshold); 1738 ProfOverlap.BaseSample += FuncStats.SampleSum; 1739 BaseStats.try_emplace(I.second.getNameWithContext(), FuncStats); 1740 } 1741 1742 const auto &TestProf = TestReader->getProfiles(); 1743 for (const auto &I : TestProf) { 1744 ++ProfOverlap.TestCount; 1745 FuncSampleStats FuncStats; 1746 getFuncSampleStats(I.second, FuncStats, TestHotThreshold); 1747 ProfOverlap.TestSample += FuncStats.SampleSum; 1748 TestStats.try_emplace(I.second.getNameWithContext(), FuncStats); 1749 } 1750 1751 ProfOverlap.BaseName = StringRef(BaseFilename); 1752 ProfOverlap.TestName = StringRef(TestFilename); 1753 } 1754 1755 void SampleOverlapAggregator::dumpFuncSimilarity(raw_fd_ostream &OS) const { 1756 using namespace sampleprof; 1757 1758 if (FuncSimilarityDump.empty()) 1759 return; 1760 1761 formatted_raw_ostream FOS(OS); 1762 FOS << "Function-level details:\n"; 1763 FOS << "Base weight"; 1764 FOS.PadToColumn(TestWeightCol); 1765 FOS << "Test weight"; 1766 FOS.PadToColumn(SimilarityCol); 1767 FOS << "Similarity"; 1768 FOS.PadToColumn(OverlapCol); 1769 FOS << "Overlap"; 1770 FOS.PadToColumn(BaseUniqueCol); 1771 FOS << "Base unique"; 1772 FOS.PadToColumn(TestUniqueCol); 1773 FOS << "Test unique"; 1774 FOS.PadToColumn(BaseSampleCol); 1775 FOS << "Base samples"; 1776 FOS.PadToColumn(TestSampleCol); 1777 FOS << "Test samples"; 1778 FOS.PadToColumn(FuncNameCol); 1779 FOS << "Function name\n"; 1780 for (const auto &F : FuncSimilarityDump) { 1781 double OverlapPercent = 1782 F.second.UnionSample > 0 1783 ? static_cast<double>(F.second.OverlapSample) / F.second.UnionSample 1784 : 0; 1785 double BaseUniquePercent = 1786 F.second.BaseSample > 0 1787 ? static_cast<double>(F.second.BaseUniqueSample) / 1788 F.second.BaseSample 1789 : 0; 1790 double TestUniquePercent = 1791 F.second.TestSample > 0 1792 ? static_cast<double>(F.second.TestUniqueSample) / 1793 F.second.TestSample 1794 : 0; 1795 1796 FOS << format("%.2f%%", F.second.BaseWeight * 100); 1797 FOS.PadToColumn(TestWeightCol); 1798 FOS << format("%.2f%%", F.second.TestWeight * 100); 1799 FOS.PadToColumn(SimilarityCol); 1800 FOS << format("%.2f%%", F.second.Similarity * 100); 1801 FOS.PadToColumn(OverlapCol); 1802 FOS << format("%.2f%%", OverlapPercent * 100); 1803 FOS.PadToColumn(BaseUniqueCol); 1804 FOS << format("%.2f%%", BaseUniquePercent * 100); 1805 FOS.PadToColumn(TestUniqueCol); 1806 FOS << format("%.2f%%", TestUniquePercent * 100); 1807 FOS.PadToColumn(BaseSampleCol); 1808 FOS << F.second.BaseSample; 1809 FOS.PadToColumn(TestSampleCol); 1810 FOS << F.second.TestSample; 1811 FOS.PadToColumn(FuncNameCol); 1812 FOS << F.second.TestName << "\n"; 1813 } 1814 } 1815 1816 void SampleOverlapAggregator::dumpProgramSummary(raw_fd_ostream &OS) const { 1817 OS << "Profile overlap infomation for base_profile: " << ProfOverlap.BaseName 1818 << " and test_profile: " << ProfOverlap.TestName << "\nProgram level:\n"; 1819 1820 OS << " Whole program profile similarity: " 1821 << format("%.3f%%", ProfOverlap.Similarity * 100) << "\n"; 1822 1823 assert(ProfOverlap.UnionSample > 0 && 1824 "Total samples in two profile should be greater than 0"); 1825 double OverlapPercent = 1826 static_cast<double>(ProfOverlap.OverlapSample) / ProfOverlap.UnionSample; 1827 assert(ProfOverlap.BaseSample > 0 && 1828 "Total samples in base profile should be greater than 0"); 1829 double BaseUniquePercent = static_cast<double>(ProfOverlap.BaseUniqueSample) / 1830 ProfOverlap.BaseSample; 1831 assert(ProfOverlap.TestSample > 0 && 1832 "Total samples in test profile should be greater than 0"); 1833 double TestUniquePercent = static_cast<double>(ProfOverlap.TestUniqueSample) / 1834 ProfOverlap.TestSample; 1835 1836 OS << " Whole program sample overlap: " 1837 << format("%.3f%%", OverlapPercent * 100) << "\n"; 1838 OS << " percentage of samples unique in base profile: " 1839 << format("%.3f%%", BaseUniquePercent * 100) << "\n"; 1840 OS << " percentage of samples unique in test profile: " 1841 << format("%.3f%%", TestUniquePercent * 100) << "\n"; 1842 OS << " total samples in base profile: " << ProfOverlap.BaseSample << "\n" 1843 << " total samples in test profile: " << ProfOverlap.TestSample << "\n"; 1844 1845 assert(ProfOverlap.UnionCount > 0 && 1846 "There should be at least one function in two input profiles"); 1847 double FuncOverlapPercent = 1848 static_cast<double>(ProfOverlap.OverlapCount) / ProfOverlap.UnionCount; 1849 OS << " Function overlap: " << format("%.3f%%", FuncOverlapPercent * 100) 1850 << "\n"; 1851 OS << " overlap functions: " << ProfOverlap.OverlapCount << "\n"; 1852 OS << " functions unique in base profile: " << ProfOverlap.BaseUniqueCount 1853 << "\n"; 1854 OS << " functions unique in test profile: " << ProfOverlap.TestUniqueCount 1855 << "\n"; 1856 } 1857 1858 void SampleOverlapAggregator::dumpHotFuncAndBlockOverlap( 1859 raw_fd_ostream &OS) const { 1860 assert(HotFuncOverlap.UnionCount > 0 && 1861 "There should be at least one hot function in two input profiles"); 1862 OS << " Hot-function overlap: " 1863 << format("%.3f%%", static_cast<double>(HotFuncOverlap.OverlapCount) / 1864 HotFuncOverlap.UnionCount * 100) 1865 << "\n"; 1866 OS << " overlap hot functions: " << HotFuncOverlap.OverlapCount << "\n"; 1867 OS << " hot functions unique in base profile: " 1868 << HotFuncOverlap.BaseCount - HotFuncOverlap.OverlapCount << "\n"; 1869 OS << " hot functions unique in test profile: " 1870 << HotFuncOverlap.TestCount - HotFuncOverlap.OverlapCount << "\n"; 1871 1872 assert(HotBlockOverlap.UnionCount > 0 && 1873 "There should be at least one hot block in two input profiles"); 1874 OS << " Hot-block overlap: " 1875 << format("%.3f%%", static_cast<double>(HotBlockOverlap.OverlapCount) / 1876 HotBlockOverlap.UnionCount * 100) 1877 << "\n"; 1878 OS << " overlap hot blocks: " << HotBlockOverlap.OverlapCount << "\n"; 1879 OS << " hot blocks unique in base profile: " 1880 << HotBlockOverlap.BaseCount - HotBlockOverlap.OverlapCount << "\n"; 1881 OS << " hot blocks unique in test profile: " 1882 << HotBlockOverlap.TestCount - HotBlockOverlap.OverlapCount << "\n"; 1883 } 1884 1885 std::error_code SampleOverlapAggregator::loadProfiles() { 1886 using namespace sampleprof; 1887 1888 LLVMContext Context; 1889 auto BaseReaderOrErr = SampleProfileReader::create(BaseFilename, Context, 1890 FSDiscriminatorPassOption); 1891 if (std::error_code EC = BaseReaderOrErr.getError()) 1892 exitWithErrorCode(EC, BaseFilename); 1893 1894 auto TestReaderOrErr = SampleProfileReader::create(TestFilename, Context, 1895 FSDiscriminatorPassOption); 1896 if (std::error_code EC = TestReaderOrErr.getError()) 1897 exitWithErrorCode(EC, TestFilename); 1898 1899 BaseReader = std::move(BaseReaderOrErr.get()); 1900 TestReader = std::move(TestReaderOrErr.get()); 1901 1902 if (std::error_code EC = BaseReader->read()) 1903 exitWithErrorCode(EC, BaseFilename); 1904 if (std::error_code EC = TestReader->read()) 1905 exitWithErrorCode(EC, TestFilename); 1906 if (BaseReader->profileIsProbeBased() != TestReader->profileIsProbeBased()) 1907 exitWithError( 1908 "cannot compare probe-based profile with non-probe-based profile"); 1909 if (BaseReader->profileIsCS() != TestReader->profileIsCS()) 1910 exitWithError("cannot compare CS profile with non-CS profile"); 1911 1912 // Load BaseHotThreshold and TestHotThreshold as 99-percentile threshold in 1913 // profile summary. 1914 const uint64_t HotCutoff = 990000; 1915 ProfileSummary &BasePS = BaseReader->getSummary(); 1916 for (const auto &SummaryEntry : BasePS.getDetailedSummary()) { 1917 if (SummaryEntry.Cutoff == HotCutoff) { 1918 BaseHotThreshold = SummaryEntry.MinCount; 1919 break; 1920 } 1921 } 1922 1923 ProfileSummary &TestPS = TestReader->getSummary(); 1924 for (const auto &SummaryEntry : TestPS.getDetailedSummary()) { 1925 if (SummaryEntry.Cutoff == HotCutoff) { 1926 TestHotThreshold = SummaryEntry.MinCount; 1927 break; 1928 } 1929 } 1930 return std::error_code(); 1931 } 1932 1933 void overlapSampleProfile(const std::string &BaseFilename, 1934 const std::string &TestFilename, 1935 const OverlapFuncFilters &FuncFilter, 1936 uint64_t SimilarityCutoff, raw_fd_ostream &OS) { 1937 using namespace sampleprof; 1938 1939 // We use 0.000005 to initialize OverlapAggr.Epsilon because the final metrics 1940 // report 2--3 places after decimal point in percentage numbers. 1941 SampleOverlapAggregator OverlapAggr( 1942 BaseFilename, TestFilename, 1943 static_cast<double>(SimilarityCutoff) / 1000000, 0.000005, FuncFilter); 1944 if (std::error_code EC = OverlapAggr.loadProfiles()) 1945 exitWithErrorCode(EC); 1946 1947 OverlapAggr.initializeSampleProfileOverlap(); 1948 if (OverlapAggr.detectZeroSampleProfile(OS)) 1949 return; 1950 1951 OverlapAggr.computeSampleProfileOverlap(OS); 1952 1953 OverlapAggr.dumpProgramSummary(OS); 1954 OverlapAggr.dumpHotFuncAndBlockOverlap(OS); 1955 OverlapAggr.dumpFuncSimilarity(OS); 1956 } 1957 1958 static int overlap_main(int argc, const char *argv[]) { 1959 cl::opt<std::string> BaseFilename(cl::Positional, cl::Required, 1960 cl::desc("<base profile file>")); 1961 cl::opt<std::string> TestFilename(cl::Positional, cl::Required, 1962 cl::desc("<test profile file>")); 1963 cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"), 1964 cl::desc("Output file")); 1965 cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output)); 1966 cl::opt<bool> IsCS( 1967 "cs", cl::init(false), 1968 cl::desc("For context sensitive PGO counts. Does not work with CSSPGO.")); 1969 cl::opt<unsigned long long> ValueCutoff( 1970 "value-cutoff", cl::init(-1), 1971 cl::desc( 1972 "Function level overlap information for every function (with calling " 1973 "context for csspgo) in test " 1974 "profile with max count value greater then the parameter value")); 1975 cl::opt<std::string> FuncNameFilter( 1976 "function", 1977 cl::desc("Function level overlap information for matching functions. For " 1978 "CSSPGO this takes a a function name with calling context")); 1979 cl::opt<unsigned long long> SimilarityCutoff( 1980 "similarity-cutoff", cl::init(0), 1981 cl::desc("For sample profiles, list function names (with calling context " 1982 "for csspgo) for overlapped functions " 1983 "with similarities below the cutoff (percentage times 10000).")); 1984 cl::opt<ProfileKinds> ProfileKind( 1985 cl::desc("Profile kind:"), cl::init(instr), 1986 cl::values(clEnumVal(instr, "Instrumentation profile (default)"), 1987 clEnumVal(sample, "Sample profile"))); 1988 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n"); 1989 1990 std::error_code EC; 1991 raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_TextWithCRLF); 1992 if (EC) 1993 exitWithErrorCode(EC, Output); 1994 1995 if (ProfileKind == instr) 1996 overlapInstrProfile(BaseFilename, TestFilename, 1997 OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS, 1998 IsCS); 1999 else 2000 overlapSampleProfile(BaseFilename, TestFilename, 2001 OverlapFuncFilters{ValueCutoff, FuncNameFilter}, 2002 SimilarityCutoff, OS); 2003 2004 return 0; 2005 } 2006 2007 typedef struct ValueSitesStats { 2008 ValueSitesStats() 2009 : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0), 2010 TotalNumValues(0) {} 2011 uint64_t TotalNumValueSites; 2012 uint64_t TotalNumValueSitesWithValueProfile; 2013 uint64_t TotalNumValues; 2014 std::vector<unsigned> ValueSitesHistogram; 2015 } ValueSitesStats; 2016 2017 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK, 2018 ValueSitesStats &Stats, raw_fd_ostream &OS, 2019 InstrProfSymtab *Symtab) { 2020 uint32_t NS = Func.getNumValueSites(VK); 2021 Stats.TotalNumValueSites += NS; 2022 for (size_t I = 0; I < NS; ++I) { 2023 uint32_t NV = Func.getNumValueDataForSite(VK, I); 2024 std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I); 2025 Stats.TotalNumValues += NV; 2026 if (NV) { 2027 Stats.TotalNumValueSitesWithValueProfile++; 2028 if (NV > Stats.ValueSitesHistogram.size()) 2029 Stats.ValueSitesHistogram.resize(NV, 0); 2030 Stats.ValueSitesHistogram[NV - 1]++; 2031 } 2032 2033 uint64_t SiteSum = 0; 2034 for (uint32_t V = 0; V < NV; V++) 2035 SiteSum += VD[V].Count; 2036 if (SiteSum == 0) 2037 SiteSum = 1; 2038 2039 for (uint32_t V = 0; V < NV; V++) { 2040 OS << "\t[ " << format("%2u", I) << ", "; 2041 if (Symtab == nullptr) 2042 OS << format("%4" PRIu64, VD[V].Value); 2043 else 2044 OS << Symtab->getFuncName(VD[V].Value); 2045 OS << ", " << format("%10" PRId64, VD[V].Count) << " ] (" 2046 << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n"; 2047 } 2048 } 2049 } 2050 2051 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK, 2052 ValueSitesStats &Stats) { 2053 OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n"; 2054 OS << " Total number of sites with values: " 2055 << Stats.TotalNumValueSitesWithValueProfile << "\n"; 2056 OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n"; 2057 2058 OS << " Value sites histogram:\n\tNumTargets, SiteCount\n"; 2059 for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) { 2060 if (Stats.ValueSitesHistogram[I] > 0) 2061 OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n"; 2062 } 2063 } 2064 2065 static int showInstrProfile(const std::string &Filename, bool ShowCounts, 2066 uint32_t TopN, bool ShowIndirectCallTargets, 2067 bool ShowMemOPSizes, bool ShowDetailedSummary, 2068 std::vector<uint32_t> DetailedSummaryCutoffs, 2069 bool ShowAllFunctions, bool ShowCS, 2070 uint64_t ValueCutoff, bool OnlyListBelow, 2071 const std::string &ShowFunction, bool TextFormat, 2072 raw_fd_ostream &OS) { 2073 auto ReaderOrErr = InstrProfReader::create(Filename); 2074 std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs); 2075 if (ShowDetailedSummary && Cutoffs.empty()) { 2076 Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990}; 2077 } 2078 InstrProfSummaryBuilder Builder(std::move(Cutoffs)); 2079 if (Error E = ReaderOrErr.takeError()) 2080 exitWithError(std::move(E), Filename); 2081 2082 auto Reader = std::move(ReaderOrErr.get()); 2083 bool IsIRInstr = Reader->isIRLevelProfile(); 2084 size_t ShownFunctions = 0; 2085 size_t BelowCutoffFunctions = 0; 2086 int NumVPKind = IPVK_Last - IPVK_First + 1; 2087 std::vector<ValueSitesStats> VPStats(NumVPKind); 2088 2089 auto MinCmp = [](const std::pair<std::string, uint64_t> &v1, 2090 const std::pair<std::string, uint64_t> &v2) { 2091 return v1.second > v2.second; 2092 }; 2093 2094 std::priority_queue<std::pair<std::string, uint64_t>, 2095 std::vector<std::pair<std::string, uint64_t>>, 2096 decltype(MinCmp)> 2097 HottestFuncs(MinCmp); 2098 2099 if (!TextFormat && OnlyListBelow) { 2100 OS << "The list of functions with the maximum counter less than " 2101 << ValueCutoff << ":\n"; 2102 } 2103 2104 // Add marker so that IR-level instrumentation round-trips properly. 2105 if (TextFormat && IsIRInstr) 2106 OS << ":ir\n"; 2107 2108 for (const auto &Func : *Reader) { 2109 if (Reader->isIRLevelProfile()) { 2110 bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash); 2111 if (FuncIsCS != ShowCS) 2112 continue; 2113 } 2114 bool Show = 2115 ShowAllFunctions || (!ShowFunction.empty() && 2116 Func.Name.find(ShowFunction) != Func.Name.npos); 2117 2118 bool doTextFormatDump = (Show && TextFormat); 2119 2120 if (doTextFormatDump) { 2121 InstrProfSymtab &Symtab = Reader->getSymtab(); 2122 InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab, 2123 OS); 2124 continue; 2125 } 2126 2127 assert(Func.Counts.size() > 0 && "function missing entry counter"); 2128 Builder.addRecord(Func); 2129 2130 uint64_t FuncMax = 0; 2131 uint64_t FuncSum = 0; 2132 for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) { 2133 if (Func.Counts[I] == (uint64_t)-1) 2134 continue; 2135 FuncMax = std::max(FuncMax, Func.Counts[I]); 2136 FuncSum += Func.Counts[I]; 2137 } 2138 2139 if (FuncMax < ValueCutoff) { 2140 ++BelowCutoffFunctions; 2141 if (OnlyListBelow) { 2142 OS << " " << Func.Name << ": (Max = " << FuncMax 2143 << " Sum = " << FuncSum << ")\n"; 2144 } 2145 continue; 2146 } else if (OnlyListBelow) 2147 continue; 2148 2149 if (TopN) { 2150 if (HottestFuncs.size() == TopN) { 2151 if (HottestFuncs.top().second < FuncMax) { 2152 HottestFuncs.pop(); 2153 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax)); 2154 } 2155 } else 2156 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax)); 2157 } 2158 2159 if (Show) { 2160 if (!ShownFunctions) 2161 OS << "Counters:\n"; 2162 2163 ++ShownFunctions; 2164 2165 OS << " " << Func.Name << ":\n" 2166 << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n" 2167 << " Counters: " << Func.Counts.size() << "\n"; 2168 if (!IsIRInstr) 2169 OS << " Function count: " << Func.Counts[0] << "\n"; 2170 2171 if (ShowIndirectCallTargets) 2172 OS << " Indirect Call Site Count: " 2173 << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n"; 2174 2175 uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize); 2176 if (ShowMemOPSizes && NumMemOPCalls > 0) 2177 OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls 2178 << "\n"; 2179 2180 if (ShowCounts) { 2181 OS << " Block counts: ["; 2182 size_t Start = (IsIRInstr ? 0 : 1); 2183 for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) { 2184 OS << (I == Start ? "" : ", ") << Func.Counts[I]; 2185 } 2186 OS << "]\n"; 2187 } 2188 2189 if (ShowIndirectCallTargets) { 2190 OS << " Indirect Target Results:\n"; 2191 traverseAllValueSites(Func, IPVK_IndirectCallTarget, 2192 VPStats[IPVK_IndirectCallTarget], OS, 2193 &(Reader->getSymtab())); 2194 } 2195 2196 if (ShowMemOPSizes && NumMemOPCalls > 0) { 2197 OS << " Memory Intrinsic Size Results:\n"; 2198 traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS, 2199 nullptr); 2200 } 2201 } 2202 } 2203 if (Reader->hasError()) 2204 exitWithError(Reader->getError(), Filename); 2205 2206 if (TextFormat) 2207 return 0; 2208 std::unique_ptr<ProfileSummary> PS(Builder.getSummary()); 2209 bool IsIR = Reader->isIRLevelProfile(); 2210 OS << "Instrumentation level: " << (IsIR ? "IR" : "Front-end"); 2211 if (IsIR) 2212 OS << " entry_first = " << Reader->instrEntryBBEnabled(); 2213 OS << "\n"; 2214 if (ShowAllFunctions || !ShowFunction.empty()) 2215 OS << "Functions shown: " << ShownFunctions << "\n"; 2216 OS << "Total functions: " << PS->getNumFunctions() << "\n"; 2217 if (ValueCutoff > 0) { 2218 OS << "Number of functions with maximum count (< " << ValueCutoff 2219 << "): " << BelowCutoffFunctions << "\n"; 2220 OS << "Number of functions with maximum count (>= " << ValueCutoff 2221 << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n"; 2222 } 2223 OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n"; 2224 OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n"; 2225 2226 if (TopN) { 2227 std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs; 2228 while (!HottestFuncs.empty()) { 2229 SortedHottestFuncs.emplace_back(HottestFuncs.top()); 2230 HottestFuncs.pop(); 2231 } 2232 OS << "Top " << TopN 2233 << " functions with the largest internal block counts: \n"; 2234 for (auto &hotfunc : llvm::reverse(SortedHottestFuncs)) 2235 OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n"; 2236 } 2237 2238 if (ShownFunctions && ShowIndirectCallTargets) { 2239 OS << "Statistics for indirect call sites profile:\n"; 2240 showValueSitesStats(OS, IPVK_IndirectCallTarget, 2241 VPStats[IPVK_IndirectCallTarget]); 2242 } 2243 2244 if (ShownFunctions && ShowMemOPSizes) { 2245 OS << "Statistics for memory intrinsic calls sizes profile:\n"; 2246 showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]); 2247 } 2248 2249 if (ShowDetailedSummary) { 2250 OS << "Total number of blocks: " << PS->getNumCounts() << "\n"; 2251 OS << "Total count: " << PS->getTotalCount() << "\n"; 2252 PS->printDetailedSummary(OS); 2253 } 2254 return 0; 2255 } 2256 2257 static void showSectionInfo(sampleprof::SampleProfileReader *Reader, 2258 raw_fd_ostream &OS) { 2259 if (!Reader->dumpSectionInfo(OS)) { 2260 WithColor::warning() << "-show-sec-info-only is only supported for " 2261 << "sample profile in extbinary format and is " 2262 << "ignored for other formats.\n"; 2263 return; 2264 } 2265 } 2266 2267 namespace { 2268 struct HotFuncInfo { 2269 StringRef FuncName; 2270 uint64_t TotalCount; 2271 double TotalCountPercent; 2272 uint64_t MaxCount; 2273 uint64_t EntryCount; 2274 2275 HotFuncInfo() 2276 : FuncName(), TotalCount(0), TotalCountPercent(0.0f), MaxCount(0), 2277 EntryCount(0) {} 2278 2279 HotFuncInfo(StringRef FN, uint64_t TS, double TSP, uint64_t MS, uint64_t ES) 2280 : FuncName(FN), TotalCount(TS), TotalCountPercent(TSP), MaxCount(MS), 2281 EntryCount(ES) {} 2282 }; 2283 } // namespace 2284 2285 // Print out detailed information about hot functions in PrintValues vector. 2286 // Users specify titles and offset of every columns through ColumnTitle and 2287 // ColumnOffset. The size of ColumnTitle and ColumnOffset need to be the same 2288 // and at least 4. Besides, users can optionally give a HotFuncMetric string to 2289 // print out or let it be an empty string. 2290 static void dumpHotFunctionList(const std::vector<std::string> &ColumnTitle, 2291 const std::vector<int> &ColumnOffset, 2292 const std::vector<HotFuncInfo> &PrintValues, 2293 uint64_t HotFuncCount, uint64_t TotalFuncCount, 2294 uint64_t HotProfCount, uint64_t TotalProfCount, 2295 const std::string &HotFuncMetric, 2296 raw_fd_ostream &OS) { 2297 assert(ColumnOffset.size() == ColumnTitle.size() && 2298 "ColumnOffset and ColumnTitle should have the same size"); 2299 assert(ColumnTitle.size() >= 4 && 2300 "ColumnTitle should have at least 4 elements"); 2301 assert(TotalFuncCount > 0 && 2302 "There should be at least one function in the profile"); 2303 double TotalProfPercent = 0; 2304 if (TotalProfCount > 0) 2305 TotalProfPercent = static_cast<double>(HotProfCount) / TotalProfCount * 100; 2306 2307 formatted_raw_ostream FOS(OS); 2308 FOS << HotFuncCount << " out of " << TotalFuncCount 2309 << " functions with profile (" 2310 << format("%.2f%%", 2311 (static_cast<double>(HotFuncCount) / TotalFuncCount * 100)) 2312 << ") are considered hot functions"; 2313 if (!HotFuncMetric.empty()) 2314 FOS << " (" << HotFuncMetric << ")"; 2315 FOS << ".\n"; 2316 FOS << HotProfCount << " out of " << TotalProfCount << " profile counts (" 2317 << format("%.2f%%", TotalProfPercent) << ") are from hot functions.\n"; 2318 2319 for (size_t I = 0; I < ColumnTitle.size(); ++I) { 2320 FOS.PadToColumn(ColumnOffset[I]); 2321 FOS << ColumnTitle[I]; 2322 } 2323 FOS << "\n"; 2324 2325 for (const HotFuncInfo &R : PrintValues) { 2326 FOS.PadToColumn(ColumnOffset[0]); 2327 FOS << R.TotalCount << " (" << format("%.2f%%", R.TotalCountPercent) << ")"; 2328 FOS.PadToColumn(ColumnOffset[1]); 2329 FOS << R.MaxCount; 2330 FOS.PadToColumn(ColumnOffset[2]); 2331 FOS << R.EntryCount; 2332 FOS.PadToColumn(ColumnOffset[3]); 2333 FOS << R.FuncName << "\n"; 2334 } 2335 } 2336 2337 static int 2338 showHotFunctionList(const StringMap<sampleprof::FunctionSamples> &Profiles, 2339 ProfileSummary &PS, raw_fd_ostream &OS) { 2340 using namespace sampleprof; 2341 2342 const uint32_t HotFuncCutoff = 990000; 2343 auto &SummaryVector = PS.getDetailedSummary(); 2344 uint64_t MinCountThreshold = 0; 2345 for (const ProfileSummaryEntry &SummaryEntry : SummaryVector) { 2346 if (SummaryEntry.Cutoff == HotFuncCutoff) { 2347 MinCountThreshold = SummaryEntry.MinCount; 2348 break; 2349 } 2350 } 2351 2352 // Traverse all functions in the profile and keep only hot functions. 2353 // The following loop also calculates the sum of total samples of all 2354 // functions. 2355 std::multimap<uint64_t, std::pair<const FunctionSamples *, const uint64_t>, 2356 std::greater<uint64_t>> 2357 HotFunc; 2358 uint64_t ProfileTotalSample = 0; 2359 uint64_t HotFuncSample = 0; 2360 uint64_t HotFuncCount = 0; 2361 2362 for (const auto &I : Profiles) { 2363 FuncSampleStats FuncStats; 2364 const FunctionSamples &FuncProf = I.second; 2365 ProfileTotalSample += FuncProf.getTotalSamples(); 2366 getFuncSampleStats(FuncProf, FuncStats, MinCountThreshold); 2367 2368 if (isFunctionHot(FuncStats, MinCountThreshold)) { 2369 HotFunc.emplace(FuncProf.getTotalSamples(), 2370 std::make_pair(&(I.second), FuncStats.MaxSample)); 2371 HotFuncSample += FuncProf.getTotalSamples(); 2372 ++HotFuncCount; 2373 } 2374 } 2375 2376 std::vector<std::string> ColumnTitle{"Total sample (%)", "Max sample", 2377 "Entry sample", "Function name"}; 2378 std::vector<int> ColumnOffset{0, 24, 42, 58}; 2379 std::string Metric = 2380 std::string("max sample >= ") + std::to_string(MinCountThreshold); 2381 std::vector<HotFuncInfo> PrintValues; 2382 for (const auto &FuncPair : HotFunc) { 2383 const FunctionSamples &Func = *FuncPair.second.first; 2384 double TotalSamplePercent = 2385 (ProfileTotalSample > 0) 2386 ? (Func.getTotalSamples() * 100.0) / ProfileTotalSample 2387 : 0; 2388 PrintValues.emplace_back(HotFuncInfo( 2389 Func.getNameWithContext(), Func.getTotalSamples(), TotalSamplePercent, 2390 FuncPair.second.second, Func.getEntrySamples())); 2391 } 2392 dumpHotFunctionList(ColumnTitle, ColumnOffset, PrintValues, HotFuncCount, 2393 Profiles.size(), HotFuncSample, ProfileTotalSample, 2394 Metric, OS); 2395 2396 return 0; 2397 } 2398 2399 static int showSampleProfile(const std::string &Filename, bool ShowCounts, 2400 bool ShowAllFunctions, bool ShowDetailedSummary, 2401 const std::string &ShowFunction, 2402 bool ShowProfileSymbolList, 2403 bool ShowSectionInfoOnly, bool ShowHotFuncList, 2404 raw_fd_ostream &OS) { 2405 using namespace sampleprof; 2406 LLVMContext Context; 2407 auto ReaderOrErr = 2408 SampleProfileReader::create(Filename, Context, FSDiscriminatorPassOption); 2409 if (std::error_code EC = ReaderOrErr.getError()) 2410 exitWithErrorCode(EC, Filename); 2411 2412 auto Reader = std::move(ReaderOrErr.get()); 2413 if (ShowSectionInfoOnly) { 2414 showSectionInfo(Reader.get(), OS); 2415 return 0; 2416 } 2417 2418 if (std::error_code EC = Reader->read()) 2419 exitWithErrorCode(EC, Filename); 2420 2421 if (ShowAllFunctions || ShowFunction.empty()) 2422 Reader->dump(OS); 2423 else 2424 Reader->dumpFunctionProfile(ShowFunction, OS); 2425 2426 if (ShowProfileSymbolList) { 2427 std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList = 2428 Reader->getProfileSymbolList(); 2429 ReaderList->dump(OS); 2430 } 2431 2432 if (ShowDetailedSummary) { 2433 auto &PS = Reader->getSummary(); 2434 PS.printSummary(OS); 2435 PS.printDetailedSummary(OS); 2436 } 2437 2438 if (ShowHotFuncList) 2439 showHotFunctionList(Reader->getProfiles(), Reader->getSummary(), OS); 2440 2441 return 0; 2442 } 2443 2444 static int show_main(int argc, const char *argv[]) { 2445 cl::opt<std::string> Filename(cl::Positional, cl::Required, 2446 cl::desc("<profdata-file>")); 2447 2448 cl::opt<bool> ShowCounts("counts", cl::init(false), 2449 cl::desc("Show counter values for shown functions")); 2450 cl::opt<bool> TextFormat( 2451 "text", cl::init(false), 2452 cl::desc("Show instr profile data in text dump format")); 2453 cl::opt<bool> ShowIndirectCallTargets( 2454 "ic-targets", cl::init(false), 2455 cl::desc("Show indirect call site target values for shown functions")); 2456 cl::opt<bool> ShowMemOPSizes( 2457 "memop-sizes", cl::init(false), 2458 cl::desc("Show the profiled sizes of the memory intrinsic calls " 2459 "for shown functions")); 2460 cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false), 2461 cl::desc("Show detailed profile summary")); 2462 cl::list<uint32_t> DetailedSummaryCutoffs( 2463 cl::CommaSeparated, "detailed-summary-cutoffs", 2464 cl::desc( 2465 "Cutoff percentages (times 10000) for generating detailed summary"), 2466 cl::value_desc("800000,901000,999999")); 2467 cl::opt<bool> ShowHotFuncList( 2468 "hot-func-list", cl::init(false), 2469 cl::desc("Show profile summary of a list of hot functions")); 2470 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false), 2471 cl::desc("Details for every function")); 2472 cl::opt<bool> ShowCS("showcs", cl::init(false), 2473 cl::desc("Show context sensitive counts")); 2474 cl::opt<std::string> ShowFunction("function", 2475 cl::desc("Details for matching functions")); 2476 2477 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), 2478 cl::init("-"), cl::desc("Output file")); 2479 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), 2480 cl::aliasopt(OutputFilename)); 2481 cl::opt<ProfileKinds> ProfileKind( 2482 cl::desc("Profile kind:"), cl::init(instr), 2483 cl::values(clEnumVal(instr, "Instrumentation profile (default)"), 2484 clEnumVal(sample, "Sample profile"))); 2485 cl::opt<uint32_t> TopNFunctions( 2486 "topn", cl::init(0), 2487 cl::desc("Show the list of functions with the largest internal counts")); 2488 cl::opt<uint32_t> ValueCutoff( 2489 "value-cutoff", cl::init(0), 2490 cl::desc("Set the count value cutoff. Functions with the maximum count " 2491 "less than this value will not be printed out. (Default is 0)")); 2492 cl::opt<bool> OnlyListBelow( 2493 "list-below-cutoff", cl::init(false), 2494 cl::desc("Only output names of functions whose max count values are " 2495 "below the cutoff value")); 2496 cl::opt<bool> ShowProfileSymbolList( 2497 "show-prof-sym-list", cl::init(false), 2498 cl::desc("Show profile symbol list if it exists in the profile. ")); 2499 cl::opt<bool> ShowSectionInfoOnly( 2500 "show-sec-info-only", cl::init(false), 2501 cl::desc("Show the information of each section in the sample profile. " 2502 "The flag is only usable when the sample profile is in " 2503 "extbinary format")); 2504 2505 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n"); 2506 2507 if (OutputFilename.empty()) 2508 OutputFilename = "-"; 2509 2510 if (Filename == OutputFilename) { 2511 errs() << sys::path::filename(argv[0]) 2512 << ": Input file name cannot be the same as the output file name!\n"; 2513 return 1; 2514 } 2515 2516 std::error_code EC; 2517 raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF); 2518 if (EC) 2519 exitWithErrorCode(EC, OutputFilename); 2520 2521 if (ShowAllFunctions && !ShowFunction.empty()) 2522 WithColor::warning() << "-function argument ignored: showing all functions\n"; 2523 2524 if (ProfileKind == instr) 2525 return showInstrProfile(Filename, ShowCounts, TopNFunctions, 2526 ShowIndirectCallTargets, ShowMemOPSizes, 2527 ShowDetailedSummary, DetailedSummaryCutoffs, 2528 ShowAllFunctions, ShowCS, ValueCutoff, 2529 OnlyListBelow, ShowFunction, TextFormat, OS); 2530 else 2531 return showSampleProfile(Filename, ShowCounts, ShowAllFunctions, 2532 ShowDetailedSummary, ShowFunction, 2533 ShowProfileSymbolList, ShowSectionInfoOnly, 2534 ShowHotFuncList, OS); 2535 } 2536 2537 int main(int argc, const char *argv[]) { 2538 InitLLVM X(argc, argv); 2539 2540 StringRef ProgName(sys::path::filename(argv[0])); 2541 if (argc > 1) { 2542 int (*func)(int, const char *[]) = nullptr; 2543 2544 if (strcmp(argv[1], "merge") == 0) 2545 func = merge_main; 2546 else if (strcmp(argv[1], "show") == 0) 2547 func = show_main; 2548 else if (strcmp(argv[1], "overlap") == 0) 2549 func = overlap_main; 2550 2551 if (func) { 2552 std::string Invocation(ProgName.str() + " " + argv[1]); 2553 argv[1] = Invocation.c_str(); 2554 return func(argc - 1, argv + 1); 2555 } 2556 2557 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 || 2558 strcmp(argv[1], "--help") == 0) { 2559 2560 errs() << "OVERVIEW: LLVM profile data tools\n\n" 2561 << "USAGE: " << ProgName << " <command> [args...]\n" 2562 << "USAGE: " << ProgName << " <command> -help\n\n" 2563 << "See each individual command --help for more details.\n" 2564 << "Available commands: merge, show, overlap\n"; 2565 return 0; 2566 } 2567 } 2568 2569 if (argc < 2) 2570 errs() << ProgName << ": No command specified!\n"; 2571 else 2572 errs() << ProgName << ": Unknown command!\n"; 2573 2574 errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n"; 2575 return 1; 2576 } 2577