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