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