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