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