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