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