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