xref: /freebsd-src/contrib/llvm-project/llvm/tools/llvm-profdata/llvm-profdata.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
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,
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> ProfileIsCS;
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 (ProfileIsCS.hasValue() && ProfileIsCS != FunctionSamples::ProfileIsCS)
727       exitWithError("cannot merge CS profile with non-CS profile");
728     ProfileIsCS = FunctionSamples::ProfileIsCS;
729     for (SampleProfileMap::iterator I = Profiles.begin(), E = Profiles.end();
730          I != E; ++I) {
731       sampleprof_error Result = sampleprof_error::success;
732       FunctionSamples Remapped =
733           Remapper ? remapSamples(I->second, *Remapper, Result)
734                    : FunctionSamples();
735       FunctionSamples &Samples = Remapper ? Remapped : I->second;
736       SampleContext FContext = Samples.getContext();
737       MergeResult(Result, ProfileMap[FContext].merge(Samples, Input.Weight));
738       if (Result != sampleprof_error::success) {
739         std::error_code EC = make_error_code(Result);
740         handleMergeWriterError(errorCodeToError(EC), Input.Filename,
741                                FContext.toString());
742       }
743     }
744 
745     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
746         Reader->getProfileSymbolList();
747     if (ReaderList)
748       WriterList.merge(*ReaderList);
749   }
750 
751   if (ProfileIsCS && (SampleMergeColdContext || SampleTrimColdContext)) {
752     // Use threshold calculated from profile summary unless specified.
753     SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
754     auto Summary = Builder.computeSummaryForProfiles(ProfileMap);
755     uint64_t SampleProfColdThreshold =
756         ProfileSummaryBuilder::getColdCountThreshold(
757             (Summary->getDetailedSummary()));
758 
759     // Trim and merge cold context profile using cold threshold above;
760     SampleContextTrimmer(ProfileMap)
761         .trimAndMergeColdContextProfiles(
762             SampleProfColdThreshold, SampleTrimColdContext,
763             SampleMergeColdContext, SampleColdContextFrameDepth, false);
764   }
765 
766   auto WriterOrErr =
767       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
768   if (std::error_code EC = WriterOrErr.getError())
769     exitWithErrorCode(EC, OutputFilename);
770 
771   auto Writer = std::move(WriterOrErr.get());
772   // WriterList will have StringRef refering to string in Buffer.
773   // Make sure Buffer lives as long as WriterList.
774   auto Buffer = getInputFileBuf(ProfileSymbolListFile);
775   handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList,
776                         CompressAllSections, UseMD5, GenPartialProfile);
777   if (std::error_code EC = Writer->write(ProfileMap))
778     exitWithErrorCode(std::move(EC));
779 }
780 
781 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
782   StringRef WeightStr, FileName;
783   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
784 
785   uint64_t Weight;
786   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
787     exitWithError("input weight must be a positive integer");
788 
789   return {std::string(FileName), Weight};
790 }
791 
792 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
793   StringRef Filename = WF.Filename;
794   uint64_t Weight = WF.Weight;
795 
796   // If it's STDIN just pass it on.
797   if (Filename == "-") {
798     WNI.push_back({std::string(Filename), Weight});
799     return;
800   }
801 
802   llvm::sys::fs::file_status Status;
803   llvm::sys::fs::status(Filename, Status);
804   if (!llvm::sys::fs::exists(Status))
805     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
806                       Filename);
807   // If it's a source file, collect it.
808   if (llvm::sys::fs::is_regular_file(Status)) {
809     WNI.push_back({std::string(Filename), Weight});
810     return;
811   }
812 
813   if (llvm::sys::fs::is_directory(Status)) {
814     std::error_code EC;
815     for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
816          F != E && !EC; F.increment(EC)) {
817       if (llvm::sys::fs::is_regular_file(F->path())) {
818         addWeightedInput(WNI, {F->path(), Weight});
819       }
820     }
821     if (EC)
822       exitWithErrorCode(EC, Filename);
823   }
824 }
825 
826 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
827                                     WeightedFileVector &WFV) {
828   if (!Buffer)
829     return;
830 
831   SmallVector<StringRef, 8> Entries;
832   StringRef Data = Buffer->getBuffer();
833   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
834   for (const StringRef &FileWeightEntry : Entries) {
835     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
836     // Skip comments.
837     if (SanitizedEntry.startswith("#"))
838       continue;
839     // If there's no comma, it's an unweighted profile.
840     else if (!SanitizedEntry.contains(','))
841       addWeightedInput(WFV, {std::string(SanitizedEntry), 1});
842     else
843       addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
844   }
845 }
846 
847 static int merge_main(int argc, const char *argv[]) {
848   cl::list<std::string> InputFilenames(cl::Positional,
849                                        cl::desc("<filename...>"));
850   cl::list<std::string> WeightedInputFilenames("weighted-input",
851                                                cl::desc("<weight>,<filename>"));
852   cl::opt<std::string> InputFilenamesFile(
853       "input-files", cl::init(""),
854       cl::desc("Path to file containing newline-separated "
855                "[<weight>,]<filename> entries"));
856   cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
857                                 cl::aliasopt(InputFilenamesFile));
858   cl::opt<bool> DumpInputFileList(
859       "dump-input-file-list", cl::init(false), cl::Hidden,
860       cl::desc("Dump the list of input files and their weights, then exit"));
861   cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
862                                      cl::desc("Symbol remapping file"));
863   cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
864                            cl::aliasopt(RemappingFile));
865   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
866                                       cl::init("-"), cl::desc("Output file"));
867   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
868                             cl::aliasopt(OutputFilename));
869   cl::opt<ProfileKinds> ProfileKind(
870       cl::desc("Profile kind:"), cl::init(instr),
871       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
872                  clEnumVal(sample, "Sample profile")));
873   cl::opt<ProfileFormat> OutputFormat(
874       cl::desc("Format of output profile"), cl::init(PF_Binary),
875       cl::values(
876           clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
877           clEnumValN(PF_Compact_Binary, "compbinary",
878                      "Compact binary encoding"),
879           clEnumValN(PF_Ext_Binary, "extbinary", "Extensible binary encoding"),
880           clEnumValN(PF_Text, "text", "Text encoding"),
881           clEnumValN(PF_GCC, "gcc",
882                      "GCC encoding (only meaningful for -sample)")));
883   cl::opt<FailureMode> FailureMode(
884       "failure-mode", cl::init(failIfAnyAreInvalid), cl::desc("Failure mode:"),
885       cl::values(clEnumValN(failIfAnyAreInvalid, "any",
886                             "Fail if any profile is invalid."),
887                  clEnumValN(failIfAllAreInvalid, "all",
888                             "Fail only if all profiles are invalid.")));
889   cl::opt<bool> OutputSparse("sparse", cl::init(false),
890       cl::desc("Generate a sparse profile (only meaningful for -instr)"));
891   cl::opt<unsigned> NumThreads(
892       "num-threads", cl::init(0),
893       cl::desc("Number of merge threads to use (default: autodetect)"));
894   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
895                         cl::aliasopt(NumThreads));
896   cl::opt<std::string> ProfileSymbolListFile(
897       "prof-sym-list", cl::init(""),
898       cl::desc("Path to file containing the list of function symbols "
899                "used to populate profile symbol list"));
900   cl::opt<bool> CompressAllSections(
901       "compress-all-sections", cl::init(false), cl::Hidden,
902       cl::desc("Compress all sections when writing the profile (only "
903                "meaningful for -extbinary)"));
904   cl::opt<bool> UseMD5(
905       "use-md5", cl::init(false), cl::Hidden,
906       cl::desc("Choose to use MD5 to represent string in name table (only "
907                "meaningful for -extbinary)"));
908   cl::opt<bool> SampleMergeColdContext(
909       "sample-merge-cold-context", cl::init(false), cl::Hidden,
910       cl::desc(
911           "Merge context sample profiles whose count is below cold threshold"));
912   cl::opt<bool> SampleTrimColdContext(
913       "sample-trim-cold-context", cl::init(false), cl::Hidden,
914       cl::desc(
915           "Trim context sample profiles whose count is below cold threshold"));
916   cl::opt<uint32_t> SampleColdContextFrameDepth(
917       "sample-frame-depth-for-cold-context", cl::init(1), cl::ZeroOrMore,
918       cl::desc("Keep the last K frames while merging cold profile. 1 means the "
919                "context-less base profile"));
920   cl::opt<bool> GenPartialProfile(
921       "gen-partial-profile", cl::init(false), cl::Hidden,
922       cl::desc("Generate a partial profile (only meaningful for -extbinary)"));
923   cl::opt<std::string> SupplInstrWithSample(
924       "supplement-instr-with-sample", cl::init(""), cl::Hidden,
925       cl::desc("Supplement an instr profile with sample profile, to correct "
926                "the profile unrepresentativeness issue. The sample "
927                "profile is the input of the flag. Output will be in instr "
928                "format (The flag only works with -instr)"));
929   cl::opt<float> ZeroCounterThreshold(
930       "zero-counter-threshold", cl::init(0.7), cl::Hidden,
931       cl::desc("For the function which is cold in instr profile but hot in "
932                "sample profile, if the ratio of the number of zero counters "
933                "divided by the the total number of counters is above the "
934                "threshold, the profile of the function will be regarded as "
935                "being harmful for performance and will be dropped."));
936   cl::opt<unsigned> SupplMinSizeThreshold(
937       "suppl-min-size-threshold", cl::init(10), cl::Hidden,
938       cl::desc("If the size of a function is smaller than the threshold, "
939                "assume it can be inlined by PGO early inliner and it won't "
940                "be adjusted based on sample profile."));
941   cl::opt<unsigned> InstrProfColdThreshold(
942       "instr-prof-cold-threshold", cl::init(0), cl::Hidden,
943       cl::desc("User specified cold threshold for instr profile which will "
944                "override the cold threshold got from profile summary."));
945 
946   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
947 
948   WeightedFileVector WeightedInputs;
949   for (StringRef Filename : InputFilenames)
950     addWeightedInput(WeightedInputs, {std::string(Filename), 1});
951   for (StringRef WeightedFilename : WeightedInputFilenames)
952     addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
953 
954   // Make sure that the file buffer stays alive for the duration of the
955   // weighted input vector's lifetime.
956   auto Buffer = getInputFileBuf(InputFilenamesFile);
957   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
958 
959   if (WeightedInputs.empty())
960     exitWithError("no input files specified. See " +
961                   sys::path::filename(argv[0]) + " -help");
962 
963   if (DumpInputFileList) {
964     for (auto &WF : WeightedInputs)
965       outs() << WF.Weight << "," << WF.Filename << "\n";
966     return 0;
967   }
968 
969   std::unique_ptr<SymbolRemapper> Remapper;
970   if (!RemappingFile.empty())
971     Remapper = SymbolRemapper::create(RemappingFile);
972 
973   if (!SupplInstrWithSample.empty()) {
974     if (ProfileKind != instr)
975       exitWithError(
976           "-supplement-instr-with-sample can only work with -instr. ");
977 
978     supplementInstrProfile(WeightedInputs, SupplInstrWithSample, OutputFilename,
979                            OutputFormat, OutputSparse, SupplMinSizeThreshold,
980                            ZeroCounterThreshold, InstrProfColdThreshold);
981     return 0;
982   }
983 
984   if (ProfileKind == instr)
985     mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
986                       OutputFormat, OutputSparse, NumThreads, FailureMode);
987   else
988     mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
989                        OutputFormat, ProfileSymbolListFile, CompressAllSections,
990                        UseMD5, GenPartialProfile, SampleMergeColdContext,
991                        SampleTrimColdContext, SampleColdContextFrameDepth,
992                        FailureMode);
993 
994   return 0;
995 }
996 
997 /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
998 static void overlapInstrProfile(const std::string &BaseFilename,
999                                 const std::string &TestFilename,
1000                                 const OverlapFuncFilters &FuncFilter,
1001                                 raw_fd_ostream &OS, bool IsCS) {
1002   std::mutex ErrorLock;
1003   SmallSet<instrprof_error, 4> WriterErrorCodes;
1004   WriterContext Context(false, ErrorLock, WriterErrorCodes);
1005   WeightedFile WeightedInput{BaseFilename, 1};
1006   OverlapStats Overlap;
1007   Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS);
1008   if (E)
1009     exitWithError(std::move(E), "error in getting profile count sums");
1010   if (Overlap.Base.CountSum < 1.0f) {
1011     OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
1012     exit(0);
1013   }
1014   if (Overlap.Test.CountSum < 1.0f) {
1015     OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
1016     exit(0);
1017   }
1018   loadInput(WeightedInput, nullptr, &Context);
1019   overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
1020                IsCS);
1021   Overlap.dump(OS);
1022 }
1023 
1024 namespace {
1025 struct SampleOverlapStats {
1026   SampleContext BaseName;
1027   SampleContext TestName;
1028   // Number of overlap units
1029   uint64_t OverlapCount;
1030   // Total samples of overlap units
1031   uint64_t OverlapSample;
1032   // Number of and total samples of units that only present in base or test
1033   // profile
1034   uint64_t BaseUniqueCount;
1035   uint64_t BaseUniqueSample;
1036   uint64_t TestUniqueCount;
1037   uint64_t TestUniqueSample;
1038   // Number of units and total samples in base or test profile
1039   uint64_t BaseCount;
1040   uint64_t BaseSample;
1041   uint64_t TestCount;
1042   uint64_t TestSample;
1043   // Number of and total samples of units that present in at least one profile
1044   uint64_t UnionCount;
1045   uint64_t UnionSample;
1046   // Weighted similarity
1047   double Similarity;
1048   // For SampleOverlapStats instances representing functions, weights of the
1049   // function in base and test profiles
1050   double BaseWeight;
1051   double TestWeight;
1052 
1053   SampleOverlapStats()
1054       : OverlapCount(0), OverlapSample(0), BaseUniqueCount(0),
1055         BaseUniqueSample(0), TestUniqueCount(0), TestUniqueSample(0),
1056         BaseCount(0), BaseSample(0), TestCount(0), TestSample(0), UnionCount(0),
1057         UnionSample(0), Similarity(0.0), BaseWeight(0.0), TestWeight(0.0) {}
1058 };
1059 } // end anonymous namespace
1060 
1061 namespace {
1062 struct FuncSampleStats {
1063   uint64_t SampleSum;
1064   uint64_t MaxSample;
1065   uint64_t HotBlockCount;
1066   FuncSampleStats() : SampleSum(0), MaxSample(0), HotBlockCount(0) {}
1067   FuncSampleStats(uint64_t SampleSum, uint64_t MaxSample,
1068                   uint64_t HotBlockCount)
1069       : SampleSum(SampleSum), MaxSample(MaxSample),
1070         HotBlockCount(HotBlockCount) {}
1071 };
1072 } // end anonymous namespace
1073 
1074 namespace {
1075 enum MatchStatus { MS_Match, MS_FirstUnique, MS_SecondUnique, MS_None };
1076 
1077 // Class for updating merging steps for two sorted maps. The class should be
1078 // instantiated with a map iterator type.
1079 template <class T> class MatchStep {
1080 public:
1081   MatchStep() = delete;
1082 
1083   MatchStep(T FirstIter, T FirstEnd, T SecondIter, T SecondEnd)
1084       : FirstIter(FirstIter), FirstEnd(FirstEnd), SecondIter(SecondIter),
1085         SecondEnd(SecondEnd), Status(MS_None) {}
1086 
1087   bool areBothFinished() const {
1088     return (FirstIter == FirstEnd && SecondIter == SecondEnd);
1089   }
1090 
1091   bool isFirstFinished() const { return FirstIter == FirstEnd; }
1092 
1093   bool isSecondFinished() const { return SecondIter == SecondEnd; }
1094 
1095   /// Advance one step based on the previous match status unless the previous
1096   /// status is MS_None. Then update Status based on the comparison between two
1097   /// container iterators at the current step. If the previous status is
1098   /// MS_None, it means two iterators are at the beginning and no comparison has
1099   /// been made, so we simply update Status without advancing the iterators.
1100   void updateOneStep();
1101 
1102   T getFirstIter() const { return FirstIter; }
1103 
1104   T getSecondIter() const { return SecondIter; }
1105 
1106   MatchStatus getMatchStatus() const { return Status; }
1107 
1108 private:
1109   // Current iterator and end iterator of the first container.
1110   T FirstIter;
1111   T FirstEnd;
1112   // Current iterator and end iterator of the second container.
1113   T SecondIter;
1114   T SecondEnd;
1115   // Match status of the current step.
1116   MatchStatus Status;
1117 };
1118 } // end anonymous namespace
1119 
1120 template <class T> void MatchStep<T>::updateOneStep() {
1121   switch (Status) {
1122   case MS_Match:
1123     ++FirstIter;
1124     ++SecondIter;
1125     break;
1126   case MS_FirstUnique:
1127     ++FirstIter;
1128     break;
1129   case MS_SecondUnique:
1130     ++SecondIter;
1131     break;
1132   case MS_None:
1133     break;
1134   }
1135 
1136   // Update Status according to iterators at the current step.
1137   if (areBothFinished())
1138     return;
1139   if (FirstIter != FirstEnd &&
1140       (SecondIter == SecondEnd || FirstIter->first < SecondIter->first))
1141     Status = MS_FirstUnique;
1142   else if (SecondIter != SecondEnd &&
1143            (FirstIter == FirstEnd || SecondIter->first < FirstIter->first))
1144     Status = MS_SecondUnique;
1145   else
1146     Status = MS_Match;
1147 }
1148 
1149 // Return the sum of line/block samples, the max line/block sample, and the
1150 // number of line/block samples above the given threshold in a function
1151 // including its inlinees.
1152 static void getFuncSampleStats(const sampleprof::FunctionSamples &Func,
1153                                FuncSampleStats &FuncStats,
1154                                uint64_t HotThreshold) {
1155   for (const auto &L : Func.getBodySamples()) {
1156     uint64_t Sample = L.second.getSamples();
1157     FuncStats.SampleSum += Sample;
1158     FuncStats.MaxSample = std::max(FuncStats.MaxSample, Sample);
1159     if (Sample >= HotThreshold)
1160       ++FuncStats.HotBlockCount;
1161   }
1162 
1163   for (const auto &C : Func.getCallsiteSamples()) {
1164     for (const auto &F : C.second)
1165       getFuncSampleStats(F.second, FuncStats, HotThreshold);
1166   }
1167 }
1168 
1169 /// Predicate that determines if a function is hot with a given threshold. We
1170 /// keep it separate from its callsites for possible extension in the future.
1171 static bool isFunctionHot(const FuncSampleStats &FuncStats,
1172                           uint64_t HotThreshold) {
1173   // We intentionally compare the maximum sample count in a function with the
1174   // HotThreshold to get an approximate determination on hot functions.
1175   return (FuncStats.MaxSample >= HotThreshold);
1176 }
1177 
1178 namespace {
1179 class SampleOverlapAggregator {
1180 public:
1181   SampleOverlapAggregator(const std::string &BaseFilename,
1182                           const std::string &TestFilename,
1183                           double LowSimilarityThreshold, double Epsilon,
1184                           const OverlapFuncFilters &FuncFilter)
1185       : BaseFilename(BaseFilename), TestFilename(TestFilename),
1186         LowSimilarityThreshold(LowSimilarityThreshold), Epsilon(Epsilon),
1187         FuncFilter(FuncFilter) {}
1188 
1189   /// Detect 0-sample input profile and report to output stream. This interface
1190   /// should be called after loadProfiles().
1191   bool detectZeroSampleProfile(raw_fd_ostream &OS) const;
1192 
1193   /// Write out function-level similarity statistics for functions specified by
1194   /// options --function, --value-cutoff, and --similarity-cutoff.
1195   void dumpFuncSimilarity(raw_fd_ostream &OS) const;
1196 
1197   /// Write out program-level similarity and overlap statistics.
1198   void dumpProgramSummary(raw_fd_ostream &OS) const;
1199 
1200   /// Write out hot-function and hot-block statistics for base_profile,
1201   /// test_profile, and their overlap. For both cases, the overlap HO is
1202   /// calculated as follows:
1203   ///    Given the number of functions (or blocks) that are hot in both profiles
1204   ///    HCommon and the number of functions (or blocks) that are hot in at
1205   ///    least one profile HUnion, HO = HCommon / HUnion.
1206   void dumpHotFuncAndBlockOverlap(raw_fd_ostream &OS) const;
1207 
1208   /// This function tries matching functions in base and test profiles. For each
1209   /// pair of matched functions, it aggregates the function-level
1210   /// similarity into a profile-level similarity. It also dump function-level
1211   /// similarity information of functions specified by --function,
1212   /// --value-cutoff, and --similarity-cutoff options. The program-level
1213   /// similarity PS is computed as follows:
1214   ///     Given function-level similarity FS(A) for all function A, the
1215   ///     weight of function A in base profile WB(A), and the weight of function
1216   ///     A in test profile WT(A), compute PS(base_profile, test_profile) =
1217   ///     sum_A(FS(A) * avg(WB(A), WT(A))) ranging in [0.0f to 1.0f] with 0.0
1218   ///     meaning no-overlap.
1219   void computeSampleProfileOverlap(raw_fd_ostream &OS);
1220 
1221   /// Initialize ProfOverlap with the sum of samples in base and test
1222   /// profiles. This function also computes and keeps the sum of samples and
1223   /// max sample counts of each function in BaseStats and TestStats for later
1224   /// use to avoid re-computations.
1225   void initializeSampleProfileOverlap();
1226 
1227   /// Load profiles specified by BaseFilename and TestFilename.
1228   std::error_code loadProfiles();
1229 
1230   using FuncSampleStatsMap =
1231       std::unordered_map<SampleContext, FuncSampleStats, SampleContext::Hash>;
1232 
1233 private:
1234   SampleOverlapStats ProfOverlap;
1235   SampleOverlapStats HotFuncOverlap;
1236   SampleOverlapStats HotBlockOverlap;
1237   std::string BaseFilename;
1238   std::string TestFilename;
1239   std::unique_ptr<sampleprof::SampleProfileReader> BaseReader;
1240   std::unique_ptr<sampleprof::SampleProfileReader> TestReader;
1241   // BaseStats and TestStats hold FuncSampleStats for each function, with
1242   // function name as the key.
1243   FuncSampleStatsMap BaseStats;
1244   FuncSampleStatsMap TestStats;
1245   // Low similarity threshold in floating point number
1246   double LowSimilarityThreshold;
1247   // Block samples above BaseHotThreshold or TestHotThreshold are considered hot
1248   // for tracking hot blocks.
1249   uint64_t BaseHotThreshold;
1250   uint64_t TestHotThreshold;
1251   // A small threshold used to round the results of floating point accumulations
1252   // to resolve imprecision.
1253   const double Epsilon;
1254   std::multimap<double, SampleOverlapStats, std::greater<double>>
1255       FuncSimilarityDump;
1256   // FuncFilter carries specifications in options --value-cutoff and
1257   // --function.
1258   OverlapFuncFilters FuncFilter;
1259   // Column offsets for printing the function-level details table.
1260   static const unsigned int TestWeightCol = 15;
1261   static const unsigned int SimilarityCol = 30;
1262   static const unsigned int OverlapCol = 43;
1263   static const unsigned int BaseUniqueCol = 53;
1264   static const unsigned int TestUniqueCol = 67;
1265   static const unsigned int BaseSampleCol = 81;
1266   static const unsigned int TestSampleCol = 96;
1267   static const unsigned int FuncNameCol = 111;
1268 
1269   /// Return a similarity of two line/block sample counters in the same
1270   /// function in base and test profiles. The line/block-similarity BS(i) is
1271   /// computed as follows:
1272   ///    For an offsets i, given the sample count at i in base profile BB(i),
1273   ///    the sample count at i in test profile BT(i), the sum of sample counts
1274   ///    in this function in base profile SB, and the sum of sample counts in
1275   ///    this function in test profile ST, compute BS(i) = 1.0 - fabs(BB(i)/SB -
1276   ///    BT(i)/ST), ranging in [0.0f to 1.0f] with 0.0 meaning no-overlap.
1277   double computeBlockSimilarity(uint64_t BaseSample, uint64_t TestSample,
1278                                 const SampleOverlapStats &FuncOverlap) const;
1279 
1280   void updateHotBlockOverlap(uint64_t BaseSample, uint64_t TestSample,
1281                              uint64_t HotBlockCount);
1282 
1283   void getHotFunctions(const FuncSampleStatsMap &ProfStats,
1284                        FuncSampleStatsMap &HotFunc,
1285                        uint64_t HotThreshold) const;
1286 
1287   void computeHotFuncOverlap();
1288 
1289   /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
1290   /// Difference for two sample units in a matched function according to the
1291   /// given match status.
1292   void updateOverlapStatsForFunction(uint64_t BaseSample, uint64_t TestSample,
1293                                      uint64_t HotBlockCount,
1294                                      SampleOverlapStats &FuncOverlap,
1295                                      double &Difference, MatchStatus Status);
1296 
1297   /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
1298   /// Difference for unmatched callees that only present in one profile in a
1299   /// matched caller function.
1300   void updateForUnmatchedCallee(const sampleprof::FunctionSamples &Func,
1301                                 SampleOverlapStats &FuncOverlap,
1302                                 double &Difference, MatchStatus Status);
1303 
1304   /// This function updates sample overlap statistics of an overlap function in
1305   /// base and test profile. It also calculates a function-internal similarity
1306   /// FIS as follows:
1307   ///    For offsets i that have samples in at least one profile in this
1308   ///    function A, given BS(i) returned by computeBlockSimilarity(), compute
1309   ///    FIS(A) = (2.0 - sum_i(1.0 - BS(i))) / 2, ranging in [0.0f to 1.0f] with
1310   ///    0.0 meaning no overlap.
1311   double computeSampleFunctionInternalOverlap(
1312       const sampleprof::FunctionSamples &BaseFunc,
1313       const sampleprof::FunctionSamples &TestFunc,
1314       SampleOverlapStats &FuncOverlap);
1315 
1316   /// Function-level similarity (FS) is a weighted value over function internal
1317   /// similarity (FIS). This function computes a function's FS from its FIS by
1318   /// applying the weight.
1319   double weightForFuncSimilarity(double FuncSimilarity, uint64_t BaseFuncSample,
1320                                  uint64_t TestFuncSample) const;
1321 
1322   /// The function-level similarity FS(A) for a function A is computed as
1323   /// follows:
1324   ///     Compute a function-internal similarity FIS(A) by
1325   ///     computeSampleFunctionInternalOverlap(). Then, with the weight of
1326   ///     function A in base profile WB(A), and the weight of function A in test
1327   ///     profile WT(A), compute FS(A) = FIS(A) * (1.0 - fabs(WB(A) - WT(A)))
1328   ///     ranging in [0.0f to 1.0f] with 0.0 meaning no overlap.
1329   double
1330   computeSampleFunctionOverlap(const sampleprof::FunctionSamples *BaseFunc,
1331                                const sampleprof::FunctionSamples *TestFunc,
1332                                SampleOverlapStats *FuncOverlap,
1333                                uint64_t BaseFuncSample,
1334                                uint64_t TestFuncSample);
1335 
1336   /// Profile-level similarity (PS) is a weighted aggregate over function-level
1337   /// similarities (FS). This method weights the FS value by the function
1338   /// weights in the base and test profiles for the aggregation.
1339   double weightByImportance(double FuncSimilarity, uint64_t BaseFuncSample,
1340                             uint64_t TestFuncSample) const;
1341 };
1342 } // end anonymous namespace
1343 
1344 bool SampleOverlapAggregator::detectZeroSampleProfile(
1345     raw_fd_ostream &OS) const {
1346   bool HaveZeroSample = false;
1347   if (ProfOverlap.BaseSample == 0) {
1348     OS << "Sum of sample counts for profile " << BaseFilename << " is 0.\n";
1349     HaveZeroSample = true;
1350   }
1351   if (ProfOverlap.TestSample == 0) {
1352     OS << "Sum of sample counts for profile " << TestFilename << " is 0.\n";
1353     HaveZeroSample = true;
1354   }
1355   return HaveZeroSample;
1356 }
1357 
1358 double SampleOverlapAggregator::computeBlockSimilarity(
1359     uint64_t BaseSample, uint64_t TestSample,
1360     const SampleOverlapStats &FuncOverlap) const {
1361   double BaseFrac = 0.0;
1362   double TestFrac = 0.0;
1363   if (FuncOverlap.BaseSample > 0)
1364     BaseFrac = static_cast<double>(BaseSample) / FuncOverlap.BaseSample;
1365   if (FuncOverlap.TestSample > 0)
1366     TestFrac = static_cast<double>(TestSample) / FuncOverlap.TestSample;
1367   return 1.0 - std::fabs(BaseFrac - TestFrac);
1368 }
1369 
1370 void SampleOverlapAggregator::updateHotBlockOverlap(uint64_t BaseSample,
1371                                                     uint64_t TestSample,
1372                                                     uint64_t HotBlockCount) {
1373   bool IsBaseHot = (BaseSample >= BaseHotThreshold);
1374   bool IsTestHot = (TestSample >= TestHotThreshold);
1375   if (!IsBaseHot && !IsTestHot)
1376     return;
1377 
1378   HotBlockOverlap.UnionCount += HotBlockCount;
1379   if (IsBaseHot)
1380     HotBlockOverlap.BaseCount += HotBlockCount;
1381   if (IsTestHot)
1382     HotBlockOverlap.TestCount += HotBlockCount;
1383   if (IsBaseHot && IsTestHot)
1384     HotBlockOverlap.OverlapCount += HotBlockCount;
1385 }
1386 
1387 void SampleOverlapAggregator::getHotFunctions(
1388     const FuncSampleStatsMap &ProfStats, FuncSampleStatsMap &HotFunc,
1389     uint64_t HotThreshold) const {
1390   for (const auto &F : ProfStats) {
1391     if (isFunctionHot(F.second, HotThreshold))
1392       HotFunc.emplace(F.first, F.second);
1393   }
1394 }
1395 
1396 void SampleOverlapAggregator::computeHotFuncOverlap() {
1397   FuncSampleStatsMap BaseHotFunc;
1398   getHotFunctions(BaseStats, BaseHotFunc, BaseHotThreshold);
1399   HotFuncOverlap.BaseCount = BaseHotFunc.size();
1400 
1401   FuncSampleStatsMap TestHotFunc;
1402   getHotFunctions(TestStats, TestHotFunc, TestHotThreshold);
1403   HotFuncOverlap.TestCount = TestHotFunc.size();
1404   HotFuncOverlap.UnionCount = HotFuncOverlap.TestCount;
1405 
1406   for (const auto &F : BaseHotFunc) {
1407     if (TestHotFunc.count(F.first))
1408       ++HotFuncOverlap.OverlapCount;
1409     else
1410       ++HotFuncOverlap.UnionCount;
1411   }
1412 }
1413 
1414 void SampleOverlapAggregator::updateOverlapStatsForFunction(
1415     uint64_t BaseSample, uint64_t TestSample, uint64_t HotBlockCount,
1416     SampleOverlapStats &FuncOverlap, double &Difference, MatchStatus Status) {
1417   assert(Status != MS_None &&
1418          "Match status should be updated before updating overlap statistics");
1419   if (Status == MS_FirstUnique) {
1420     TestSample = 0;
1421     FuncOverlap.BaseUniqueSample += BaseSample;
1422   } else if (Status == MS_SecondUnique) {
1423     BaseSample = 0;
1424     FuncOverlap.TestUniqueSample += TestSample;
1425   } else {
1426     ++FuncOverlap.OverlapCount;
1427   }
1428 
1429   FuncOverlap.UnionSample += std::max(BaseSample, TestSample);
1430   FuncOverlap.OverlapSample += std::min(BaseSample, TestSample);
1431   Difference +=
1432       1.0 - computeBlockSimilarity(BaseSample, TestSample, FuncOverlap);
1433   updateHotBlockOverlap(BaseSample, TestSample, HotBlockCount);
1434 }
1435 
1436 void SampleOverlapAggregator::updateForUnmatchedCallee(
1437     const sampleprof::FunctionSamples &Func, SampleOverlapStats &FuncOverlap,
1438     double &Difference, MatchStatus Status) {
1439   assert((Status == MS_FirstUnique || Status == MS_SecondUnique) &&
1440          "Status must be either of the two unmatched cases");
1441   FuncSampleStats FuncStats;
1442   if (Status == MS_FirstUnique) {
1443     getFuncSampleStats(Func, FuncStats, BaseHotThreshold);
1444     updateOverlapStatsForFunction(FuncStats.SampleSum, 0,
1445                                   FuncStats.HotBlockCount, FuncOverlap,
1446                                   Difference, Status);
1447   } else {
1448     getFuncSampleStats(Func, FuncStats, TestHotThreshold);
1449     updateOverlapStatsForFunction(0, FuncStats.SampleSum,
1450                                   FuncStats.HotBlockCount, FuncOverlap,
1451                                   Difference, Status);
1452   }
1453 }
1454 
1455 double SampleOverlapAggregator::computeSampleFunctionInternalOverlap(
1456     const sampleprof::FunctionSamples &BaseFunc,
1457     const sampleprof::FunctionSamples &TestFunc,
1458     SampleOverlapStats &FuncOverlap) {
1459 
1460   using namespace sampleprof;
1461 
1462   double Difference = 0;
1463 
1464   // Accumulate Difference for regular line/block samples in the function.
1465   // We match them through sort-merge join algorithm because
1466   // FunctionSamples::getBodySamples() returns a map of sample counters ordered
1467   // by their offsets.
1468   MatchStep<BodySampleMap::const_iterator> BlockIterStep(
1469       BaseFunc.getBodySamples().cbegin(), BaseFunc.getBodySamples().cend(),
1470       TestFunc.getBodySamples().cbegin(), TestFunc.getBodySamples().cend());
1471   BlockIterStep.updateOneStep();
1472   while (!BlockIterStep.areBothFinished()) {
1473     uint64_t BaseSample =
1474         BlockIterStep.isFirstFinished()
1475             ? 0
1476             : BlockIterStep.getFirstIter()->second.getSamples();
1477     uint64_t TestSample =
1478         BlockIterStep.isSecondFinished()
1479             ? 0
1480             : BlockIterStep.getSecondIter()->second.getSamples();
1481     updateOverlapStatsForFunction(BaseSample, TestSample, 1, FuncOverlap,
1482                                   Difference, BlockIterStep.getMatchStatus());
1483 
1484     BlockIterStep.updateOneStep();
1485   }
1486 
1487   // Accumulate Difference for callsite lines in the function. We match
1488   // them through sort-merge algorithm because
1489   // FunctionSamples::getCallsiteSamples() returns a map of callsite records
1490   // ordered by their offsets.
1491   MatchStep<CallsiteSampleMap::const_iterator> CallsiteIterStep(
1492       BaseFunc.getCallsiteSamples().cbegin(),
1493       BaseFunc.getCallsiteSamples().cend(),
1494       TestFunc.getCallsiteSamples().cbegin(),
1495       TestFunc.getCallsiteSamples().cend());
1496   CallsiteIterStep.updateOneStep();
1497   while (!CallsiteIterStep.areBothFinished()) {
1498     MatchStatus CallsiteStepStatus = CallsiteIterStep.getMatchStatus();
1499     assert(CallsiteStepStatus != MS_None &&
1500            "Match status should be updated before entering loop body");
1501 
1502     if (CallsiteStepStatus != MS_Match) {
1503       auto Callsite = (CallsiteStepStatus == MS_FirstUnique)
1504                           ? CallsiteIterStep.getFirstIter()
1505                           : CallsiteIterStep.getSecondIter();
1506       for (const auto &F : Callsite->second)
1507         updateForUnmatchedCallee(F.second, FuncOverlap, Difference,
1508                                  CallsiteStepStatus);
1509     } else {
1510       // There may be multiple inlinees at the same offset, so we need to try
1511       // matching all of them. This match is implemented through sort-merge
1512       // algorithm because callsite records at the same offset are ordered by
1513       // function names.
1514       MatchStep<FunctionSamplesMap::const_iterator> CalleeIterStep(
1515           CallsiteIterStep.getFirstIter()->second.cbegin(),
1516           CallsiteIterStep.getFirstIter()->second.cend(),
1517           CallsiteIterStep.getSecondIter()->second.cbegin(),
1518           CallsiteIterStep.getSecondIter()->second.cend());
1519       CalleeIterStep.updateOneStep();
1520       while (!CalleeIterStep.areBothFinished()) {
1521         MatchStatus CalleeStepStatus = CalleeIterStep.getMatchStatus();
1522         if (CalleeStepStatus != MS_Match) {
1523           auto Callee = (CalleeStepStatus == MS_FirstUnique)
1524                             ? CalleeIterStep.getFirstIter()
1525                             : CalleeIterStep.getSecondIter();
1526           updateForUnmatchedCallee(Callee->second, FuncOverlap, Difference,
1527                                    CalleeStepStatus);
1528         } else {
1529           // An inlined function can contain other inlinees inside, so compute
1530           // the Difference recursively.
1531           Difference += 2.0 - 2 * computeSampleFunctionInternalOverlap(
1532                                       CalleeIterStep.getFirstIter()->second,
1533                                       CalleeIterStep.getSecondIter()->second,
1534                                       FuncOverlap);
1535         }
1536         CalleeIterStep.updateOneStep();
1537       }
1538     }
1539     CallsiteIterStep.updateOneStep();
1540   }
1541 
1542   // Difference reflects the total differences of line/block samples in this
1543   // function and ranges in [0.0f to 2.0f]. Take (2.0 - Difference) / 2 to
1544   // reflect the similarity between function profiles in [0.0f to 1.0f].
1545   return (2.0 - Difference) / 2;
1546 }
1547 
1548 double SampleOverlapAggregator::weightForFuncSimilarity(
1549     double FuncInternalSimilarity, uint64_t BaseFuncSample,
1550     uint64_t TestFuncSample) const {
1551   // Compute the weight as the distance between the function weights in two
1552   // profiles.
1553   double BaseFrac = 0.0;
1554   double TestFrac = 0.0;
1555   assert(ProfOverlap.BaseSample > 0 &&
1556          "Total samples in base profile should be greater than 0");
1557   BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample;
1558   assert(ProfOverlap.TestSample > 0 &&
1559          "Total samples in test profile should be greater than 0");
1560   TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample;
1561   double WeightDistance = std::fabs(BaseFrac - TestFrac);
1562 
1563   // Take WeightDistance into the similarity.
1564   return FuncInternalSimilarity * (1 - WeightDistance);
1565 }
1566 
1567 double
1568 SampleOverlapAggregator::weightByImportance(double FuncSimilarity,
1569                                             uint64_t BaseFuncSample,
1570                                             uint64_t TestFuncSample) const {
1571 
1572   double BaseFrac = 0.0;
1573   double TestFrac = 0.0;
1574   assert(ProfOverlap.BaseSample > 0 &&
1575          "Total samples in base profile should be greater than 0");
1576   BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample / 2.0;
1577   assert(ProfOverlap.TestSample > 0 &&
1578          "Total samples in test profile should be greater than 0");
1579   TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample / 2.0;
1580   return FuncSimilarity * (BaseFrac + TestFrac);
1581 }
1582 
1583 double SampleOverlapAggregator::computeSampleFunctionOverlap(
1584     const sampleprof::FunctionSamples *BaseFunc,
1585     const sampleprof::FunctionSamples *TestFunc,
1586     SampleOverlapStats *FuncOverlap, uint64_t BaseFuncSample,
1587     uint64_t TestFuncSample) {
1588   // Default function internal similarity before weighted, meaning two functions
1589   // has no overlap.
1590   const double DefaultFuncInternalSimilarity = 0;
1591   double FuncSimilarity;
1592   double FuncInternalSimilarity;
1593 
1594   // If BaseFunc or TestFunc is nullptr, it means the functions do not overlap.
1595   // In this case, we use DefaultFuncInternalSimilarity as the function internal
1596   // similarity.
1597   if (!BaseFunc || !TestFunc) {
1598     FuncInternalSimilarity = DefaultFuncInternalSimilarity;
1599   } else {
1600     assert(FuncOverlap != nullptr &&
1601            "FuncOverlap should be provided in this case");
1602     FuncInternalSimilarity = computeSampleFunctionInternalOverlap(
1603         *BaseFunc, *TestFunc, *FuncOverlap);
1604     // Now, FuncInternalSimilarity may be a little less than 0 due to
1605     // imprecision of floating point accumulations. Make it zero if the
1606     // difference is below Epsilon.
1607     FuncInternalSimilarity = (std::fabs(FuncInternalSimilarity - 0) < Epsilon)
1608                                  ? 0
1609                                  : FuncInternalSimilarity;
1610   }
1611   FuncSimilarity = weightForFuncSimilarity(FuncInternalSimilarity,
1612                                            BaseFuncSample, TestFuncSample);
1613   return FuncSimilarity;
1614 }
1615 
1616 void SampleOverlapAggregator::computeSampleProfileOverlap(raw_fd_ostream &OS) {
1617   using namespace sampleprof;
1618 
1619   std::unordered_map<SampleContext, const FunctionSamples *,
1620                      SampleContext::Hash>
1621       BaseFuncProf;
1622   const auto &BaseProfiles = BaseReader->getProfiles();
1623   for (const auto &BaseFunc : BaseProfiles) {
1624     BaseFuncProf.emplace(BaseFunc.second.getContext(), &(BaseFunc.second));
1625   }
1626   ProfOverlap.UnionCount = BaseFuncProf.size();
1627 
1628   const auto &TestProfiles = TestReader->getProfiles();
1629   for (const auto &TestFunc : TestProfiles) {
1630     SampleOverlapStats FuncOverlap;
1631     FuncOverlap.TestName = TestFunc.second.getContext();
1632     assert(TestStats.count(FuncOverlap.TestName) &&
1633            "TestStats should have records for all functions in test profile "
1634            "except inlinees");
1635     FuncOverlap.TestSample = TestStats[FuncOverlap.TestName].SampleSum;
1636 
1637     bool Matched = false;
1638     const auto Match = BaseFuncProf.find(FuncOverlap.TestName);
1639     if (Match == BaseFuncProf.end()) {
1640       const FuncSampleStats &FuncStats = TestStats[FuncOverlap.TestName];
1641       ++ProfOverlap.TestUniqueCount;
1642       ProfOverlap.TestUniqueSample += FuncStats.SampleSum;
1643       FuncOverlap.TestUniqueSample = FuncStats.SampleSum;
1644 
1645       updateHotBlockOverlap(0, FuncStats.SampleSum, FuncStats.HotBlockCount);
1646 
1647       double FuncSimilarity = computeSampleFunctionOverlap(
1648           nullptr, nullptr, nullptr, 0, FuncStats.SampleSum);
1649       ProfOverlap.Similarity +=
1650           weightByImportance(FuncSimilarity, 0, FuncStats.SampleSum);
1651 
1652       ++ProfOverlap.UnionCount;
1653       ProfOverlap.UnionSample += FuncStats.SampleSum;
1654     } else {
1655       ++ProfOverlap.OverlapCount;
1656 
1657       // Two functions match with each other. Compute function-level overlap and
1658       // aggregate them into profile-level overlap.
1659       FuncOverlap.BaseName = Match->second->getContext();
1660       assert(BaseStats.count(FuncOverlap.BaseName) &&
1661              "BaseStats should have records for all functions in base profile "
1662              "except inlinees");
1663       FuncOverlap.BaseSample = BaseStats[FuncOverlap.BaseName].SampleSum;
1664 
1665       FuncOverlap.Similarity = computeSampleFunctionOverlap(
1666           Match->second, &TestFunc.second, &FuncOverlap, FuncOverlap.BaseSample,
1667           FuncOverlap.TestSample);
1668       ProfOverlap.Similarity +=
1669           weightByImportance(FuncOverlap.Similarity, FuncOverlap.BaseSample,
1670                              FuncOverlap.TestSample);
1671       ProfOverlap.OverlapSample += FuncOverlap.OverlapSample;
1672       ProfOverlap.UnionSample += FuncOverlap.UnionSample;
1673 
1674       // Accumulate the percentage of base unique and test unique samples into
1675       // ProfOverlap.
1676       ProfOverlap.BaseUniqueSample += FuncOverlap.BaseUniqueSample;
1677       ProfOverlap.TestUniqueSample += FuncOverlap.TestUniqueSample;
1678 
1679       // Remove matched base functions for later reporting functions not found
1680       // in test profile.
1681       BaseFuncProf.erase(Match);
1682       Matched = true;
1683     }
1684 
1685     // Print function-level similarity information if specified by options.
1686     assert(TestStats.count(FuncOverlap.TestName) &&
1687            "TestStats should have records for all functions in test profile "
1688            "except inlinees");
1689     if (TestStats[FuncOverlap.TestName].MaxSample >= FuncFilter.ValueCutoff ||
1690         (Matched && FuncOverlap.Similarity < LowSimilarityThreshold) ||
1691         (Matched && !FuncFilter.NameFilter.empty() &&
1692          FuncOverlap.BaseName.toString().find(FuncFilter.NameFilter) !=
1693              std::string::npos)) {
1694       assert(ProfOverlap.BaseSample > 0 &&
1695              "Total samples in base profile should be greater than 0");
1696       FuncOverlap.BaseWeight =
1697           static_cast<double>(FuncOverlap.BaseSample) / ProfOverlap.BaseSample;
1698       assert(ProfOverlap.TestSample > 0 &&
1699              "Total samples in test profile should be greater than 0");
1700       FuncOverlap.TestWeight =
1701           static_cast<double>(FuncOverlap.TestSample) / ProfOverlap.TestSample;
1702       FuncSimilarityDump.emplace(FuncOverlap.BaseWeight, FuncOverlap);
1703     }
1704   }
1705 
1706   // Traverse through functions in base profile but not in test profile.
1707   for (const auto &F : BaseFuncProf) {
1708     assert(BaseStats.count(F.second->getContext()) &&
1709            "BaseStats should have records for all functions in base profile "
1710            "except inlinees");
1711     const FuncSampleStats &FuncStats = BaseStats[F.second->getContext()];
1712     ++ProfOverlap.BaseUniqueCount;
1713     ProfOverlap.BaseUniqueSample += FuncStats.SampleSum;
1714 
1715     updateHotBlockOverlap(FuncStats.SampleSum, 0, FuncStats.HotBlockCount);
1716 
1717     double FuncSimilarity = computeSampleFunctionOverlap(
1718         nullptr, nullptr, nullptr, FuncStats.SampleSum, 0);
1719     ProfOverlap.Similarity +=
1720         weightByImportance(FuncSimilarity, FuncStats.SampleSum, 0);
1721 
1722     ProfOverlap.UnionSample += FuncStats.SampleSum;
1723   }
1724 
1725   // Now, ProfSimilarity may be a little greater than 1 due to imprecision
1726   // of floating point accumulations. Make it 1.0 if the difference is below
1727   // Epsilon.
1728   ProfOverlap.Similarity = (std::fabs(ProfOverlap.Similarity - 1) < Epsilon)
1729                                ? 1
1730                                : ProfOverlap.Similarity;
1731 
1732   computeHotFuncOverlap();
1733 }
1734 
1735 void SampleOverlapAggregator::initializeSampleProfileOverlap() {
1736   const auto &BaseProf = BaseReader->getProfiles();
1737   for (const auto &I : BaseProf) {
1738     ++ProfOverlap.BaseCount;
1739     FuncSampleStats FuncStats;
1740     getFuncSampleStats(I.second, FuncStats, BaseHotThreshold);
1741     ProfOverlap.BaseSample += FuncStats.SampleSum;
1742     BaseStats.emplace(I.second.getContext(), FuncStats);
1743   }
1744 
1745   const auto &TestProf = TestReader->getProfiles();
1746   for (const auto &I : TestProf) {
1747     ++ProfOverlap.TestCount;
1748     FuncSampleStats FuncStats;
1749     getFuncSampleStats(I.second, FuncStats, TestHotThreshold);
1750     ProfOverlap.TestSample += FuncStats.SampleSum;
1751     TestStats.emplace(I.second.getContext(), FuncStats);
1752   }
1753 
1754   ProfOverlap.BaseName = StringRef(BaseFilename);
1755   ProfOverlap.TestName = StringRef(TestFilename);
1756 }
1757 
1758 void SampleOverlapAggregator::dumpFuncSimilarity(raw_fd_ostream &OS) const {
1759   using namespace sampleprof;
1760 
1761   if (FuncSimilarityDump.empty())
1762     return;
1763 
1764   formatted_raw_ostream FOS(OS);
1765   FOS << "Function-level details:\n";
1766   FOS << "Base weight";
1767   FOS.PadToColumn(TestWeightCol);
1768   FOS << "Test weight";
1769   FOS.PadToColumn(SimilarityCol);
1770   FOS << "Similarity";
1771   FOS.PadToColumn(OverlapCol);
1772   FOS << "Overlap";
1773   FOS.PadToColumn(BaseUniqueCol);
1774   FOS << "Base unique";
1775   FOS.PadToColumn(TestUniqueCol);
1776   FOS << "Test unique";
1777   FOS.PadToColumn(BaseSampleCol);
1778   FOS << "Base samples";
1779   FOS.PadToColumn(TestSampleCol);
1780   FOS << "Test samples";
1781   FOS.PadToColumn(FuncNameCol);
1782   FOS << "Function name\n";
1783   for (const auto &F : FuncSimilarityDump) {
1784     double OverlapPercent =
1785         F.second.UnionSample > 0
1786             ? static_cast<double>(F.second.OverlapSample) / F.second.UnionSample
1787             : 0;
1788     double BaseUniquePercent =
1789         F.second.BaseSample > 0
1790             ? static_cast<double>(F.second.BaseUniqueSample) /
1791                   F.second.BaseSample
1792             : 0;
1793     double TestUniquePercent =
1794         F.second.TestSample > 0
1795             ? static_cast<double>(F.second.TestUniqueSample) /
1796                   F.second.TestSample
1797             : 0;
1798 
1799     FOS << format("%.2f%%", F.second.BaseWeight * 100);
1800     FOS.PadToColumn(TestWeightCol);
1801     FOS << format("%.2f%%", F.second.TestWeight * 100);
1802     FOS.PadToColumn(SimilarityCol);
1803     FOS << format("%.2f%%", F.second.Similarity * 100);
1804     FOS.PadToColumn(OverlapCol);
1805     FOS << format("%.2f%%", OverlapPercent * 100);
1806     FOS.PadToColumn(BaseUniqueCol);
1807     FOS << format("%.2f%%", BaseUniquePercent * 100);
1808     FOS.PadToColumn(TestUniqueCol);
1809     FOS << format("%.2f%%", TestUniquePercent * 100);
1810     FOS.PadToColumn(BaseSampleCol);
1811     FOS << F.second.BaseSample;
1812     FOS.PadToColumn(TestSampleCol);
1813     FOS << F.second.TestSample;
1814     FOS.PadToColumn(FuncNameCol);
1815     FOS << F.second.TestName.toString() << "\n";
1816   }
1817 }
1818 
1819 void SampleOverlapAggregator::dumpProgramSummary(raw_fd_ostream &OS) const {
1820   OS << "Profile overlap infomation for base_profile: "
1821      << ProfOverlap.BaseName.toString()
1822      << " and test_profile: " << ProfOverlap.TestName.toString()
1823      << "\nProgram level:\n";
1824 
1825   OS << "  Whole program profile similarity: "
1826      << format("%.3f%%", ProfOverlap.Similarity * 100) << "\n";
1827 
1828   assert(ProfOverlap.UnionSample > 0 &&
1829          "Total samples in two profile should be greater than 0");
1830   double OverlapPercent =
1831       static_cast<double>(ProfOverlap.OverlapSample) / ProfOverlap.UnionSample;
1832   assert(ProfOverlap.BaseSample > 0 &&
1833          "Total samples in base profile should be greater than 0");
1834   double BaseUniquePercent = static_cast<double>(ProfOverlap.BaseUniqueSample) /
1835                              ProfOverlap.BaseSample;
1836   assert(ProfOverlap.TestSample > 0 &&
1837          "Total samples in test profile should be greater than 0");
1838   double TestUniquePercent = static_cast<double>(ProfOverlap.TestUniqueSample) /
1839                              ProfOverlap.TestSample;
1840 
1841   OS << "  Whole program sample overlap: "
1842      << format("%.3f%%", OverlapPercent * 100) << "\n";
1843   OS << "    percentage of samples unique in base profile: "
1844      << format("%.3f%%", BaseUniquePercent * 100) << "\n";
1845   OS << "    percentage of samples unique in test profile: "
1846      << format("%.3f%%", TestUniquePercent * 100) << "\n";
1847   OS << "    total samples in base profile: " << ProfOverlap.BaseSample << "\n"
1848      << "    total samples in test profile: " << ProfOverlap.TestSample << "\n";
1849 
1850   assert(ProfOverlap.UnionCount > 0 &&
1851          "There should be at least one function in two input profiles");
1852   double FuncOverlapPercent =
1853       static_cast<double>(ProfOverlap.OverlapCount) / ProfOverlap.UnionCount;
1854   OS << "  Function overlap: " << format("%.3f%%", FuncOverlapPercent * 100)
1855      << "\n";
1856   OS << "    overlap functions: " << ProfOverlap.OverlapCount << "\n";
1857   OS << "    functions unique in base profile: " << ProfOverlap.BaseUniqueCount
1858      << "\n";
1859   OS << "    functions unique in test profile: " << ProfOverlap.TestUniqueCount
1860      << "\n";
1861 }
1862 
1863 void SampleOverlapAggregator::dumpHotFuncAndBlockOverlap(
1864     raw_fd_ostream &OS) const {
1865   assert(HotFuncOverlap.UnionCount > 0 &&
1866          "There should be at least one hot function in two input profiles");
1867   OS << "  Hot-function overlap: "
1868      << format("%.3f%%", static_cast<double>(HotFuncOverlap.OverlapCount) /
1869                              HotFuncOverlap.UnionCount * 100)
1870      << "\n";
1871   OS << "    overlap hot functions: " << HotFuncOverlap.OverlapCount << "\n";
1872   OS << "    hot functions unique in base profile: "
1873      << HotFuncOverlap.BaseCount - HotFuncOverlap.OverlapCount << "\n";
1874   OS << "    hot functions unique in test profile: "
1875      << HotFuncOverlap.TestCount - HotFuncOverlap.OverlapCount << "\n";
1876 
1877   assert(HotBlockOverlap.UnionCount > 0 &&
1878          "There should be at least one hot block in two input profiles");
1879   OS << "  Hot-block overlap: "
1880      << format("%.3f%%", static_cast<double>(HotBlockOverlap.OverlapCount) /
1881                              HotBlockOverlap.UnionCount * 100)
1882      << "\n";
1883   OS << "    overlap hot blocks: " << HotBlockOverlap.OverlapCount << "\n";
1884   OS << "    hot blocks unique in base profile: "
1885      << HotBlockOverlap.BaseCount - HotBlockOverlap.OverlapCount << "\n";
1886   OS << "    hot blocks unique in test profile: "
1887      << HotBlockOverlap.TestCount - HotBlockOverlap.OverlapCount << "\n";
1888 }
1889 
1890 std::error_code SampleOverlapAggregator::loadProfiles() {
1891   using namespace sampleprof;
1892 
1893   LLVMContext Context;
1894   auto BaseReaderOrErr = SampleProfileReader::create(BaseFilename, Context,
1895                                                      FSDiscriminatorPassOption);
1896   if (std::error_code EC = BaseReaderOrErr.getError())
1897     exitWithErrorCode(EC, BaseFilename);
1898 
1899   auto TestReaderOrErr = SampleProfileReader::create(TestFilename, Context,
1900                                                      FSDiscriminatorPassOption);
1901   if (std::error_code EC = TestReaderOrErr.getError())
1902     exitWithErrorCode(EC, TestFilename);
1903 
1904   BaseReader = std::move(BaseReaderOrErr.get());
1905   TestReader = std::move(TestReaderOrErr.get());
1906 
1907   if (std::error_code EC = BaseReader->read())
1908     exitWithErrorCode(EC, BaseFilename);
1909   if (std::error_code EC = TestReader->read())
1910     exitWithErrorCode(EC, TestFilename);
1911   if (BaseReader->profileIsProbeBased() != TestReader->profileIsProbeBased())
1912     exitWithError(
1913         "cannot compare probe-based profile with non-probe-based profile");
1914   if (BaseReader->profileIsCS() != TestReader->profileIsCS())
1915     exitWithError("cannot compare CS profile with non-CS profile");
1916 
1917   // Load BaseHotThreshold and TestHotThreshold as 99-percentile threshold in
1918   // profile summary.
1919   ProfileSummary &BasePS = BaseReader->getSummary();
1920   ProfileSummary &TestPS = TestReader->getSummary();
1921   BaseHotThreshold =
1922       ProfileSummaryBuilder::getHotCountThreshold(BasePS.getDetailedSummary());
1923   TestHotThreshold =
1924       ProfileSummaryBuilder::getHotCountThreshold(TestPS.getDetailedSummary());
1925 
1926   return std::error_code();
1927 }
1928 
1929 void overlapSampleProfile(const std::string &BaseFilename,
1930                           const std::string &TestFilename,
1931                           const OverlapFuncFilters &FuncFilter,
1932                           uint64_t SimilarityCutoff, raw_fd_ostream &OS) {
1933   using namespace sampleprof;
1934 
1935   // We use 0.000005 to initialize OverlapAggr.Epsilon because the final metrics
1936   // report 2--3 places after decimal point in percentage numbers.
1937   SampleOverlapAggregator OverlapAggr(
1938       BaseFilename, TestFilename,
1939       static_cast<double>(SimilarityCutoff) / 1000000, 0.000005, FuncFilter);
1940   if (std::error_code EC = OverlapAggr.loadProfiles())
1941     exitWithErrorCode(EC);
1942 
1943   OverlapAggr.initializeSampleProfileOverlap();
1944   if (OverlapAggr.detectZeroSampleProfile(OS))
1945     return;
1946 
1947   OverlapAggr.computeSampleProfileOverlap(OS);
1948 
1949   OverlapAggr.dumpProgramSummary(OS);
1950   OverlapAggr.dumpHotFuncAndBlockOverlap(OS);
1951   OverlapAggr.dumpFuncSimilarity(OS);
1952 }
1953 
1954 static int overlap_main(int argc, const char *argv[]) {
1955   cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
1956                                     cl::desc("<base profile file>"));
1957   cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
1958                                     cl::desc("<test profile file>"));
1959   cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
1960                               cl::desc("Output file"));
1961   cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
1962   cl::opt<bool> IsCS(
1963       "cs", cl::init(false),
1964       cl::desc("For context sensitive PGO counts. Does not work with CSSPGO."));
1965   cl::opt<unsigned long long> ValueCutoff(
1966       "value-cutoff", cl::init(-1),
1967       cl::desc(
1968           "Function level overlap information for every function (with calling "
1969           "context for csspgo) in test "
1970           "profile with max count value greater then the parameter value"));
1971   cl::opt<std::string> FuncNameFilter(
1972       "function",
1973       cl::desc("Function level overlap information for matching functions. For "
1974                "CSSPGO this takes a a function name with calling context"));
1975   cl::opt<unsigned long long> SimilarityCutoff(
1976       "similarity-cutoff", cl::init(0),
1977       cl::desc("For sample profiles, list function names (with calling context "
1978                "for csspgo) for overlapped functions "
1979                "with similarities below the cutoff (percentage times 10000)."));
1980   cl::opt<ProfileKinds> ProfileKind(
1981       cl::desc("Profile kind:"), cl::init(instr),
1982       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
1983                  clEnumVal(sample, "Sample profile")));
1984   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
1985 
1986   std::error_code EC;
1987   raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_TextWithCRLF);
1988   if (EC)
1989     exitWithErrorCode(EC, Output);
1990 
1991   if (ProfileKind == instr)
1992     overlapInstrProfile(BaseFilename, TestFilename,
1993                         OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
1994                         IsCS);
1995   else
1996     overlapSampleProfile(BaseFilename, TestFilename,
1997                          OverlapFuncFilters{ValueCutoff, FuncNameFilter},
1998                          SimilarityCutoff, OS);
1999 
2000   return 0;
2001 }
2002 
2003 namespace {
2004 struct ValueSitesStats {
2005   ValueSitesStats()
2006       : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
2007         TotalNumValues(0) {}
2008   uint64_t TotalNumValueSites;
2009   uint64_t TotalNumValueSitesWithValueProfile;
2010   uint64_t TotalNumValues;
2011   std::vector<unsigned> ValueSitesHistogram;
2012 };
2013 } // namespace
2014 
2015 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
2016                                   ValueSitesStats &Stats, raw_fd_ostream &OS,
2017                                   InstrProfSymtab *Symtab) {
2018   uint32_t NS = Func.getNumValueSites(VK);
2019   Stats.TotalNumValueSites += NS;
2020   for (size_t I = 0; I < NS; ++I) {
2021     uint32_t NV = Func.getNumValueDataForSite(VK, I);
2022     std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
2023     Stats.TotalNumValues += NV;
2024     if (NV) {
2025       Stats.TotalNumValueSitesWithValueProfile++;
2026       if (NV > Stats.ValueSitesHistogram.size())
2027         Stats.ValueSitesHistogram.resize(NV, 0);
2028       Stats.ValueSitesHistogram[NV - 1]++;
2029     }
2030 
2031     uint64_t SiteSum = 0;
2032     for (uint32_t V = 0; V < NV; V++)
2033       SiteSum += VD[V].Count;
2034     if (SiteSum == 0)
2035       SiteSum = 1;
2036 
2037     for (uint32_t V = 0; V < NV; V++) {
2038       OS << "\t[ " << format("%2u", I) << ", ";
2039       if (Symtab == nullptr)
2040         OS << format("%4" PRIu64, VD[V].Value);
2041       else
2042         OS << Symtab->getFuncName(VD[V].Value);
2043       OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
2044          << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
2045     }
2046   }
2047 }
2048 
2049 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
2050                                 ValueSitesStats &Stats) {
2051   OS << "  Total number of sites: " << Stats.TotalNumValueSites << "\n";
2052   OS << "  Total number of sites with values: "
2053      << Stats.TotalNumValueSitesWithValueProfile << "\n";
2054   OS << "  Total number of profiled values: " << Stats.TotalNumValues << "\n";
2055 
2056   OS << "  Value sites histogram:\n\tNumTargets, SiteCount\n";
2057   for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
2058     if (Stats.ValueSitesHistogram[I] > 0)
2059       OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
2060   }
2061 }
2062 
2063 static int showInstrProfile(const std::string &Filename, bool ShowCounts,
2064                             uint32_t TopN, bool ShowIndirectCallTargets,
2065                             bool ShowMemOPSizes, bool ShowDetailedSummary,
2066                             std::vector<uint32_t> DetailedSummaryCutoffs,
2067                             bool ShowAllFunctions, bool ShowCS,
2068                             uint64_t ValueCutoff, bool OnlyListBelow,
2069                             const std::string &ShowFunction, bool TextFormat,
2070                             bool ShowBinaryIds, raw_fd_ostream &OS) {
2071   auto ReaderOrErr = InstrProfReader::create(Filename);
2072   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
2073   if (ShowDetailedSummary && Cutoffs.empty()) {
2074     Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
2075   }
2076   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
2077   if (Error E = ReaderOrErr.takeError())
2078     exitWithError(std::move(E), Filename);
2079 
2080   auto Reader = std::move(ReaderOrErr.get());
2081   bool IsIRInstr = Reader->isIRLevelProfile();
2082   size_t ShownFunctions = 0;
2083   size_t BelowCutoffFunctions = 0;
2084   int NumVPKind = IPVK_Last - IPVK_First + 1;
2085   std::vector<ValueSitesStats> VPStats(NumVPKind);
2086 
2087   auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
2088                    const std::pair<std::string, uint64_t> &v2) {
2089     return v1.second > v2.second;
2090   };
2091 
2092   std::priority_queue<std::pair<std::string, uint64_t>,
2093                       std::vector<std::pair<std::string, uint64_t>>,
2094                       decltype(MinCmp)>
2095       HottestFuncs(MinCmp);
2096 
2097   if (!TextFormat && OnlyListBelow) {
2098     OS << "The list of functions with the maximum counter less than "
2099        << ValueCutoff << ":\n";
2100   }
2101 
2102   // Add marker so that IR-level instrumentation round-trips properly.
2103   if (TextFormat && IsIRInstr)
2104     OS << ":ir\n";
2105 
2106   for (const auto &Func : *Reader) {
2107     if (Reader->isIRLevelProfile()) {
2108       bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
2109       if (FuncIsCS != ShowCS)
2110         continue;
2111     }
2112     bool Show = ShowAllFunctions ||
2113                 (!ShowFunction.empty() && Func.Name.contains(ShowFunction));
2114 
2115     bool doTextFormatDump = (Show && TextFormat);
2116 
2117     if (doTextFormatDump) {
2118       InstrProfSymtab &Symtab = Reader->getSymtab();
2119       InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
2120                                          OS);
2121       continue;
2122     }
2123 
2124     assert(Func.Counts.size() > 0 && "function missing entry counter");
2125     Builder.addRecord(Func);
2126 
2127     uint64_t FuncMax = 0;
2128     uint64_t FuncSum = 0;
2129     for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
2130       if (Func.Counts[I] == (uint64_t)-1)
2131         continue;
2132       FuncMax = std::max(FuncMax, Func.Counts[I]);
2133       FuncSum += Func.Counts[I];
2134     }
2135 
2136     if (FuncMax < ValueCutoff) {
2137       ++BelowCutoffFunctions;
2138       if (OnlyListBelow) {
2139         OS << "  " << Func.Name << ": (Max = " << FuncMax
2140            << " Sum = " << FuncSum << ")\n";
2141       }
2142       continue;
2143     } else if (OnlyListBelow)
2144       continue;
2145 
2146     if (TopN) {
2147       if (HottestFuncs.size() == TopN) {
2148         if (HottestFuncs.top().second < FuncMax) {
2149           HottestFuncs.pop();
2150           HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
2151         }
2152       } else
2153         HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
2154     }
2155 
2156     if (Show) {
2157       if (!ShownFunctions)
2158         OS << "Counters:\n";
2159 
2160       ++ShownFunctions;
2161 
2162       OS << "  " << Func.Name << ":\n"
2163          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
2164          << "    Counters: " << Func.Counts.size() << "\n";
2165       if (!IsIRInstr)
2166         OS << "    Function count: " << Func.Counts[0] << "\n";
2167 
2168       if (ShowIndirectCallTargets)
2169         OS << "    Indirect Call Site Count: "
2170            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
2171 
2172       uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
2173       if (ShowMemOPSizes && NumMemOPCalls > 0)
2174         OS << "    Number of Memory Intrinsics Calls: " << NumMemOPCalls
2175            << "\n";
2176 
2177       if (ShowCounts) {
2178         OS << "    Block counts: [";
2179         size_t Start = (IsIRInstr ? 0 : 1);
2180         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
2181           OS << (I == Start ? "" : ", ") << Func.Counts[I];
2182         }
2183         OS << "]\n";
2184       }
2185 
2186       if (ShowIndirectCallTargets) {
2187         OS << "    Indirect Target Results:\n";
2188         traverseAllValueSites(Func, IPVK_IndirectCallTarget,
2189                               VPStats[IPVK_IndirectCallTarget], OS,
2190                               &(Reader->getSymtab()));
2191       }
2192 
2193       if (ShowMemOPSizes && NumMemOPCalls > 0) {
2194         OS << "    Memory Intrinsic Size Results:\n";
2195         traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
2196                               nullptr);
2197       }
2198     }
2199   }
2200   if (Reader->hasError())
2201     exitWithError(Reader->getError(), Filename);
2202 
2203   if (TextFormat)
2204     return 0;
2205   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
2206   bool IsIR = Reader->isIRLevelProfile();
2207   OS << "Instrumentation level: " << (IsIR ? "IR" : "Front-end");
2208   if (IsIR)
2209     OS << "  entry_first = " << Reader->instrEntryBBEnabled();
2210   OS << "\n";
2211   if (ShowAllFunctions || !ShowFunction.empty())
2212     OS << "Functions shown: " << ShownFunctions << "\n";
2213   OS << "Total functions: " << PS->getNumFunctions() << "\n";
2214   if (ValueCutoff > 0) {
2215     OS << "Number of functions with maximum count (< " << ValueCutoff
2216        << "): " << BelowCutoffFunctions << "\n";
2217     OS << "Number of functions with maximum count (>= " << ValueCutoff
2218        << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
2219   }
2220   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
2221   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
2222 
2223   if (TopN) {
2224     std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
2225     while (!HottestFuncs.empty()) {
2226       SortedHottestFuncs.emplace_back(HottestFuncs.top());
2227       HottestFuncs.pop();
2228     }
2229     OS << "Top " << TopN
2230        << " functions with the largest internal block counts: \n";
2231     for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
2232       OS << "  " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
2233   }
2234 
2235   if (ShownFunctions && ShowIndirectCallTargets) {
2236     OS << "Statistics for indirect call sites profile:\n";
2237     showValueSitesStats(OS, IPVK_IndirectCallTarget,
2238                         VPStats[IPVK_IndirectCallTarget]);
2239   }
2240 
2241   if (ShownFunctions && ShowMemOPSizes) {
2242     OS << "Statistics for memory intrinsic calls sizes profile:\n";
2243     showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
2244   }
2245 
2246   if (ShowDetailedSummary) {
2247     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
2248     OS << "Total count: " << PS->getTotalCount() << "\n";
2249     PS->printDetailedSummary(OS);
2250   }
2251 
2252   if (ShowBinaryIds)
2253     if (Error E = Reader->printBinaryIds(OS))
2254       exitWithError(std::move(E), Filename);
2255 
2256   return 0;
2257 }
2258 
2259 static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
2260                             raw_fd_ostream &OS) {
2261   if (!Reader->dumpSectionInfo(OS)) {
2262     WithColor::warning() << "-show-sec-info-only is only supported for "
2263                          << "sample profile in extbinary format and is "
2264                          << "ignored for other formats.\n";
2265     return;
2266   }
2267 }
2268 
2269 namespace {
2270 struct HotFuncInfo {
2271   std::string FuncName;
2272   uint64_t TotalCount;
2273   double TotalCountPercent;
2274   uint64_t MaxCount;
2275   uint64_t EntryCount;
2276 
2277   HotFuncInfo()
2278       : FuncName(), TotalCount(0), TotalCountPercent(0.0f), MaxCount(0),
2279         EntryCount(0) {}
2280 
2281   HotFuncInfo(StringRef FN, uint64_t TS, double TSP, uint64_t MS, uint64_t ES)
2282       : FuncName(FN.begin(), FN.end()), TotalCount(TS), TotalCountPercent(TSP),
2283         MaxCount(MS), EntryCount(ES) {}
2284 };
2285 } // namespace
2286 
2287 // Print out detailed information about hot functions in PrintValues vector.
2288 // Users specify titles and offset of every columns through ColumnTitle and
2289 // ColumnOffset. The size of ColumnTitle and ColumnOffset need to be the same
2290 // and at least 4. Besides, users can optionally give a HotFuncMetric string to
2291 // print out or let it be an empty string.
2292 static void dumpHotFunctionList(const std::vector<std::string> &ColumnTitle,
2293                                 const std::vector<int> &ColumnOffset,
2294                                 const std::vector<HotFuncInfo> &PrintValues,
2295                                 uint64_t HotFuncCount, uint64_t TotalFuncCount,
2296                                 uint64_t HotProfCount, uint64_t TotalProfCount,
2297                                 const std::string &HotFuncMetric,
2298                                 uint32_t TopNFunctions, raw_fd_ostream &OS) {
2299   assert(ColumnOffset.size() == ColumnTitle.size() &&
2300          "ColumnOffset and ColumnTitle should have the same size");
2301   assert(ColumnTitle.size() >= 4 &&
2302          "ColumnTitle should have at least 4 elements");
2303   assert(TotalFuncCount > 0 &&
2304          "There should be at least one function in the profile");
2305   double TotalProfPercent = 0;
2306   if (TotalProfCount > 0)
2307     TotalProfPercent = static_cast<double>(HotProfCount) / TotalProfCount * 100;
2308 
2309   formatted_raw_ostream FOS(OS);
2310   FOS << HotFuncCount << " out of " << TotalFuncCount
2311       << " functions with profile ("
2312       << format("%.2f%%",
2313                 (static_cast<double>(HotFuncCount) / TotalFuncCount * 100))
2314       << ") are considered hot functions";
2315   if (!HotFuncMetric.empty())
2316     FOS << " (" << HotFuncMetric << ")";
2317   FOS << ".\n";
2318   FOS << HotProfCount << " out of " << TotalProfCount << " profile counts ("
2319       << format("%.2f%%", TotalProfPercent) << ") are from hot functions.\n";
2320 
2321   for (size_t I = 0; I < ColumnTitle.size(); ++I) {
2322     FOS.PadToColumn(ColumnOffset[I]);
2323     FOS << ColumnTitle[I];
2324   }
2325   FOS << "\n";
2326 
2327   uint32_t Count = 0;
2328   for (const auto &R : PrintValues) {
2329     if (TopNFunctions && (Count++ == TopNFunctions))
2330       break;
2331     FOS.PadToColumn(ColumnOffset[0]);
2332     FOS << R.TotalCount << " (" << format("%.2f%%", R.TotalCountPercent) << ")";
2333     FOS.PadToColumn(ColumnOffset[1]);
2334     FOS << R.MaxCount;
2335     FOS.PadToColumn(ColumnOffset[2]);
2336     FOS << R.EntryCount;
2337     FOS.PadToColumn(ColumnOffset[3]);
2338     FOS << R.FuncName << "\n";
2339   }
2340 }
2341 
2342 static int showHotFunctionList(const sampleprof::SampleProfileMap &Profiles,
2343                                ProfileSummary &PS, uint32_t TopN,
2344                                raw_fd_ostream &OS) {
2345   using namespace sampleprof;
2346 
2347   const uint32_t HotFuncCutoff = 990000;
2348   auto &SummaryVector = PS.getDetailedSummary();
2349   uint64_t MinCountThreshold = 0;
2350   for (const ProfileSummaryEntry &SummaryEntry : SummaryVector) {
2351     if (SummaryEntry.Cutoff == HotFuncCutoff) {
2352       MinCountThreshold = SummaryEntry.MinCount;
2353       break;
2354     }
2355   }
2356 
2357   // Traverse all functions in the profile and keep only hot functions.
2358   // The following loop also calculates the sum of total samples of all
2359   // functions.
2360   std::multimap<uint64_t, std::pair<const FunctionSamples *, const uint64_t>,
2361                 std::greater<uint64_t>>
2362       HotFunc;
2363   uint64_t ProfileTotalSample = 0;
2364   uint64_t HotFuncSample = 0;
2365   uint64_t HotFuncCount = 0;
2366 
2367   for (const auto &I : Profiles) {
2368     FuncSampleStats FuncStats;
2369     const FunctionSamples &FuncProf = I.second;
2370     ProfileTotalSample += FuncProf.getTotalSamples();
2371     getFuncSampleStats(FuncProf, FuncStats, MinCountThreshold);
2372 
2373     if (isFunctionHot(FuncStats, MinCountThreshold)) {
2374       HotFunc.emplace(FuncProf.getTotalSamples(),
2375                       std::make_pair(&(I.second), FuncStats.MaxSample));
2376       HotFuncSample += FuncProf.getTotalSamples();
2377       ++HotFuncCount;
2378     }
2379   }
2380 
2381   std::vector<std::string> ColumnTitle{"Total sample (%)", "Max sample",
2382                                        "Entry sample", "Function name"};
2383   std::vector<int> ColumnOffset{0, 24, 42, 58};
2384   std::string Metric =
2385       std::string("max sample >= ") + std::to_string(MinCountThreshold);
2386   std::vector<HotFuncInfo> PrintValues;
2387   for (const auto &FuncPair : HotFunc) {
2388     const FunctionSamples &Func = *FuncPair.second.first;
2389     double TotalSamplePercent =
2390         (ProfileTotalSample > 0)
2391             ? (Func.getTotalSamples() * 100.0) / ProfileTotalSample
2392             : 0;
2393     PrintValues.emplace_back(HotFuncInfo(
2394         Func.getContext().toString(), Func.getTotalSamples(),
2395         TotalSamplePercent, FuncPair.second.second, Func.getEntrySamples()));
2396   }
2397   dumpHotFunctionList(ColumnTitle, ColumnOffset, PrintValues, HotFuncCount,
2398                       Profiles.size(), HotFuncSample, ProfileTotalSample,
2399                       Metric, TopN, OS);
2400 
2401   return 0;
2402 }
2403 
2404 static int showSampleProfile(const std::string &Filename, bool ShowCounts,
2405                              uint32_t TopN, bool ShowAllFunctions,
2406                              bool ShowDetailedSummary,
2407                              const std::string &ShowFunction,
2408                              bool ShowProfileSymbolList,
2409                              bool ShowSectionInfoOnly, bool ShowHotFuncList,
2410                              raw_fd_ostream &OS) {
2411   using namespace sampleprof;
2412   LLVMContext Context;
2413   auto ReaderOrErr =
2414       SampleProfileReader::create(Filename, Context, FSDiscriminatorPassOption);
2415   if (std::error_code EC = ReaderOrErr.getError())
2416     exitWithErrorCode(EC, Filename);
2417 
2418   auto Reader = std::move(ReaderOrErr.get());
2419   if (ShowSectionInfoOnly) {
2420     showSectionInfo(Reader.get(), OS);
2421     return 0;
2422   }
2423 
2424   if (std::error_code EC = Reader->read())
2425     exitWithErrorCode(EC, Filename);
2426 
2427   if (ShowAllFunctions || ShowFunction.empty())
2428     Reader->dump(OS);
2429   else
2430     // TODO: parse context string to support filtering by contexts.
2431     Reader->dumpFunctionProfile(StringRef(ShowFunction), OS);
2432 
2433   if (ShowProfileSymbolList) {
2434     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
2435         Reader->getProfileSymbolList();
2436     ReaderList->dump(OS);
2437   }
2438 
2439   if (ShowDetailedSummary) {
2440     auto &PS = Reader->getSummary();
2441     PS.printSummary(OS);
2442     PS.printDetailedSummary(OS);
2443   }
2444 
2445   if (ShowHotFuncList || TopN)
2446     showHotFunctionList(Reader->getProfiles(), Reader->getSummary(), TopN, OS);
2447 
2448   return 0;
2449 }
2450 
2451 static int showMemProfProfile(const std::string &Filename, raw_fd_ostream &OS) {
2452   auto ReaderOr = llvm::memprof::RawMemProfReader::create(Filename);
2453   if (Error E = ReaderOr.takeError())
2454     exitWithError(std::move(E), Filename);
2455 
2456   std::unique_ptr<llvm::memprof::RawMemProfReader> Reader(
2457       ReaderOr.get().release());
2458   Reader->printSummaries(OS);
2459   return 0;
2460 }
2461 
2462 static int show_main(int argc, const char *argv[]) {
2463   cl::opt<std::string> Filename(cl::Positional, cl::Required,
2464                                 cl::desc("<profdata-file>"));
2465 
2466   cl::opt<bool> ShowCounts("counts", cl::init(false),
2467                            cl::desc("Show counter values for shown functions"));
2468   cl::opt<bool> TextFormat(
2469       "text", cl::init(false),
2470       cl::desc("Show instr profile data in text dump format"));
2471   cl::opt<bool> ShowIndirectCallTargets(
2472       "ic-targets", cl::init(false),
2473       cl::desc("Show indirect call site target values for shown functions"));
2474   cl::opt<bool> ShowMemOPSizes(
2475       "memop-sizes", cl::init(false),
2476       cl::desc("Show the profiled sizes of the memory intrinsic calls "
2477                "for shown functions"));
2478   cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
2479                                     cl::desc("Show detailed profile summary"));
2480   cl::list<uint32_t> DetailedSummaryCutoffs(
2481       cl::CommaSeparated, "detailed-summary-cutoffs",
2482       cl::desc(
2483           "Cutoff percentages (times 10000) for generating detailed summary"),
2484       cl::value_desc("800000,901000,999999"));
2485   cl::opt<bool> ShowHotFuncList(
2486       "hot-func-list", cl::init(false),
2487       cl::desc("Show profile summary of a list of hot functions"));
2488   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
2489                                  cl::desc("Details for every function"));
2490   cl::opt<bool> ShowCS("showcs", cl::init(false),
2491                        cl::desc("Show context sensitive counts"));
2492   cl::opt<std::string> ShowFunction("function",
2493                                     cl::desc("Details for matching functions"));
2494 
2495   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
2496                                       cl::init("-"), cl::desc("Output file"));
2497   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
2498                             cl::aliasopt(OutputFilename));
2499   cl::opt<ProfileKinds> ProfileKind(
2500       cl::desc("Profile kind:"), cl::init(instr),
2501       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
2502                  clEnumVal(sample, "Sample profile"),
2503                  clEnumVal(memory, "MemProf memory access profile")));
2504   cl::opt<uint32_t> TopNFunctions(
2505       "topn", cl::init(0),
2506       cl::desc("Show the list of functions with the largest internal counts"));
2507   cl::opt<uint32_t> ValueCutoff(
2508       "value-cutoff", cl::init(0),
2509       cl::desc("Set the count value cutoff. Functions with the maximum count "
2510                "less than this value will not be printed out. (Default is 0)"));
2511   cl::opt<bool> OnlyListBelow(
2512       "list-below-cutoff", cl::init(false),
2513       cl::desc("Only output names of functions whose max count values are "
2514                "below the cutoff value"));
2515   cl::opt<bool> ShowProfileSymbolList(
2516       "show-prof-sym-list", cl::init(false),
2517       cl::desc("Show profile symbol list if it exists in the profile. "));
2518   cl::opt<bool> ShowSectionInfoOnly(
2519       "show-sec-info-only", cl::init(false),
2520       cl::desc("Show the information of each section in the sample profile. "
2521                "The flag is only usable when the sample profile is in "
2522                "extbinary format"));
2523   cl::opt<bool> ShowBinaryIds("binary-ids", cl::init(false),
2524                               cl::desc("Show binary ids in the profile. "));
2525 
2526   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
2527 
2528   if (Filename == OutputFilename) {
2529     errs() << sys::path::filename(argv[0])
2530            << ": Input file name cannot be the same as the output file name!\n";
2531     return 1;
2532   }
2533 
2534   std::error_code EC;
2535   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF);
2536   if (EC)
2537     exitWithErrorCode(EC, OutputFilename);
2538 
2539   if (ShowAllFunctions && !ShowFunction.empty())
2540     WithColor::warning() << "-function argument ignored: showing all functions\n";
2541 
2542   if (ProfileKind == instr)
2543     return showInstrProfile(
2544         Filename, ShowCounts, TopNFunctions, ShowIndirectCallTargets,
2545         ShowMemOPSizes, ShowDetailedSummary, DetailedSummaryCutoffs,
2546         ShowAllFunctions, ShowCS, ValueCutoff, OnlyListBelow, ShowFunction,
2547         TextFormat, ShowBinaryIds, OS);
2548   if (ProfileKind == sample)
2549     return showSampleProfile(Filename, ShowCounts, TopNFunctions,
2550                              ShowAllFunctions, ShowDetailedSummary,
2551                              ShowFunction, ShowProfileSymbolList,
2552                              ShowSectionInfoOnly, ShowHotFuncList, OS);
2553   return showMemProfProfile(Filename, OS);
2554 }
2555 
2556 int main(int argc, const char *argv[]) {
2557   InitLLVM X(argc, argv);
2558 
2559   StringRef ProgName(sys::path::filename(argv[0]));
2560   if (argc > 1) {
2561     int (*func)(int, const char *[]) = nullptr;
2562 
2563     if (strcmp(argv[1], "merge") == 0)
2564       func = merge_main;
2565     else if (strcmp(argv[1], "show") == 0)
2566       func = show_main;
2567     else if (strcmp(argv[1], "overlap") == 0)
2568       func = overlap_main;
2569 
2570     if (func) {
2571       std::string Invocation(ProgName.str() + " " + argv[1]);
2572       argv[1] = Invocation.c_str();
2573       return func(argc - 1, argv + 1);
2574     }
2575 
2576     if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
2577         strcmp(argv[1], "--help") == 0) {
2578 
2579       errs() << "OVERVIEW: LLVM profile data tools\n\n"
2580              << "USAGE: " << ProgName << " <command> [args...]\n"
2581              << "USAGE: " << ProgName << " <command> -help\n\n"
2582              << "See each individual command --help for more details.\n"
2583              << "Available commands: merge, show, overlap\n";
2584       return 0;
2585     }
2586   }
2587 
2588   if (argc < 2)
2589     errs() << ProgName << ": No command specified!\n";
2590   else
2591     errs() << ProgName << ": Unknown command!\n";
2592 
2593   errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
2594   return 1;
2595 }
2596