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