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