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