1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // llvm-profdata merges .profdata files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/SmallSet.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/Object/Binary.h"
19 #include "llvm/ProfileData/InstrProfCorrelator.h"
20 #include "llvm/ProfileData/InstrProfReader.h"
21 #include "llvm/ProfileData/InstrProfWriter.h"
22 #include "llvm/ProfileData/MemProf.h"
23 #include "llvm/ProfileData/ProfileCommon.h"
24 #include "llvm/ProfileData/RawMemProfReader.h"
25 #include "llvm/ProfileData/SampleProfReader.h"
26 #include "llvm/ProfileData/SampleProfWriter.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Discriminator.h"
29 #include "llvm/Support/Errc.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/InitLLVM.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/ThreadPool.h"
37 #include "llvm/Support/Threading.h"
38 #include "llvm/Support/WithColor.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <algorithm>
41 
42 using namespace llvm;
43 
44 enum ProfileFormat {
45   PF_None = 0,
46   PF_Text,
47   PF_Compact_Binary,
48   PF_Ext_Binary,
49   PF_GCC,
50   PF_Binary
51 };
52 
53 static void warn(Twine Message, std::string Whence = "",
54                  std::string Hint = "") {
55   WithColor::warning();
56   if (!Whence.empty())
57     errs() << Whence << ": ";
58   errs() << Message << "\n";
59   if (!Hint.empty())
60     WithColor::note() << Hint << "\n";
61 }
62 
63 static void warn(Error E, StringRef Whence = "") {
64   if (E.isA<InstrProfError>()) {
65     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
66       warn(IPE.message(), std::string(Whence), std::string(""));
67     });
68   }
69 }
70 
71 static void exitWithError(Twine Message, std::string Whence = "",
72                           std::string Hint = "") {
73   WithColor::error();
74   if (!Whence.empty())
75     errs() << Whence << ": ";
76   errs() << Message << "\n";
77   if (!Hint.empty())
78     WithColor::note() << Hint << "\n";
79   ::exit(1);
80 }
81 
82 static void exitWithError(Error E, StringRef Whence = "") {
83   if (E.isA<InstrProfError>()) {
84     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
85       instrprof_error instrError = IPE.get();
86       StringRef Hint = "";
87       if (instrError == instrprof_error::unrecognized_format) {
88         // Hint in case user missed specifying the profile type.
89         Hint = "Perhaps you forgot to use the --sample or --memory option?";
90       }
91       exitWithError(IPE.message(), std::string(Whence), std::string(Hint));
92     });
93     return;
94   }
95 
96   exitWithError(toString(std::move(E)), std::string(Whence));
97 }
98 
99 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
100   exitWithError(EC.message(), std::string(Whence));
101 }
102 
103 namespace {
104 enum ProfileKinds { instr, sample, memory };
105 enum FailureMode { failIfAnyAreInvalid, failIfAllAreInvalid };
106 }
107 
108 static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
109                                  StringRef Whence = "") {
110   if (FailMode == failIfAnyAreInvalid)
111     exitWithErrorCode(EC, Whence);
112   else
113     warn(EC.message(), std::string(Whence));
114 }
115 
116 static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
117                                    StringRef WhenceFunction = "",
118                                    bool ShowHint = true) {
119   if (!WhenceFile.empty())
120     errs() << WhenceFile << ": ";
121   if (!WhenceFunction.empty())
122     errs() << WhenceFunction << ": ";
123 
124   auto IPE = instrprof_error::success;
125   E = handleErrors(std::move(E),
126                    [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
127                      IPE = E->get();
128                      return Error(std::move(E));
129                    });
130   errs() << toString(std::move(E)) << "\n";
131 
132   if (ShowHint) {
133     StringRef Hint = "";
134     if (IPE != instrprof_error::success) {
135       switch (IPE) {
136       case instrprof_error::hash_mismatch:
137       case instrprof_error::count_mismatch:
138       case instrprof_error::value_site_count_mismatch:
139         Hint = "Make sure that all profile data to be merged is generated "
140                "from the same binary.";
141         break;
142       default:
143         break;
144       }
145     }
146 
147     if (!Hint.empty())
148       errs() << Hint << "\n";
149   }
150 }
151 
152 namespace {
153 /// A remapper from original symbol names to new symbol names based on a file
154 /// containing a list of mappings from old name to new name.
155 class SymbolRemapper {
156   std::unique_ptr<MemoryBuffer> File;
157   DenseMap<StringRef, StringRef> RemappingTable;
158 
159 public:
160   /// Build a SymbolRemapper from a file containing a list of old/new symbols.
161   static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
162     auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
163     if (!BufOrError)
164       exitWithErrorCode(BufOrError.getError(), InputFile);
165 
166     auto Remapper = std::make_unique<SymbolRemapper>();
167     Remapper->File = std::move(BufOrError.get());
168 
169     for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
170          !LineIt.is_at_eof(); ++LineIt) {
171       std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
172       if (Parts.first.empty() || Parts.second.empty() ||
173           Parts.second.count(' ')) {
174         exitWithError("unexpected line in remapping file",
175                       (InputFile + ":" + Twine(LineIt.line_number())).str(),
176                       "expected 'old_symbol new_symbol'");
177       }
178       Remapper->RemappingTable.insert(Parts);
179     }
180     return Remapper;
181   }
182 
183   /// Attempt to map the given old symbol into a new symbol.
184   ///
185   /// \return The new symbol, or \p Name if no such symbol was found.
186   StringRef operator()(StringRef Name) {
187     StringRef New = RemappingTable.lookup(Name);
188     return New.empty() ? Name : New;
189   }
190 };
191 }
192 
193 struct WeightedFile {
194   std::string Filename;
195   uint64_t Weight;
196 };
197 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
198 
199 /// Keep track of merged data and reported errors.
200 struct WriterContext {
201   std::mutex Lock;
202   InstrProfWriter Writer;
203   std::vector<std::pair<Error, std::string>> Errors;
204   std::mutex &ErrLock;
205   SmallSet<instrprof_error, 4> &WriterErrorCodes;
206 
207   WriterContext(bool IsSparse, std::mutex &ErrLock,
208                 SmallSet<instrprof_error, 4> &WriterErrorCodes)
209       : Writer(IsSparse), ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {
210   }
211 };
212 
213 /// Computer the overlap b/w profile BaseFilename and TestFileName,
214 /// and store the program level result to Overlap.
215 static void overlapInput(const std::string &BaseFilename,
216                          const std::string &TestFilename, WriterContext *WC,
217                          OverlapStats &Overlap,
218                          const OverlapFuncFilters &FuncFilter,
219                          raw_fd_ostream &OS, bool IsCS) {
220   auto ReaderOrErr = InstrProfReader::create(TestFilename);
221   if (Error E = ReaderOrErr.takeError()) {
222     // Skip the empty profiles by returning sliently.
223     instrprof_error IPE = InstrProfError::take(std::move(E));
224     if (IPE != instrprof_error::empty_raw_profile)
225       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), TestFilename);
226     return;
227   }
228 
229   auto Reader = std::move(ReaderOrErr.get());
230   for (auto &I : *Reader) {
231     OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
232     FuncOverlap.setFuncInfo(I.Name, I.Hash);
233 
234     WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
235     FuncOverlap.dump(OS);
236   }
237 }
238 
239 /// Load an input into a writer context.
240 static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
241                       const InstrProfCorrelator *Correlator,
242                       const StringRef ProfiledBinary, WriterContext *WC) {
243   std::unique_lock<std::mutex> CtxGuard{WC->Lock};
244 
245   // Copy the filename, because llvm::ThreadPool copied the input "const
246   // WeightedFile &" by value, making a reference to the filename within it
247   // invalid outside of this packaged task.
248   std::string Filename = Input.Filename;
249 
250   using ::llvm::memprof::RawMemProfReader;
251   if (RawMemProfReader::hasFormat(Input.Filename)) {
252     auto ReaderOrErr = RawMemProfReader::create(Input.Filename, ProfiledBinary);
253     if (!ReaderOrErr) {
254       exitWithError(ReaderOrErr.takeError(), Input.Filename);
255     }
256     std::unique_ptr<RawMemProfReader> Reader = std::move(ReaderOrErr.get());
257     // Check if the profile types can be merged, e.g. clang frontend profiles
258     // should not be merged with memprof profiles.
259     if (Error E = WC->Writer.mergeProfileKind(Reader->getProfileKind())) {
260       consumeError(std::move(E));
261       WC->Errors.emplace_back(
262           make_error<StringError>(
263               "Cannot merge MemProf profile with Clang generated profile.",
264               std::error_code()),
265           Filename);
266       return;
267     }
268 
269     auto MemProfError = [&](Error E) {
270       instrprof_error IPE = InstrProfError::take(std::move(E));
271       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename);
272     };
273 
274     // Add the frame mappings into the writer context.
275     const auto &IdToFrame = Reader->getFrameMapping();
276     for (const auto &I : IdToFrame) {
277       bool Succeeded = WC->Writer.addMemProfFrame(
278           /*Id=*/I.first, /*Frame=*/I.getSecond(), MemProfError);
279       // If we weren't able to add the frame mappings then it doesn't make sense
280       // to try to add the records from this profile.
281       if (!Succeeded)
282         return;
283     }
284     const auto &FunctionProfileData = Reader->getProfileData();
285     // Add the memprof records into the writer context.
286     for (const auto &I : FunctionProfileData) {
287       WC->Writer.addMemProfRecord(/*Id=*/I.first, /*Record=*/I.second);
288     }
289     return;
290   }
291 
292   auto ReaderOrErr = InstrProfReader::create(Input.Filename, Correlator);
293   if (Error E = ReaderOrErr.takeError()) {
294     // Skip the empty profiles by returning sliently.
295     instrprof_error IPE = InstrProfError::take(std::move(E));
296     if (IPE != instrprof_error::empty_raw_profile)
297       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename);
298     return;
299   }
300 
301   auto Reader = std::move(ReaderOrErr.get());
302   if (Error E = WC->Writer.mergeProfileKind(Reader->getProfileKind())) {
303     consumeError(std::move(E));
304     WC->Errors.emplace_back(
305         make_error<StringError>(
306             "Merge IR generated profile with Clang generated profile.",
307             std::error_code()),
308         Filename);
309     return;
310   }
311 
312   for (auto &I : *Reader) {
313     if (Remapper)
314       I.Name = (*Remapper)(I.Name);
315     const StringRef FuncName = I.Name;
316     bool Reported = false;
317     WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
318       if (Reported) {
319         consumeError(std::move(E));
320         return;
321       }
322       Reported = true;
323       // Only show hint the first time an error occurs.
324       instrprof_error IPE = InstrProfError::take(std::move(E));
325       std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
326       bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
327       handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
328                              FuncName, firstTime);
329     });
330   }
331   if (Reader->hasError())
332     if (Error E = Reader->getError())
333       WC->Errors.emplace_back(std::move(E), Filename);
334 }
335 
336 /// Merge the \p Src writer context into \p Dst.
337 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
338   for (auto &ErrorPair : Src->Errors)
339     Dst->Errors.push_back(std::move(ErrorPair));
340   Src->Errors.clear();
341 
342   Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
343     instrprof_error IPE = InstrProfError::take(std::move(E));
344     std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
345     bool firstTime = Dst->WriterErrorCodes.insert(IPE).second;
346     if (firstTime)
347       warn(toString(make_error<InstrProfError>(IPE)));
348   });
349 }
350 
351 static void writeInstrProfile(StringRef OutputFilename,
352                               ProfileFormat OutputFormat,
353                               InstrProfWriter &Writer) {
354   std::error_code EC;
355   raw_fd_ostream Output(OutputFilename.data(), EC,
356                         OutputFormat == PF_Text ? sys::fs::OF_TextWithCRLF
357                                                 : sys::fs::OF_None);
358   if (EC)
359     exitWithErrorCode(EC, OutputFilename);
360 
361   if (OutputFormat == PF_Text) {
362     if (Error E = Writer.writeText(Output))
363       warn(std::move(E));
364   } else {
365     if (Output.is_displayed())
366       exitWithError("cannot write a non-text format profile to the terminal");
367     if (Error E = Writer.write(Output))
368       warn(std::move(E));
369   }
370 }
371 
372 static void mergeInstrProfile(const WeightedFileVector &Inputs,
373                               StringRef DebugInfoFilename,
374                               SymbolRemapper *Remapper,
375                               StringRef OutputFilename,
376                               ProfileFormat OutputFormat, bool OutputSparse,
377                               unsigned NumThreads, FailureMode FailMode,
378                               const StringRef ProfiledBinary) {
379   if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
380       OutputFormat != PF_Ext_Binary && OutputFormat != PF_Text)
381     exitWithError("unknown format is specified");
382 
383   std::unique_ptr<InstrProfCorrelator> Correlator;
384   if (!DebugInfoFilename.empty()) {
385     if (auto Err =
386             InstrProfCorrelator::get(DebugInfoFilename).moveInto(Correlator))
387       exitWithError(std::move(Err), DebugInfoFilename);
388     if (auto Err = Correlator->correlateProfileData())
389       exitWithError(std::move(Err), DebugInfoFilename);
390   }
391 
392   std::mutex ErrorLock;
393   SmallSet<instrprof_error, 4> WriterErrorCodes;
394 
395   // If NumThreads is not specified, auto-detect a good default.
396   if (NumThreads == 0)
397     NumThreads = std::min(hardware_concurrency().compute_thread_count(),
398                           unsigned((Inputs.size() + 1) / 2));
399   // FIXME: There's a bug here, where setting NumThreads = Inputs.size() fails
400   // the merge_empty_profile.test because the InstrProfWriter.ProfileKind isn't
401   // merged, thus the emitted file ends up with a PF_Unknown kind.
402 
403   // Initialize the writer contexts.
404   SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
405   for (unsigned I = 0; I < NumThreads; ++I)
406     Contexts.emplace_back(std::make_unique<WriterContext>(
407         OutputSparse, ErrorLock, WriterErrorCodes));
408 
409   if (NumThreads == 1) {
410     for (const auto &Input : Inputs)
411       loadInput(Input, Remapper, Correlator.get(), ProfiledBinary,
412                 Contexts[0].get());
413   } else {
414     ThreadPool Pool(hardware_concurrency(NumThreads));
415 
416     // Load the inputs in parallel (N/NumThreads serial steps).
417     unsigned Ctx = 0;
418     for (const auto &Input : Inputs) {
419       Pool.async(loadInput, Input, Remapper, Correlator.get(), ProfiledBinary,
420                  Contexts[Ctx].get());
421       Ctx = (Ctx + 1) % NumThreads;
422     }
423     Pool.wait();
424 
425     // Merge the writer contexts together (~ lg(NumThreads) serial steps).
426     unsigned Mid = Contexts.size() / 2;
427     unsigned End = Contexts.size();
428     assert(Mid > 0 && "Expected more than one context");
429     do {
430       for (unsigned I = 0; I < Mid; ++I)
431         Pool.async(mergeWriterContexts, Contexts[I].get(),
432                    Contexts[I + Mid].get());
433       Pool.wait();
434       if (End & 1) {
435         Pool.async(mergeWriterContexts, Contexts[0].get(),
436                    Contexts[End - 1].get());
437         Pool.wait();
438       }
439       End = Mid;
440       Mid /= 2;
441     } while (Mid > 0);
442   }
443 
444   // Handle deferred errors encountered during merging. If the number of errors
445   // is equal to the number of inputs the merge failed.
446   unsigned NumErrors = 0;
447   for (std::unique_ptr<WriterContext> &WC : Contexts) {
448     for (auto &ErrorPair : WC->Errors) {
449       ++NumErrors;
450       warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
451     }
452   }
453   if (NumErrors == Inputs.size() ||
454       (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
455     exitWithError("no profile can be merged");
456 
457   writeInstrProfile(OutputFilename, OutputFormat, Contexts[0]->Writer);
458 }
459 
460 /// The profile entry for a function in instrumentation profile.
461 struct InstrProfileEntry {
462   uint64_t MaxCount = 0;
463   float ZeroCounterRatio = 0.0;
464   InstrProfRecord *ProfRecord;
465   InstrProfileEntry(InstrProfRecord *Record);
466   InstrProfileEntry() = default;
467 };
468 
469 InstrProfileEntry::InstrProfileEntry(InstrProfRecord *Record) {
470   ProfRecord = Record;
471   uint64_t CntNum = Record->Counts.size();
472   uint64_t ZeroCntNum = 0;
473   for (size_t I = 0; I < CntNum; ++I) {
474     MaxCount = std::max(MaxCount, Record->Counts[I]);
475     ZeroCntNum += !Record->Counts[I];
476   }
477   ZeroCounterRatio = (float)ZeroCntNum / CntNum;
478 }
479 
480 /// Either set all the counters in the instr profile entry \p IFE to -1
481 /// in order to drop the profile or scale up the counters in \p IFP to
482 /// be above hot threshold. We use the ratio of zero counters in the
483 /// profile of a function to decide the profile is helpful or harmful
484 /// for performance, and to choose whether to scale up or drop it.
485 static void updateInstrProfileEntry(InstrProfileEntry &IFE,
486                                     uint64_t HotInstrThreshold,
487                                     float ZeroCounterThreshold) {
488   InstrProfRecord *ProfRecord = IFE.ProfRecord;
489   if (!IFE.MaxCount || IFE.ZeroCounterRatio > ZeroCounterThreshold) {
490     // If all or most of the counters of the function are zero, the
491     // profile is unaccountable and shuld be dropped. Reset all the
492     // counters to be -1 and PGO profile-use will drop the profile.
493     // All counters being -1 also implies that the function is hot so
494     // PGO profile-use will also set the entry count metadata to be
495     // above hot threshold.
496     for (size_t I = 0; I < ProfRecord->Counts.size(); ++I)
497       ProfRecord->Counts[I] = -1;
498     return;
499   }
500 
501   // Scale up the MaxCount to be multiple times above hot threshold.
502   const unsigned MultiplyFactor = 3;
503   uint64_t Numerator = HotInstrThreshold * MultiplyFactor;
504   uint64_t Denominator = IFE.MaxCount;
505   ProfRecord->scale(Numerator, Denominator, [&](instrprof_error E) {
506     warn(toString(make_error<InstrProfError>(E)));
507   });
508 }
509 
510 const uint64_t ColdPercentileIdx = 15;
511 const uint64_t HotPercentileIdx = 11;
512 
513 using sampleprof::FSDiscriminatorPass;
514 
515 // Internal options to set FSDiscriminatorPass. Used in merge and show
516 // commands.
517 static cl::opt<FSDiscriminatorPass> FSDiscriminatorPassOption(
518     "fs-discriminator-pass", cl::init(PassLast), cl::Hidden,
519     cl::desc("Zero out the discriminator bits for the FS discrimiantor "
520              "pass beyond this value. The enum values are defined in "
521              "Support/Discriminator.h"),
522     cl::values(clEnumVal(Base, "Use base discriminators only"),
523                clEnumVal(Pass1, "Use base and pass 1 discriminators"),
524                clEnumVal(Pass2, "Use base and pass 1-2 discriminators"),
525                clEnumVal(Pass3, "Use base and pass 1-3 discriminators"),
526                clEnumVal(PassLast, "Use all discriminator bits (default)")));
527 
528 static unsigned getDiscriminatorMask() {
529   return getN1Bits(getFSPassBitEnd(FSDiscriminatorPassOption.getValue()));
530 }
531 
532 /// Adjust the instr profile in \p WC based on the sample profile in
533 /// \p Reader.
534 static void
535 adjustInstrProfile(std::unique_ptr<WriterContext> &WC,
536                    std::unique_ptr<sampleprof::SampleProfileReader> &Reader,
537                    unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
538                    unsigned InstrProfColdThreshold) {
539   // Function to its entry in instr profile.
540   StringMap<InstrProfileEntry> InstrProfileMap;
541   InstrProfSummaryBuilder IPBuilder(ProfileSummaryBuilder::DefaultCutoffs);
542   for (auto &PD : WC->Writer.getProfileData()) {
543     // Populate IPBuilder.
544     for (const auto &PDV : PD.getValue()) {
545       InstrProfRecord Record = PDV.second;
546       IPBuilder.addRecord(Record);
547     }
548 
549     // If a function has multiple entries in instr profile, skip it.
550     if (PD.getValue().size() != 1)
551       continue;
552 
553     // Initialize InstrProfileMap.
554     InstrProfRecord *R = &PD.getValue().begin()->second;
555     InstrProfileMap[PD.getKey()] = InstrProfileEntry(R);
556   }
557 
558   ProfileSummary InstrPS = *IPBuilder.getSummary();
559   ProfileSummary SamplePS = Reader->getSummary();
560 
561   // Compute cold thresholds for instr profile and sample profile.
562   uint64_t ColdSampleThreshold =
563       ProfileSummaryBuilder::getEntryForPercentile(
564           SamplePS.getDetailedSummary(),
565           ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
566           .MinCount;
567   uint64_t HotInstrThreshold =
568       ProfileSummaryBuilder::getEntryForPercentile(
569           InstrPS.getDetailedSummary(),
570           ProfileSummaryBuilder::DefaultCutoffs[HotPercentileIdx])
571           .MinCount;
572   uint64_t ColdInstrThreshold =
573       InstrProfColdThreshold
574           ? InstrProfColdThreshold
575           : ProfileSummaryBuilder::getEntryForPercentile(
576                 InstrPS.getDetailedSummary(),
577                 ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
578                 .MinCount;
579 
580   // Find hot/warm functions in sample profile which is cold in instr profile
581   // and adjust the profiles of those functions in the instr profile.
582   for (const auto &PD : Reader->getProfiles()) {
583     auto &FContext = PD.first;
584     const sampleprof::FunctionSamples &FS = PD.second;
585     auto It = InstrProfileMap.find(FContext.toString());
586     if (FS.getHeadSamples() > ColdSampleThreshold &&
587         It != InstrProfileMap.end() &&
588         It->second.MaxCount <= ColdInstrThreshold &&
589         FS.getBodySamples().size() >= SupplMinSizeThreshold) {
590       updateInstrProfileEntry(It->second, HotInstrThreshold,
591                               ZeroCounterThreshold);
592     }
593   }
594 }
595 
596 /// The main function to supplement instr profile with sample profile.
597 /// \Inputs contains the instr profile. \p SampleFilename specifies the
598 /// sample profile. \p OutputFilename specifies the output profile name.
599 /// \p OutputFormat specifies the output profile format. \p OutputSparse
600 /// specifies whether to generate sparse profile. \p SupplMinSizeThreshold
601 /// specifies the minimal size for the functions whose profile will be
602 /// adjusted. \p ZeroCounterThreshold is the threshold to check whether
603 /// a function contains too many zero counters and whether its profile
604 /// should be dropped. \p InstrProfColdThreshold is the user specified
605 /// cold threshold which will override the cold threshold got from the
606 /// instr profile summary.
607 static void supplementInstrProfile(
608     const WeightedFileVector &Inputs, StringRef SampleFilename,
609     StringRef OutputFilename, ProfileFormat OutputFormat, bool OutputSparse,
610     unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
611     unsigned InstrProfColdThreshold) {
612   if (OutputFilename.compare("-") == 0)
613     exitWithError("cannot write indexed profdata format to stdout");
614   if (Inputs.size() != 1)
615     exitWithError("expect one input to be an instr profile");
616   if (Inputs[0].Weight != 1)
617     exitWithError("expect instr profile doesn't have weight");
618 
619   StringRef InstrFilename = Inputs[0].Filename;
620 
621   // Read sample profile.
622   LLVMContext Context;
623   auto ReaderOrErr = sampleprof::SampleProfileReader::create(
624       SampleFilename.str(), Context, FSDiscriminatorPassOption);
625   if (std::error_code EC = ReaderOrErr.getError())
626     exitWithErrorCode(EC, SampleFilename);
627   auto Reader = std::move(ReaderOrErr.get());
628   if (std::error_code EC = Reader->read())
629     exitWithErrorCode(EC, SampleFilename);
630 
631   // Read instr profile.
632   std::mutex ErrorLock;
633   SmallSet<instrprof_error, 4> WriterErrorCodes;
634   auto WC = std::make_unique<WriterContext>(OutputSparse, ErrorLock,
635                                             WriterErrorCodes);
636   loadInput(Inputs[0], nullptr, nullptr, /*ProfiledBinary=*/"", WC.get());
637   if (WC->Errors.size() > 0)
638     exitWithError(std::move(WC->Errors[0].first), InstrFilename);
639 
640   adjustInstrProfile(WC, Reader, SupplMinSizeThreshold, ZeroCounterThreshold,
641                      InstrProfColdThreshold);
642   writeInstrProfile(OutputFilename, OutputFormat, WC->Writer);
643 }
644 
645 /// Make a copy of the given function samples with all symbol names remapped
646 /// by the provided symbol remapper.
647 static sampleprof::FunctionSamples
648 remapSamples(const sampleprof::FunctionSamples &Samples,
649              SymbolRemapper &Remapper, sampleprof_error &Error) {
650   sampleprof::FunctionSamples Result;
651   Result.setName(Remapper(Samples.getName()));
652   Result.addTotalSamples(Samples.getTotalSamples());
653   Result.addHeadSamples(Samples.getHeadSamples());
654   for (const auto &BodySample : Samples.getBodySamples()) {
655     uint32_t MaskedDiscriminator =
656         BodySample.first.Discriminator & getDiscriminatorMask();
657     Result.addBodySamples(BodySample.first.LineOffset, MaskedDiscriminator,
658                           BodySample.second.getSamples());
659     for (const auto &Target : BodySample.second.getCallTargets()) {
660       Result.addCalledTargetSamples(BodySample.first.LineOffset,
661                                     MaskedDiscriminator,
662                                     Remapper(Target.first()), Target.second);
663     }
664   }
665   for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
666     sampleprof::FunctionSamplesMap &Target =
667         Result.functionSamplesAt(CallsiteSamples.first);
668     for (const auto &Callsite : CallsiteSamples.second) {
669       sampleprof::FunctionSamples Remapped =
670           remapSamples(Callsite.second, Remapper, Error);
671       MergeResult(Error,
672                   Target[std::string(Remapped.getName())].merge(Remapped));
673     }
674   }
675   return Result;
676 }
677 
678 static sampleprof::SampleProfileFormat FormatMap[] = {
679     sampleprof::SPF_None,
680     sampleprof::SPF_Text,
681     sampleprof::SPF_Compact_Binary,
682     sampleprof::SPF_Ext_Binary,
683     sampleprof::SPF_GCC,
684     sampleprof::SPF_Binary};
685 
686 static std::unique_ptr<MemoryBuffer>
687 getInputFileBuf(const StringRef &InputFile) {
688   if (InputFile == "")
689     return {};
690 
691   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
692   if (!BufOrError)
693     exitWithErrorCode(BufOrError.getError(), InputFile);
694 
695   return std::move(*BufOrError);
696 }
697 
698 static void populateProfileSymbolList(MemoryBuffer *Buffer,
699                                       sampleprof::ProfileSymbolList &PSL) {
700   if (!Buffer)
701     return;
702 
703   SmallVector<StringRef, 32> SymbolVec;
704   StringRef Data = Buffer->getBuffer();
705   Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
706 
707   for (StringRef SymbolStr : SymbolVec)
708     PSL.add(SymbolStr.trim());
709 }
710 
711 static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer,
712                                   ProfileFormat OutputFormat,
713                                   MemoryBuffer *Buffer,
714                                   sampleprof::ProfileSymbolList &WriterList,
715                                   bool CompressAllSections, bool UseMD5,
716                                   bool GenPartialProfile) {
717   populateProfileSymbolList(Buffer, WriterList);
718   if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
719     warn("Profile Symbol list is not empty but the output format is not "
720          "ExtBinary format. The list will be lost in the output. ");
721 
722   Writer.setProfileSymbolList(&WriterList);
723 
724   if (CompressAllSections) {
725     if (OutputFormat != PF_Ext_Binary)
726       warn("-compress-all-section is ignored. Specify -extbinary to enable it");
727     else
728       Writer.setToCompressAllSections();
729   }
730   if (UseMD5) {
731     if (OutputFormat != PF_Ext_Binary)
732       warn("-use-md5 is ignored. Specify -extbinary to enable it");
733     else
734       Writer.setUseMD5();
735   }
736   if (GenPartialProfile) {
737     if (OutputFormat != PF_Ext_Binary)
738       warn("-gen-partial-profile is ignored. Specify -extbinary to enable it");
739     else
740       Writer.setPartialProfile();
741   }
742 }
743 
744 static void
745 mergeSampleProfile(const WeightedFileVector &Inputs, SymbolRemapper *Remapper,
746                    StringRef OutputFilename, ProfileFormat OutputFormat,
747                    StringRef ProfileSymbolListFile, bool CompressAllSections,
748                    bool UseMD5, bool GenPartialProfile, bool GenCSNestedProfile,
749                    bool SampleMergeColdContext, bool SampleTrimColdContext,
750                    bool SampleColdContextFrameDepth, FailureMode FailMode) {
751   using namespace sampleprof;
752   SampleProfileMap ProfileMap;
753   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
754   LLVMContext Context;
755   sampleprof::ProfileSymbolList WriterList;
756   Optional<bool> ProfileIsProbeBased;
757   Optional<bool> ProfileIsCSFlat;
758   for (const auto &Input : Inputs) {
759     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context,
760                                                    FSDiscriminatorPassOption);
761     if (std::error_code EC = ReaderOrErr.getError()) {
762       warnOrExitGivenError(FailMode, EC, Input.Filename);
763       continue;
764     }
765 
766     // We need to keep the readers around until after all the files are
767     // read so that we do not lose the function names stored in each
768     // reader's memory. The function names are needed to write out the
769     // merged profile map.
770     Readers.push_back(std::move(ReaderOrErr.get()));
771     const auto Reader = Readers.back().get();
772     if (std::error_code EC = Reader->read()) {
773       warnOrExitGivenError(FailMode, EC, Input.Filename);
774       Readers.pop_back();
775       continue;
776     }
777 
778     SampleProfileMap &Profiles = Reader->getProfiles();
779     if (ProfileIsProbeBased.hasValue() &&
780         ProfileIsProbeBased != FunctionSamples::ProfileIsProbeBased)
781       exitWithError(
782           "cannot merge probe-based profile with non-probe-based profile");
783     ProfileIsProbeBased = FunctionSamples::ProfileIsProbeBased;
784     if (ProfileIsCSFlat.hasValue() &&
785         ProfileIsCSFlat != FunctionSamples::ProfileIsCSFlat)
786       exitWithError("cannot merge CS profile with non-CS profile");
787     ProfileIsCSFlat = FunctionSamples::ProfileIsCSFlat;
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 (ProfileIsCSFlat && (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 (ProfileIsCSFlat && GenCSNestedProfile) {
826     CSProfileConverter CSConverter(ProfileMap);
827     CSConverter.convertProfiles();
828     ProfileIsCSFlat = FunctionSamples::ProfileIsCSFlat = 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), cl::ZeroOrMore,
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 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->profileIsCSFlat() != TestReader->profileIsCSFlat())
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 (std::any_of(Func.Counts.begin(), Func.Counts.end(),
2204                       [](uint64_t C) { return C; }))
2205         OS << Func.Name << "\n";
2206       continue;
2207     }
2208 
2209     uint64_t FuncMax = 0;
2210     uint64_t FuncSum = 0;
2211     for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
2212       if (Func.Counts[I] == (uint64_t)-1)
2213         continue;
2214       FuncMax = std::max(FuncMax, Func.Counts[I]);
2215       FuncSum += Func.Counts[I];
2216     }
2217 
2218     if (FuncMax < ValueCutoff) {
2219       ++BelowCutoffFunctions;
2220       if (OnlyListBelow) {
2221         OS << "  " << Func.Name << ": (Max = " << FuncMax
2222            << " Sum = " << FuncSum << ")\n";
2223       }
2224       continue;
2225     } else if (OnlyListBelow)
2226       continue;
2227 
2228     if (TopN) {
2229       if (HottestFuncs.size() == TopN) {
2230         if (HottestFuncs.top().second < FuncMax) {
2231           HottestFuncs.pop();
2232           HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
2233         }
2234       } else
2235         HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
2236     }
2237 
2238     if (Show) {
2239       if (!ShownFunctions)
2240         OS << "Counters:\n";
2241 
2242       ++ShownFunctions;
2243 
2244       OS << "  " << Func.Name << ":\n"
2245          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
2246          << "    Counters: " << Func.Counts.size() << "\n";
2247       if (!IsIRInstr)
2248         OS << "    Function count: " << Func.Counts[0] << "\n";
2249 
2250       if (ShowIndirectCallTargets)
2251         OS << "    Indirect Call Site Count: "
2252            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
2253 
2254       uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
2255       if (ShowMemOPSizes && NumMemOPCalls > 0)
2256         OS << "    Number of Memory Intrinsics Calls: " << NumMemOPCalls
2257            << "\n";
2258 
2259       if (ShowCounts) {
2260         OS << "    Block counts: [";
2261         size_t Start = (IsIRInstr ? 0 : 1);
2262         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
2263           OS << (I == Start ? "" : ", ") << Func.Counts[I];
2264         }
2265         OS << "]\n";
2266       }
2267 
2268       if (ShowIndirectCallTargets) {
2269         OS << "    Indirect Target Results:\n";
2270         traverseAllValueSites(Func, IPVK_IndirectCallTarget,
2271                               VPStats[IPVK_IndirectCallTarget], OS,
2272                               &(Reader->getSymtab()));
2273       }
2274 
2275       if (ShowMemOPSizes && NumMemOPCalls > 0) {
2276         OS << "    Memory Intrinsic Size Results:\n";
2277         traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
2278                               nullptr);
2279       }
2280     }
2281   }
2282   if (Reader->hasError())
2283     exitWithError(Reader->getError(), Filename);
2284 
2285   if (TextFormat || ShowCovered)
2286     return 0;
2287   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
2288   bool IsIR = Reader->isIRLevelProfile();
2289   OS << "Instrumentation level: " << (IsIR ? "IR" : "Front-end");
2290   if (IsIR)
2291     OS << "  entry_first = " << Reader->instrEntryBBEnabled();
2292   OS << "\n";
2293   if (ShowAllFunctions || !ShowFunction.empty())
2294     OS << "Functions shown: " << ShownFunctions << "\n";
2295   OS << "Total functions: " << PS->getNumFunctions() << "\n";
2296   if (ValueCutoff > 0) {
2297     OS << "Number of functions with maximum count (< " << ValueCutoff
2298        << "): " << BelowCutoffFunctions << "\n";
2299     OS << "Number of functions with maximum count (>= " << ValueCutoff
2300        << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
2301   }
2302   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
2303   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
2304 
2305   if (TopN) {
2306     std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
2307     while (!HottestFuncs.empty()) {
2308       SortedHottestFuncs.emplace_back(HottestFuncs.top());
2309       HottestFuncs.pop();
2310     }
2311     OS << "Top " << TopN
2312        << " functions with the largest internal block counts: \n";
2313     for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
2314       OS << "  " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
2315   }
2316 
2317   if (ShownFunctions && ShowIndirectCallTargets) {
2318     OS << "Statistics for indirect call sites profile:\n";
2319     showValueSitesStats(OS, IPVK_IndirectCallTarget,
2320                         VPStats[IPVK_IndirectCallTarget]);
2321   }
2322 
2323   if (ShownFunctions && ShowMemOPSizes) {
2324     OS << "Statistics for memory intrinsic calls sizes profile:\n";
2325     showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
2326   }
2327 
2328   if (ShowDetailedSummary) {
2329     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
2330     OS << "Total count: " << PS->getTotalCount() << "\n";
2331     PS->printDetailedSummary(OS);
2332   }
2333 
2334   if (ShowBinaryIds)
2335     if (Error E = Reader->printBinaryIds(OS))
2336       exitWithError(std::move(E), Filename);
2337 
2338   return 0;
2339 }
2340 
2341 static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
2342                             raw_fd_ostream &OS) {
2343   if (!Reader->dumpSectionInfo(OS)) {
2344     WithColor::warning() << "-show-sec-info-only is only supported for "
2345                          << "sample profile in extbinary format and is "
2346                          << "ignored for other formats.\n";
2347     return;
2348   }
2349 }
2350 
2351 namespace {
2352 struct HotFuncInfo {
2353   std::string FuncName;
2354   uint64_t TotalCount;
2355   double TotalCountPercent;
2356   uint64_t MaxCount;
2357   uint64_t EntryCount;
2358 
2359   HotFuncInfo()
2360       : TotalCount(0), TotalCountPercent(0.0f), MaxCount(0), EntryCount(0) {}
2361 
2362   HotFuncInfo(StringRef FN, uint64_t TS, double TSP, uint64_t MS, uint64_t ES)
2363       : FuncName(FN.begin(), FN.end()), TotalCount(TS), TotalCountPercent(TSP),
2364         MaxCount(MS), EntryCount(ES) {}
2365 };
2366 } // namespace
2367 
2368 // Print out detailed information about hot functions in PrintValues vector.
2369 // Users specify titles and offset of every columns through ColumnTitle and
2370 // ColumnOffset. The size of ColumnTitle and ColumnOffset need to be the same
2371 // and at least 4. Besides, users can optionally give a HotFuncMetric string to
2372 // print out or let it be an empty string.
2373 static void dumpHotFunctionList(const std::vector<std::string> &ColumnTitle,
2374                                 const std::vector<int> &ColumnOffset,
2375                                 const std::vector<HotFuncInfo> &PrintValues,
2376                                 uint64_t HotFuncCount, uint64_t TotalFuncCount,
2377                                 uint64_t HotProfCount, uint64_t TotalProfCount,
2378                                 const std::string &HotFuncMetric,
2379                                 uint32_t TopNFunctions, raw_fd_ostream &OS) {
2380   assert(ColumnOffset.size() == ColumnTitle.size() &&
2381          "ColumnOffset and ColumnTitle should have the same size");
2382   assert(ColumnTitle.size() >= 4 &&
2383          "ColumnTitle should have at least 4 elements");
2384   assert(TotalFuncCount > 0 &&
2385          "There should be at least one function in the profile");
2386   double TotalProfPercent = 0;
2387   if (TotalProfCount > 0)
2388     TotalProfPercent = static_cast<double>(HotProfCount) / TotalProfCount * 100;
2389 
2390   formatted_raw_ostream FOS(OS);
2391   FOS << HotFuncCount << " out of " << TotalFuncCount
2392       << " functions with profile ("
2393       << format("%.2f%%",
2394                 (static_cast<double>(HotFuncCount) / TotalFuncCount * 100))
2395       << ") are considered hot functions";
2396   if (!HotFuncMetric.empty())
2397     FOS << " (" << HotFuncMetric << ")";
2398   FOS << ".\n";
2399   FOS << HotProfCount << " out of " << TotalProfCount << " profile counts ("
2400       << format("%.2f%%", TotalProfPercent) << ") are from hot functions.\n";
2401 
2402   for (size_t I = 0; I < ColumnTitle.size(); ++I) {
2403     FOS.PadToColumn(ColumnOffset[I]);
2404     FOS << ColumnTitle[I];
2405   }
2406   FOS << "\n";
2407 
2408   uint32_t Count = 0;
2409   for (const auto &R : PrintValues) {
2410     if (TopNFunctions && (Count++ == TopNFunctions))
2411       break;
2412     FOS.PadToColumn(ColumnOffset[0]);
2413     FOS << R.TotalCount << " (" << format("%.2f%%", R.TotalCountPercent) << ")";
2414     FOS.PadToColumn(ColumnOffset[1]);
2415     FOS << R.MaxCount;
2416     FOS.PadToColumn(ColumnOffset[2]);
2417     FOS << R.EntryCount;
2418     FOS.PadToColumn(ColumnOffset[3]);
2419     FOS << R.FuncName << "\n";
2420   }
2421 }
2422 
2423 static int showHotFunctionList(const sampleprof::SampleProfileMap &Profiles,
2424                                ProfileSummary &PS, uint32_t TopN,
2425                                raw_fd_ostream &OS) {
2426   using namespace sampleprof;
2427 
2428   const uint32_t HotFuncCutoff = 990000;
2429   auto &SummaryVector = PS.getDetailedSummary();
2430   uint64_t MinCountThreshold = 0;
2431   for (const ProfileSummaryEntry &SummaryEntry : SummaryVector) {
2432     if (SummaryEntry.Cutoff == HotFuncCutoff) {
2433       MinCountThreshold = SummaryEntry.MinCount;
2434       break;
2435     }
2436   }
2437 
2438   // Traverse all functions in the profile and keep only hot functions.
2439   // The following loop also calculates the sum of total samples of all
2440   // functions.
2441   std::multimap<uint64_t, std::pair<const FunctionSamples *, const uint64_t>,
2442                 std::greater<uint64_t>>
2443       HotFunc;
2444   uint64_t ProfileTotalSample = 0;
2445   uint64_t HotFuncSample = 0;
2446   uint64_t HotFuncCount = 0;
2447 
2448   for (const auto &I : Profiles) {
2449     FuncSampleStats FuncStats;
2450     const FunctionSamples &FuncProf = I.second;
2451     ProfileTotalSample += FuncProf.getTotalSamples();
2452     getFuncSampleStats(FuncProf, FuncStats, MinCountThreshold);
2453 
2454     if (isFunctionHot(FuncStats, MinCountThreshold)) {
2455       HotFunc.emplace(FuncProf.getTotalSamples(),
2456                       std::make_pair(&(I.second), FuncStats.MaxSample));
2457       HotFuncSample += FuncProf.getTotalSamples();
2458       ++HotFuncCount;
2459     }
2460   }
2461 
2462   std::vector<std::string> ColumnTitle{"Total sample (%)", "Max sample",
2463                                        "Entry sample", "Function name"};
2464   std::vector<int> ColumnOffset{0, 24, 42, 58};
2465   std::string Metric =
2466       std::string("max sample >= ") + std::to_string(MinCountThreshold);
2467   std::vector<HotFuncInfo> PrintValues;
2468   for (const auto &FuncPair : HotFunc) {
2469     const FunctionSamples &Func = *FuncPair.second.first;
2470     double TotalSamplePercent =
2471         (ProfileTotalSample > 0)
2472             ? (Func.getTotalSamples() * 100.0) / ProfileTotalSample
2473             : 0;
2474     PrintValues.emplace_back(HotFuncInfo(
2475         Func.getContext().toString(), Func.getTotalSamples(),
2476         TotalSamplePercent, FuncPair.second.second, Func.getEntrySamples()));
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 =
2536       llvm::memprof::RawMemProfReader::create(Filename, ProfiledBinary);
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