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