xref: /freebsd/contrib/llvm-project/llvm/tools/llvm-profdata/llvm-profdata.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
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/Object/Binary.h"
18 #include "llvm/ProfileData/InstrProfCorrelator.h"
19 #include "llvm/ProfileData/InstrProfReader.h"
20 #include "llvm/ProfileData/InstrProfWriter.h"
21 #include "llvm/ProfileData/MemProf.h"
22 #include "llvm/ProfileData/ProfileCommon.h"
23 #include "llvm/ProfileData/RawMemProfReader.h"
24 #include "llvm/ProfileData/SampleProfReader.h"
25 #include "llvm/ProfileData/SampleProfWriter.h"
26 #include "llvm/Support/BalancedPartitioning.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Discriminator.h"
29 #include "llvm/Support/Errc.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/InitLLVM.h"
34 #include "llvm/Support/LLVMDriver.h"
35 #include "llvm/Support/MD5.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/ThreadPool.h"
39 #include "llvm/Support/Threading.h"
40 #include "llvm/Support/VirtualFileSystem.h"
41 #include "llvm/Support/WithColor.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <algorithm>
44 #include <cmath>
45 #include <optional>
46 #include <queue>
47 
48 using namespace llvm;
49 using ProfCorrelatorKind = InstrProfCorrelator::ProfCorrelatorKind;
50 
51 // https://llvm.org/docs/CommandGuide/llvm-profdata.html has documentations
52 // on each subcommand.
53 cl::SubCommand ShowSubcommand(
54     "show",
55     "Takes a profile data file and displays the profiles. See detailed "
56     "documentation in "
57     "https://llvm.org/docs/CommandGuide/llvm-profdata.html#profdata-show");
58 cl::SubCommand OrderSubcommand(
59     "order",
60     "Reads temporal profiling traces from a profile and outputs a function "
61     "order that reduces the number of page faults for those traces. See "
62     "detailed documentation in "
63     "https://llvm.org/docs/CommandGuide/llvm-profdata.html#profdata-order");
64 cl::SubCommand OverlapSubcommand(
65     "overlap",
66     "Computes and displays the overlap between two profiles. See detailed "
67     "documentation in "
68     "https://llvm.org/docs/CommandGuide/llvm-profdata.html#profdata-overlap");
69 cl::SubCommand MergeSubcommand(
70     "merge",
71     "Takes several profiles and merge them together. See detailed "
72     "documentation in "
73     "https://llvm.org/docs/CommandGuide/llvm-profdata.html#profdata-merge");
74 
75 namespace {
76 enum ProfileKinds { instr, sample, memory };
77 enum FailureMode { warnOnly, failIfAnyAreInvalid, failIfAllAreInvalid };
78 } // namespace
79 
80 enum ProfileFormat {
81   PF_None = 0,
82   PF_Text,
83   PF_Compact_Binary, // Deprecated
84   PF_Ext_Binary,
85   PF_GCC,
86   PF_Binary
87 };
88 
89 enum class ShowFormat { Text, Json, Yaml };
90 
91 // Common options.
92 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
93                                     cl::init("-"), cl::desc("Output file"),
94                                     cl::sub(ShowSubcommand),
95                                     cl::sub(OrderSubcommand),
96                                     cl::sub(OverlapSubcommand),
97                                     cl::sub(MergeSubcommand));
98 // NOTE: cl::alias must not have cl::sub(), since aliased option's cl::sub()
99 // will be used. llvm::cl::alias::done() method asserts this condition.
100 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
101                           cl::aliasopt(OutputFilename));
102 
103 // Options common to at least two commands.
104 cl::opt<ProfileKinds> ProfileKind(
105     cl::desc("Profile kind:"), cl::sub(MergeSubcommand),
106     cl::sub(OverlapSubcommand), cl::init(instr),
107     cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
108                clEnumVal(sample, "Sample profile")));
109 cl::opt<std::string> Filename(cl::Positional, cl::desc("<profdata-file>"),
110                               cl::sub(ShowSubcommand),
111                               cl::sub(OrderSubcommand));
112 cl::opt<unsigned> MaxDbgCorrelationWarnings(
113     "max-debug-info-correlation-warnings",
114     cl::desc("The maximum number of warnings to emit when correlating "
115              "profile from debug info (0 = no limit)"),
116     cl::sub(MergeSubcommand), cl::sub(ShowSubcommand), cl::init(5));
117 cl::opt<std::string> ProfiledBinary(
118     "profiled-binary", cl::init(""),
119     cl::desc("Path to binary from which the profile was collected."),
120     cl::sub(ShowSubcommand), cl::sub(MergeSubcommand));
121 cl::opt<std::string> DebugInfoFilename(
122     "debug-info", cl::init(""),
123     cl::desc(
124         "For show, read and extract profile metadata from debug info and show "
125         "the functions it found. For merge, use the provided debug info to "
126         "correlate the raw profile."),
127     cl::sub(ShowSubcommand), cl::sub(MergeSubcommand));
128 cl::opt<std::string>
129     BinaryFilename("binary-file", cl::init(""),
130                    cl::desc("For merge, use the provided unstripped bianry to "
131                             "correlate the raw profile."),
132                    cl::sub(MergeSubcommand));
133 cl::opt<std::string> FuncNameFilter(
134     "function",
135     cl::desc("Details for matching functions. For overlapping CSSPGO, this "
136              "takes a function name with calling context."),
137     cl::sub(ShowSubcommand), cl::sub(OverlapSubcommand));
138 
139 // TODO: Consider creating a template class (e.g., MergeOption, ShowOption) to
140 // factor out the common cl::sub in cl::opt constructor for subcommand-specific
141 // options.
142 
143 // Options specific to merge subcommand.
144 cl::list<std::string> InputFilenames(cl::Positional, cl::sub(MergeSubcommand),
145                                      cl::desc("<filename...>"));
146 cl::list<std::string> WeightedInputFilenames("weighted-input",
147                                              cl::sub(MergeSubcommand),
148                                              cl::desc("<weight>,<filename>"));
149 cl::opt<ProfileFormat> OutputFormat(
150     cl::desc("Format of output profile"), cl::sub(MergeSubcommand),
151     cl::init(PF_Ext_Binary),
152     cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding"),
153                clEnumValN(PF_Ext_Binary, "extbinary",
154                           "Extensible binary encoding "
155                           "(default)"),
156                clEnumValN(PF_Text, "text", "Text encoding"),
157                clEnumValN(PF_GCC, "gcc",
158                           "GCC encoding (only meaningful for -sample)")));
159 cl::opt<std::string>
160     InputFilenamesFile("input-files", cl::init(""), cl::sub(MergeSubcommand),
161                        cl::desc("Path to file containing newline-separated "
162                                 "[<weight>,]<filename> entries"));
163 cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
164                               cl::aliasopt(InputFilenamesFile));
165 cl::opt<bool> DumpInputFileList(
166     "dump-input-file-list", cl::init(false), cl::Hidden,
167     cl::sub(MergeSubcommand),
168     cl::desc("Dump the list of input files and their weights, then exit"));
169 cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
170                                    cl::sub(MergeSubcommand),
171                                    cl::desc("Symbol remapping file"));
172 cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
173                          cl::aliasopt(RemappingFile));
174 cl::opt<bool>
175     UseMD5("use-md5", cl::init(false), cl::Hidden,
176            cl::desc("Choose to use MD5 to represent string in name table (only "
177                     "meaningful for -extbinary)"),
178            cl::sub(MergeSubcommand));
179 cl::opt<bool> CompressAllSections(
180     "compress-all-sections", cl::init(false), cl::Hidden,
181     cl::sub(MergeSubcommand),
182     cl::desc("Compress all sections when writing the profile (only "
183              "meaningful for -extbinary)"));
184 cl::opt<bool> SampleMergeColdContext(
185     "sample-merge-cold-context", cl::init(false), cl::Hidden,
186     cl::sub(MergeSubcommand),
187     cl::desc(
188         "Merge context sample profiles whose count is below cold threshold"));
189 cl::opt<bool> SampleTrimColdContext(
190     "sample-trim-cold-context", cl::init(false), cl::Hidden,
191     cl::sub(MergeSubcommand),
192     cl::desc(
193         "Trim context sample profiles whose count is below cold threshold"));
194 cl::opt<uint32_t> SampleColdContextFrameDepth(
195     "sample-frame-depth-for-cold-context", cl::init(1),
196     cl::sub(MergeSubcommand),
197     cl::desc("Keep the last K frames while merging cold profile. 1 means the "
198              "context-less base profile"));
199 cl::opt<size_t> OutputSizeLimit(
200     "output-size-limit", cl::init(0), cl::Hidden, cl::sub(MergeSubcommand),
201     cl::desc("Trim cold functions until profile size is below specified "
202              "limit in bytes. This uses a heursitic and functions may be "
203              "excessively trimmed"));
204 cl::opt<bool> GenPartialProfile(
205     "gen-partial-profile", cl::init(false), cl::Hidden,
206     cl::sub(MergeSubcommand),
207     cl::desc("Generate a partial profile (only meaningful for -extbinary)"));
208 cl::opt<std::string> SupplInstrWithSample(
209     "supplement-instr-with-sample", cl::init(""), cl::Hidden,
210     cl::sub(MergeSubcommand),
211     cl::desc("Supplement an instr profile with sample profile, to correct "
212              "the profile unrepresentativeness issue. The sample "
213              "profile is the input of the flag. Output will be in instr "
214              "format (The flag only works with -instr)"));
215 cl::opt<float> ZeroCounterThreshold(
216     "zero-counter-threshold", cl::init(0.7), cl::Hidden,
217     cl::sub(MergeSubcommand),
218     cl::desc("For the function which is cold in instr profile but hot in "
219              "sample profile, if the ratio of the number of zero counters "
220              "divided by the total number of counters is above the "
221              "threshold, the profile of the function will be regarded as "
222              "being harmful for performance and will be dropped."));
223 cl::opt<unsigned> SupplMinSizeThreshold(
224     "suppl-min-size-threshold", cl::init(10), cl::Hidden,
225     cl::sub(MergeSubcommand),
226     cl::desc("If the size of a function is smaller than the threshold, "
227              "assume it can be inlined by PGO early inliner and it won't "
228              "be adjusted based on sample profile."));
229 cl::opt<unsigned> InstrProfColdThreshold(
230     "instr-prof-cold-threshold", cl::init(0), cl::Hidden,
231     cl::sub(MergeSubcommand),
232     cl::desc("User specified cold threshold for instr profile which will "
233              "override the cold threshold got from profile summary. "));
234 // WARNING: This reservoir size value is propagated to any input indexed
235 // profiles for simplicity. Changing this value between invocations could
236 // result in sample bias.
237 cl::opt<uint64_t> TemporalProfTraceReservoirSize(
238     "temporal-profile-trace-reservoir-size", cl::init(100),
239     cl::sub(MergeSubcommand),
240     cl::desc("The maximum number of stored temporal profile traces (default: "
241              "100)"));
242 cl::opt<uint64_t> TemporalProfMaxTraceLength(
243     "temporal-profile-max-trace-length", cl::init(10000),
244     cl::sub(MergeSubcommand),
245     cl::desc("The maximum length of a single temporal profile trace "
246              "(default: 10000)"));
247 
248 cl::opt<FailureMode>
249     FailMode("failure-mode", cl::init(failIfAnyAreInvalid),
250              cl::desc("Failure mode:"), cl::sub(MergeSubcommand),
251              cl::values(clEnumValN(warnOnly, "warn",
252                                    "Do not fail and just print warnings."),
253                         clEnumValN(failIfAnyAreInvalid, "any",
254                                    "Fail if any profile is invalid."),
255                         clEnumValN(failIfAllAreInvalid, "all",
256                                    "Fail only if all profiles are invalid.")));
257 
258 cl::opt<bool> OutputSparse(
259     "sparse", cl::init(false), cl::sub(MergeSubcommand),
260     cl::desc("Generate a sparse profile (only meaningful for -instr)"));
261 cl::opt<unsigned> NumThreads(
262     "num-threads", cl::init(0), cl::sub(MergeSubcommand),
263     cl::desc("Number of merge threads to use (default: autodetect)"));
264 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
265                       cl::aliasopt(NumThreads));
266 
267 cl::opt<std::string> ProfileSymbolListFile(
268     "prof-sym-list", cl::init(""), cl::sub(MergeSubcommand),
269     cl::desc("Path to file containing the list of function symbols "
270              "used to populate profile symbol list"));
271 
272 cl::opt<SampleProfileLayout> ProfileLayout(
273     "convert-sample-profile-layout",
274     cl::desc("Convert the generated profile to a profile with a new layout"),
275     cl::sub(MergeSubcommand), cl::init(SPL_None),
276     cl::values(
277         clEnumValN(SPL_Nest, "nest",
278                    "Nested profile, the input should be CS flat profile"),
279         clEnumValN(SPL_Flat, "flat",
280                    "Profile with nested inlinee flatten out")));
281 
282 cl::opt<bool> DropProfileSymbolList(
283     "drop-profile-symbol-list", cl::init(false), cl::Hidden,
284     cl::sub(MergeSubcommand),
285     cl::desc("Drop the profile symbol list when merging AutoFDO profiles "
286              "(only meaningful for -sample)"));
287 
288 // Options specific to overlap subcommand.
289 cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
290                                   cl::desc("<base profile file>"),
291                                   cl::sub(OverlapSubcommand));
292 cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
293                                   cl::desc("<test profile file>"),
294                                   cl::sub(OverlapSubcommand));
295 
296 cl::opt<unsigned long long> SimilarityCutoff(
297     "similarity-cutoff", cl::init(0),
298     cl::desc("For sample profiles, list function names (with calling context "
299              "for csspgo) for overlapped functions "
300              "with similarities below the cutoff (percentage times 10000)."),
301     cl::sub(OverlapSubcommand));
302 
303 cl::opt<bool> IsCS(
304     "cs", cl::init(false),
305     cl::desc("For context sensitive PGO counts. Does not work with CSSPGO."),
306     cl::sub(OverlapSubcommand));
307 
308 cl::opt<unsigned long long> OverlapValueCutoff(
309     "value-cutoff", cl::init(-1),
310     cl::desc(
311         "Function level overlap information for every function (with calling "
312         "context for csspgo) in test "
313         "profile with max count value greater then the parameter value"),
314     cl::sub(OverlapSubcommand));
315 
316 // Options unique to show subcommand.
317 cl::opt<bool> ShowCounts("counts", cl::init(false),
318                          cl::desc("Show counter values for shown functions"),
319                          cl::sub(ShowSubcommand));
320 cl::opt<ShowFormat>
321     SFormat("show-format", cl::init(ShowFormat::Text),
322             cl::desc("Emit output in the selected format if supported"),
323             cl::sub(ShowSubcommand),
324             cl::values(clEnumValN(ShowFormat::Text, "text",
325                                   "emit normal text output (default)"),
326                        clEnumValN(ShowFormat::Json, "json", "emit JSON"),
327                        clEnumValN(ShowFormat::Yaml, "yaml", "emit YAML")));
328 // TODO: Consider replacing this with `--show-format=text-encoding`.
329 cl::opt<bool>
330     TextFormat("text", cl::init(false),
331                cl::desc("Show instr profile data in text dump format"),
332                cl::sub(ShowSubcommand));
333 cl::opt<bool>
334     JsonFormat("json",
335                cl::desc("Show sample profile data in the JSON format "
336                         "(deprecated, please use --show-format=json)"),
337                cl::sub(ShowSubcommand));
338 cl::opt<bool> ShowIndirectCallTargets(
339     "ic-targets", cl::init(false),
340     cl::desc("Show indirect call site target values for shown functions"),
341     cl::sub(ShowSubcommand));
342 cl::opt<bool> ShowMemOPSizes(
343     "memop-sizes", cl::init(false),
344     cl::desc("Show the profiled sizes of the memory intrinsic calls "
345              "for shown functions"),
346     cl::sub(ShowSubcommand));
347 cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
348                                   cl::desc("Show detailed profile summary"),
349                                   cl::sub(ShowSubcommand));
350 cl::list<uint32_t> DetailedSummaryCutoffs(
351     cl::CommaSeparated, "detailed-summary-cutoffs",
352     cl::desc(
353         "Cutoff percentages (times 10000) for generating detailed summary"),
354     cl::value_desc("800000,901000,999999"), cl::sub(ShowSubcommand));
355 cl::opt<bool>
356     ShowHotFuncList("hot-func-list", cl::init(false),
357                     cl::desc("Show profile summary of a list of hot functions"),
358                     cl::sub(ShowSubcommand));
359 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
360                                cl::desc("Details for each and every function"),
361                                cl::sub(ShowSubcommand));
362 cl::opt<bool> ShowCS("showcs", cl::init(false),
363                      cl::desc("Show context sensitive counts"),
364                      cl::sub(ShowSubcommand));
365 cl::opt<ProfileKinds> ShowProfileKind(
366     cl::desc("Profile kind supported by show:"), cl::sub(ShowSubcommand),
367     cl::init(instr),
368     cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
369                clEnumVal(sample, "Sample profile"),
370                clEnumVal(memory, "MemProf memory access profile")));
371 cl::opt<uint32_t> TopNFunctions(
372     "topn", cl::init(0),
373     cl::desc("Show the list of functions with the largest internal counts"),
374     cl::sub(ShowSubcommand));
375 cl::opt<uint32_t> ShowValueCutoff(
376     "value-cutoff", cl::init(0),
377     cl::desc("Set the count value cutoff. Functions with the maximum count "
378              "less than this value will not be printed out. (Default is 0)"),
379     cl::sub(ShowSubcommand));
380 cl::opt<bool> OnlyListBelow(
381     "list-below-cutoff", cl::init(false),
382     cl::desc("Only output names of functions whose max count values are "
383              "below the cutoff value"),
384     cl::sub(ShowSubcommand));
385 cl::opt<bool> ShowProfileSymbolList(
386     "show-prof-sym-list", cl::init(false),
387     cl::desc("Show profile symbol list if it exists in the profile. "),
388     cl::sub(ShowSubcommand));
389 cl::opt<bool> ShowSectionInfoOnly(
390     "show-sec-info-only", cl::init(false),
391     cl::desc("Show the information of each section in the sample profile. "
392              "The flag is only usable when the sample profile is in "
393              "extbinary format"),
394     cl::sub(ShowSubcommand));
395 cl::opt<bool> ShowBinaryIds("binary-ids", cl::init(false),
396                             cl::desc("Show binary ids in the profile. "),
397                             cl::sub(ShowSubcommand));
398 cl::opt<bool> ShowTemporalProfTraces(
399     "temporal-profile-traces",
400     cl::desc("Show temporal profile traces in the profile."),
401     cl::sub(ShowSubcommand));
402 
403 cl::opt<bool>
404     ShowCovered("covered", cl::init(false),
405                 cl::desc("Show only the functions that have been executed."),
406                 cl::sub(ShowSubcommand));
407 
408 cl::opt<bool> ShowProfileVersion("profile-version", cl::init(false),
409                                  cl::desc("Show profile version. "),
410                                  cl::sub(ShowSubcommand));
411 
412 // We use this string to indicate that there are
413 // multiple static functions map to the same name.
414 const std::string DuplicateNameStr = "----";
415 
416 static void warn(Twine Message, std::string Whence = "",
417                  std::string Hint = "") {
418   WithColor::warning();
419   if (!Whence.empty())
420     errs() << Whence << ": ";
421   errs() << Message << "\n";
422   if (!Hint.empty())
423     WithColor::note() << Hint << "\n";
424 }
425 
426 static void warn(Error E, StringRef Whence = "") {
427   if (E.isA<InstrProfError>()) {
428     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
429       warn(IPE.message(), std::string(Whence), std::string(""));
430     });
431   }
432 }
433 
434 static void exitWithError(Twine Message, std::string Whence = "",
435                           std::string Hint = "") {
436   WithColor::error();
437   if (!Whence.empty())
438     errs() << Whence << ": ";
439   errs() << Message << "\n";
440   if (!Hint.empty())
441     WithColor::note() << Hint << "\n";
442   ::exit(1);
443 }
444 
445 static void exitWithError(Error E, StringRef Whence = "") {
446   if (E.isA<InstrProfError>()) {
447     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
448       instrprof_error instrError = IPE.get();
449       StringRef Hint = "";
450       if (instrError == instrprof_error::unrecognized_format) {
451         // Hint in case user missed specifying the profile type.
452         Hint = "Perhaps you forgot to use the --sample or --memory option?";
453       }
454       exitWithError(IPE.message(), std::string(Whence), std::string(Hint));
455     });
456     return;
457   }
458 
459   exitWithError(toString(std::move(E)), std::string(Whence));
460 }
461 
462 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
463   exitWithError(EC.message(), std::string(Whence));
464 }
465 
466 static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
467                                  StringRef Whence = "") {
468   if (FailMode == failIfAnyAreInvalid)
469     exitWithErrorCode(EC, Whence);
470   else
471     warn(EC.message(), std::string(Whence));
472 }
473 
474 static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
475                                    StringRef WhenceFunction = "",
476                                    bool ShowHint = true) {
477   if (!WhenceFile.empty())
478     errs() << WhenceFile << ": ";
479   if (!WhenceFunction.empty())
480     errs() << WhenceFunction << ": ";
481 
482   auto IPE = instrprof_error::success;
483   E = handleErrors(std::move(E),
484                    [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
485                      IPE = E->get();
486                      return Error(std::move(E));
487                    });
488   errs() << toString(std::move(E)) << "\n";
489 
490   if (ShowHint) {
491     StringRef Hint = "";
492     if (IPE != instrprof_error::success) {
493       switch (IPE) {
494       case instrprof_error::hash_mismatch:
495       case instrprof_error::count_mismatch:
496       case instrprof_error::value_site_count_mismatch:
497         Hint = "Make sure that all profile data to be merged is generated "
498                "from the same binary.";
499         break;
500       default:
501         break;
502       }
503     }
504 
505     if (!Hint.empty())
506       errs() << Hint << "\n";
507   }
508 }
509 
510 namespace {
511 /// A remapper from original symbol names to new symbol names based on a file
512 /// containing a list of mappings from old name to new name.
513 class SymbolRemapper {
514   std::unique_ptr<MemoryBuffer> File;
515   DenseMap<StringRef, StringRef> RemappingTable;
516 
517 public:
518   /// Build a SymbolRemapper from a file containing a list of old/new symbols.
519   static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
520     auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
521     if (!BufOrError)
522       exitWithErrorCode(BufOrError.getError(), InputFile);
523 
524     auto Remapper = std::make_unique<SymbolRemapper>();
525     Remapper->File = std::move(BufOrError.get());
526 
527     for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
528          !LineIt.is_at_eof(); ++LineIt) {
529       std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
530       if (Parts.first.empty() || Parts.second.empty() ||
531           Parts.second.count(' ')) {
532         exitWithError("unexpected line in remapping file",
533                       (InputFile + ":" + Twine(LineIt.line_number())).str(),
534                       "expected 'old_symbol new_symbol'");
535       }
536       Remapper->RemappingTable.insert(Parts);
537     }
538     return Remapper;
539   }
540 
541   /// Attempt to map the given old symbol into a new symbol.
542   ///
543   /// \return The new symbol, or \p Name if no such symbol was found.
544   StringRef operator()(StringRef Name) {
545     StringRef New = RemappingTable.lookup(Name);
546     return New.empty() ? Name : New;
547   }
548 
549   FunctionId operator()(FunctionId Name) {
550     // MD5 name cannot be remapped.
551     if (!Name.isStringRef())
552       return Name;
553     StringRef New = RemappingTable.lookup(Name.stringRef());
554     return New.empty() ? Name : FunctionId(New);
555   }
556 };
557 }
558 
559 struct WeightedFile {
560   std::string Filename;
561   uint64_t Weight;
562 };
563 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
564 
565 /// Keep track of merged data and reported errors.
566 struct WriterContext {
567   std::mutex Lock;
568   InstrProfWriter Writer;
569   std::vector<std::pair<Error, std::string>> Errors;
570   std::mutex &ErrLock;
571   SmallSet<instrprof_error, 4> &WriterErrorCodes;
572 
573   WriterContext(bool IsSparse, std::mutex &ErrLock,
574                 SmallSet<instrprof_error, 4> &WriterErrorCodes,
575                 uint64_t ReservoirSize = 0, uint64_t MaxTraceLength = 0)
576       : Writer(IsSparse, ReservoirSize, MaxTraceLength), ErrLock(ErrLock),
577         WriterErrorCodes(WriterErrorCodes) {}
578 };
579 
580 /// Computer the overlap b/w profile BaseFilename and TestFileName,
581 /// and store the program level result to Overlap.
582 static void overlapInput(const std::string &BaseFilename,
583                          const std::string &TestFilename, WriterContext *WC,
584                          OverlapStats &Overlap,
585                          const OverlapFuncFilters &FuncFilter,
586                          raw_fd_ostream &OS, bool IsCS) {
587   auto FS = vfs::getRealFileSystem();
588   auto ReaderOrErr = InstrProfReader::create(TestFilename, *FS);
589   if (Error E = ReaderOrErr.takeError()) {
590     // Skip the empty profiles by returning sliently.
591     auto [ErrorCode, Msg] = InstrProfError::take(std::move(E));
592     if (ErrorCode != instrprof_error::empty_raw_profile)
593       WC->Errors.emplace_back(make_error<InstrProfError>(ErrorCode, Msg),
594                               TestFilename);
595     return;
596   }
597 
598   auto Reader = std::move(ReaderOrErr.get());
599   for (auto &I : *Reader) {
600     OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
601     FuncOverlap.setFuncInfo(I.Name, I.Hash);
602 
603     WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
604     FuncOverlap.dump(OS);
605   }
606 }
607 
608 /// Load an input into a writer context.
609 static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
610                       const InstrProfCorrelator *Correlator,
611                       const StringRef ProfiledBinary, WriterContext *WC) {
612   std::unique_lock<std::mutex> CtxGuard{WC->Lock};
613 
614   // Copy the filename, because llvm::ThreadPool copied the input "const
615   // WeightedFile &" by value, making a reference to the filename within it
616   // invalid outside of this packaged task.
617   std::string Filename = Input.Filename;
618 
619   using ::llvm::memprof::RawMemProfReader;
620   if (RawMemProfReader::hasFormat(Input.Filename)) {
621     auto ReaderOrErr = RawMemProfReader::create(Input.Filename, ProfiledBinary);
622     if (!ReaderOrErr) {
623       exitWithError(ReaderOrErr.takeError(), Input.Filename);
624     }
625     std::unique_ptr<RawMemProfReader> Reader = std::move(ReaderOrErr.get());
626     // Check if the profile types can be merged, e.g. clang frontend profiles
627     // should not be merged with memprof profiles.
628     if (Error E = WC->Writer.mergeProfileKind(Reader->getProfileKind())) {
629       consumeError(std::move(E));
630       WC->Errors.emplace_back(
631           make_error<StringError>(
632               "Cannot merge MemProf profile with Clang generated profile.",
633               std::error_code()),
634           Filename);
635       return;
636     }
637 
638     auto MemProfError = [&](Error E) {
639       auto [ErrorCode, Msg] = InstrProfError::take(std::move(E));
640       WC->Errors.emplace_back(make_error<InstrProfError>(ErrorCode, Msg),
641                               Filename);
642     };
643 
644     // Add the frame mappings into the writer context.
645     const auto &IdToFrame = Reader->getFrameMapping();
646     for (const auto &I : IdToFrame) {
647       bool Succeeded = WC->Writer.addMemProfFrame(
648           /*Id=*/I.first, /*Frame=*/I.getSecond(), MemProfError);
649       // If we weren't able to add the frame mappings then it doesn't make sense
650       // to try to add the records from this profile.
651       if (!Succeeded)
652         return;
653     }
654     const auto &FunctionProfileData = Reader->getProfileData();
655     // Add the memprof records into the writer context.
656     for (const auto &I : FunctionProfileData) {
657       WC->Writer.addMemProfRecord(/*Id=*/I.first, /*Record=*/I.second);
658     }
659     return;
660   }
661 
662   auto FS = vfs::getRealFileSystem();
663   // TODO: This only saves the first non-fatal error from InstrProfReader, and
664   // then added to WriterContext::Errors. However, this is not extensible, if
665   // we have more non-fatal errors from InstrProfReader in the future. How
666   // should this interact with different -failure-mode?
667   std::optional<std::pair<Error, std::string>> ReaderWarning;
668   auto Warn = [&](Error E) {
669     if (ReaderWarning) {
670       consumeError(std::move(E));
671       return;
672     }
673     // Only show the first time an error occurs in this file.
674     auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
675     ReaderWarning = {make_error<InstrProfError>(ErrCode, Msg), Filename};
676   };
677   auto ReaderOrErr =
678       InstrProfReader::create(Input.Filename, *FS, Correlator, Warn);
679   if (Error E = ReaderOrErr.takeError()) {
680     // Skip the empty profiles by returning silently.
681     auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
682     if (ErrCode != instrprof_error::empty_raw_profile)
683       WC->Errors.emplace_back(make_error<InstrProfError>(ErrCode, Msg),
684                               Filename);
685     return;
686   }
687 
688   auto Reader = std::move(ReaderOrErr.get());
689   if (Error E = WC->Writer.mergeProfileKind(Reader->getProfileKind())) {
690     consumeError(std::move(E));
691     WC->Errors.emplace_back(
692         make_error<StringError>(
693             "Merge IR generated profile with Clang generated profile.",
694             std::error_code()),
695         Filename);
696     return;
697   }
698 
699   for (auto &I : *Reader) {
700     if (Remapper)
701       I.Name = (*Remapper)(I.Name);
702     const StringRef FuncName = I.Name;
703     bool Reported = false;
704     WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
705       if (Reported) {
706         consumeError(std::move(E));
707         return;
708       }
709       Reported = true;
710       // Only show hint the first time an error occurs.
711       auto [ErrCode, Msg] = InstrProfError::take(std::move(E));
712       std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
713       bool firstTime = WC->WriterErrorCodes.insert(ErrCode).second;
714       handleMergeWriterError(make_error<InstrProfError>(ErrCode, Msg),
715                              Input.Filename, FuncName, firstTime);
716     });
717   }
718 
719   if (Reader->hasTemporalProfile()) {
720     auto &Traces = Reader->getTemporalProfTraces(Input.Weight);
721     if (!Traces.empty())
722       WC->Writer.addTemporalProfileTraces(
723           Traces, Reader->getTemporalProfTraceStreamSize());
724   }
725   if (Reader->hasError()) {
726     if (Error E = Reader->getError()) {
727       WC->Errors.emplace_back(std::move(E), Filename);
728       return;
729     }
730   }
731 
732   std::vector<llvm::object::BuildID> BinaryIds;
733   if (Error E = Reader->readBinaryIds(BinaryIds)) {
734     WC->Errors.emplace_back(std::move(E), Filename);
735     return;
736   }
737   WC->Writer.addBinaryIds(BinaryIds);
738 
739   if (ReaderWarning) {
740     WC->Errors.emplace_back(std::move(ReaderWarning->first),
741                             ReaderWarning->second);
742   }
743 }
744 
745 /// Merge the \p Src writer context into \p Dst.
746 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
747   for (auto &ErrorPair : Src->Errors)
748     Dst->Errors.push_back(std::move(ErrorPair));
749   Src->Errors.clear();
750 
751   if (Error E = Dst->Writer.mergeProfileKind(Src->Writer.getProfileKind()))
752     exitWithError(std::move(E));
753 
754   Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
755     auto [ErrorCode, Msg] = InstrProfError::take(std::move(E));
756     std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
757     bool firstTime = Dst->WriterErrorCodes.insert(ErrorCode).second;
758     if (firstTime)
759       warn(toString(make_error<InstrProfError>(ErrorCode, Msg)));
760   });
761 }
762 
763 static void writeInstrProfile(StringRef OutputFilename,
764                               ProfileFormat OutputFormat,
765                               InstrProfWriter &Writer) {
766   std::error_code EC;
767   raw_fd_ostream Output(OutputFilename.data(), EC,
768                         OutputFormat == PF_Text ? sys::fs::OF_TextWithCRLF
769                                                 : sys::fs::OF_None);
770   if (EC)
771     exitWithErrorCode(EC, OutputFilename);
772 
773   if (OutputFormat == PF_Text) {
774     if (Error E = Writer.writeText(Output))
775       warn(std::move(E));
776   } else {
777     if (Output.is_displayed())
778       exitWithError("cannot write a non-text format profile to the terminal");
779     if (Error E = Writer.write(Output))
780       warn(std::move(E));
781   }
782 }
783 
784 static void mergeInstrProfile(const WeightedFileVector &Inputs,
785                               SymbolRemapper *Remapper,
786                               int MaxDbgCorrelationWarnings,
787                               const StringRef ProfiledBinary) {
788   const uint64_t TraceReservoirSize = TemporalProfTraceReservoirSize.getValue();
789   const uint64_t MaxTraceLength = TemporalProfMaxTraceLength.getValue();
790   if (OutputFormat == PF_Compact_Binary)
791     exitWithError("Compact Binary is deprecated");
792   if (OutputFormat != PF_Binary && OutputFormat != PF_Ext_Binary &&
793       OutputFormat != PF_Text)
794     exitWithError("unknown format is specified");
795 
796   // TODO: Maybe we should support correlation with mixture of different
797   // correlation modes(w/wo debug-info/object correlation).
798   if (!DebugInfoFilename.empty() && !BinaryFilename.empty())
799     exitWithError("Expected only one of -debug-info, -binary-file");
800   std::string CorrelateFilename;
801   ProfCorrelatorKind CorrelateKind = ProfCorrelatorKind::NONE;
802   if (!DebugInfoFilename.empty()) {
803     CorrelateFilename = DebugInfoFilename;
804     CorrelateKind = ProfCorrelatorKind::DEBUG_INFO;
805   } else if (!BinaryFilename.empty()) {
806     CorrelateFilename = BinaryFilename;
807     CorrelateKind = ProfCorrelatorKind::BINARY;
808   }
809 
810   std::unique_ptr<InstrProfCorrelator> Correlator;
811   if (CorrelateKind != InstrProfCorrelator::NONE) {
812     if (auto Err = InstrProfCorrelator::get(CorrelateFilename, CorrelateKind)
813                        .moveInto(Correlator))
814       exitWithError(std::move(Err), CorrelateFilename);
815     if (auto Err = Correlator->correlateProfileData(MaxDbgCorrelationWarnings))
816       exitWithError(std::move(Err), CorrelateFilename);
817   }
818 
819   std::mutex ErrorLock;
820   SmallSet<instrprof_error, 4> WriterErrorCodes;
821 
822   // If NumThreads is not specified, auto-detect a good default.
823   if (NumThreads == 0)
824     NumThreads = std::min(hardware_concurrency().compute_thread_count(),
825                           unsigned((Inputs.size() + 1) / 2));
826 
827   // Initialize the writer contexts.
828   SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
829   for (unsigned I = 0; I < NumThreads; ++I)
830     Contexts.emplace_back(std::make_unique<WriterContext>(
831         OutputSparse, ErrorLock, WriterErrorCodes, TraceReservoirSize,
832         MaxTraceLength));
833 
834   if (NumThreads == 1) {
835     for (const auto &Input : Inputs)
836       loadInput(Input, Remapper, Correlator.get(), ProfiledBinary,
837                 Contexts[0].get());
838   } else {
839     ThreadPool Pool(hardware_concurrency(NumThreads));
840 
841     // Load the inputs in parallel (N/NumThreads serial steps).
842     unsigned Ctx = 0;
843     for (const auto &Input : Inputs) {
844       Pool.async(loadInput, Input, Remapper, Correlator.get(), ProfiledBinary,
845                  Contexts[Ctx].get());
846       Ctx = (Ctx + 1) % NumThreads;
847     }
848     Pool.wait();
849 
850     // Merge the writer contexts together (~ lg(NumThreads) serial steps).
851     unsigned Mid = Contexts.size() / 2;
852     unsigned End = Contexts.size();
853     assert(Mid > 0 && "Expected more than one context");
854     do {
855       for (unsigned I = 0; I < Mid; ++I)
856         Pool.async(mergeWriterContexts, Contexts[I].get(),
857                    Contexts[I + Mid].get());
858       Pool.wait();
859       if (End & 1) {
860         Pool.async(mergeWriterContexts, Contexts[0].get(),
861                    Contexts[End - 1].get());
862         Pool.wait();
863       }
864       End = Mid;
865       Mid /= 2;
866     } while (Mid > 0);
867   }
868 
869   // Handle deferred errors encountered during merging. If the number of errors
870   // is equal to the number of inputs the merge failed.
871   unsigned NumErrors = 0;
872   for (std::unique_ptr<WriterContext> &WC : Contexts) {
873     for (auto &ErrorPair : WC->Errors) {
874       ++NumErrors;
875       warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
876     }
877   }
878   if ((NumErrors == Inputs.size() && FailMode == failIfAllAreInvalid) ||
879       (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
880     exitWithError("no profile can be merged");
881 
882   writeInstrProfile(OutputFilename, OutputFormat, Contexts[0]->Writer);
883 }
884 
885 /// The profile entry for a function in instrumentation profile.
886 struct InstrProfileEntry {
887   uint64_t MaxCount = 0;
888   uint64_t NumEdgeCounters = 0;
889   float ZeroCounterRatio = 0.0;
890   InstrProfRecord *ProfRecord;
891   InstrProfileEntry(InstrProfRecord *Record);
892   InstrProfileEntry() = default;
893 };
894 
895 InstrProfileEntry::InstrProfileEntry(InstrProfRecord *Record) {
896   ProfRecord = Record;
897   uint64_t CntNum = Record->Counts.size();
898   uint64_t ZeroCntNum = 0;
899   for (size_t I = 0; I < CntNum; ++I) {
900     MaxCount = std::max(MaxCount, Record->Counts[I]);
901     ZeroCntNum += !Record->Counts[I];
902   }
903   ZeroCounterRatio = (float)ZeroCntNum / CntNum;
904   NumEdgeCounters = CntNum;
905 }
906 
907 /// Either set all the counters in the instr profile entry \p IFE to
908 /// -1 / -2 /in order to drop the profile or scale up the
909 /// counters in \p IFP to be above hot / cold threshold. We use
910 /// the ratio of zero counters in the profile of a function to
911 /// decide the profile is helpful or harmful for performance,
912 /// and to choose whether to scale up or drop it.
913 static void updateInstrProfileEntry(InstrProfileEntry &IFE, bool SetToHot,
914                                     uint64_t HotInstrThreshold,
915                                     uint64_t ColdInstrThreshold,
916                                     float ZeroCounterThreshold) {
917   InstrProfRecord *ProfRecord = IFE.ProfRecord;
918   if (!IFE.MaxCount || IFE.ZeroCounterRatio > ZeroCounterThreshold) {
919     // If all or most of the counters of the function are zero, the
920     // profile is unaccountable and should be dropped. Reset all the
921     // counters to be -1 / -2 and PGO profile-use will drop the profile.
922     // All counters being -1 also implies that the function is hot so
923     // PGO profile-use will also set the entry count metadata to be
924     // above hot threshold.
925     // All counters being -2 implies that the function is warm so
926     // PGO profile-use will also set the entry count metadata to be
927     // above cold threshold.
928     auto Kind =
929         (SetToHot ? InstrProfRecord::PseudoHot : InstrProfRecord::PseudoWarm);
930     ProfRecord->setPseudoCount(Kind);
931     return;
932   }
933 
934   // Scale up the MaxCount to be multiple times above hot / cold threshold.
935   const unsigned MultiplyFactor = 3;
936   uint64_t Threshold = (SetToHot ? HotInstrThreshold : ColdInstrThreshold);
937   uint64_t Numerator = Threshold * MultiplyFactor;
938 
939   // Make sure Threshold for warm counters is below the HotInstrThreshold.
940   if (!SetToHot && Threshold >= HotInstrThreshold) {
941     Threshold = (HotInstrThreshold + ColdInstrThreshold) / 2;
942   }
943 
944   uint64_t Denominator = IFE.MaxCount;
945   if (Numerator <= Denominator)
946     return;
947   ProfRecord->scale(Numerator, Denominator, [&](instrprof_error E) {
948     warn(toString(make_error<InstrProfError>(E)));
949   });
950 }
951 
952 const uint64_t ColdPercentileIdx = 15;
953 const uint64_t HotPercentileIdx = 11;
954 
955 using sampleprof::FSDiscriminatorPass;
956 
957 // Internal options to set FSDiscriminatorPass. Used in merge and show
958 // commands.
959 static cl::opt<FSDiscriminatorPass> FSDiscriminatorPassOption(
960     "fs-discriminator-pass", cl::init(PassLast), cl::Hidden,
961     cl::desc("Zero out the discriminator bits for the FS discrimiantor "
962              "pass beyond this value. The enum values are defined in "
963              "Support/Discriminator.h"),
964     cl::values(clEnumVal(Base, "Use base discriminators only"),
965                clEnumVal(Pass1, "Use base and pass 1 discriminators"),
966                clEnumVal(Pass2, "Use base and pass 1-2 discriminators"),
967                clEnumVal(Pass3, "Use base and pass 1-3 discriminators"),
968                clEnumVal(PassLast, "Use all discriminator bits (default)")));
969 
970 static unsigned getDiscriminatorMask() {
971   return getN1Bits(getFSPassBitEnd(FSDiscriminatorPassOption.getValue()));
972 }
973 
974 /// Adjust the instr profile in \p WC based on the sample profile in
975 /// \p Reader.
976 static void
977 adjustInstrProfile(std::unique_ptr<WriterContext> &WC,
978                    std::unique_ptr<sampleprof::SampleProfileReader> &Reader,
979                    unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
980                    unsigned InstrProfColdThreshold) {
981   // Function to its entry in instr profile.
982   StringMap<InstrProfileEntry> InstrProfileMap;
983   StringMap<StringRef> StaticFuncMap;
984   InstrProfSummaryBuilder IPBuilder(ProfileSummaryBuilder::DefaultCutoffs);
985 
986   auto checkSampleProfileHasFUnique = [&Reader]() {
987     for (const auto &PD : Reader->getProfiles()) {
988       auto &FContext = PD.second.getContext();
989       if (FContext.toString().find(FunctionSamples::UniqSuffix) !=
990           std::string::npos) {
991         return true;
992       }
993     }
994     return false;
995   };
996 
997   bool SampleProfileHasFUnique = checkSampleProfileHasFUnique();
998 
999   auto buildStaticFuncMap = [&StaticFuncMap,
1000                              SampleProfileHasFUnique](const StringRef Name) {
1001     std::string FilePrefixes[] = {".cpp", "cc", ".c", ".hpp", ".h"};
1002     size_t PrefixPos = StringRef::npos;
1003     for (auto &FilePrefix : FilePrefixes) {
1004       std::string NamePrefix = FilePrefix + kGlobalIdentifierDelimiter;
1005       PrefixPos = Name.find_insensitive(NamePrefix);
1006       if (PrefixPos == StringRef::npos)
1007         continue;
1008       PrefixPos += NamePrefix.size();
1009       break;
1010     }
1011 
1012     if (PrefixPos == StringRef::npos) {
1013       return;
1014     }
1015 
1016     StringRef NewName = Name.drop_front(PrefixPos);
1017     StringRef FName = Name.substr(0, PrefixPos - 1);
1018     if (NewName.size() == 0) {
1019       return;
1020     }
1021 
1022     // This name should have a static linkage.
1023     size_t PostfixPos = NewName.find(FunctionSamples::UniqSuffix);
1024     bool ProfileHasFUnique = (PostfixPos != StringRef::npos);
1025 
1026     // If sample profile and instrumented profile do not agree on symbol
1027     // uniqification.
1028     if (SampleProfileHasFUnique != ProfileHasFUnique) {
1029       // If instrumented profile uses -funique-internal-linkage-symbols,
1030       // we need to trim the name.
1031       if (ProfileHasFUnique) {
1032         NewName = NewName.substr(0, PostfixPos);
1033       } else {
1034         // If sample profile uses -funique-internal-linkage-symbols,
1035         // we build the map.
1036         std::string NStr =
1037             NewName.str() + getUniqueInternalLinkagePostfix(FName);
1038         NewName = StringRef(NStr);
1039         StaticFuncMap[NewName] = Name;
1040         return;
1041       }
1042     }
1043 
1044     if (!StaticFuncMap.contains(NewName)) {
1045       StaticFuncMap[NewName] = Name;
1046     } else {
1047       StaticFuncMap[NewName] = DuplicateNameStr;
1048     }
1049   };
1050 
1051   // We need to flatten the SampleFDO profile as the InstrFDO
1052   // profile does not have inlined callsite profiles.
1053   // One caveat is the pre-inlined function -- their samples
1054   // should be collapsed into the caller function.
1055   // Here we do a DFS traversal to get the flatten profile
1056   // info: the sum of entrycount and the max of maxcount.
1057   // Here is the algorithm:
1058   //   recursive (FS, root_name) {
1059   //      name = FS->getName();
1060   //      get samples for FS;
1061   //      if (InstrProf.find(name) {
1062   //        root_name = name;
1063   //      } else {
1064   //        if (name is in static_func map) {
1065   //          root_name = static_name;
1066   //        }
1067   //      }
1068   //      update the Map entry for root_name;
1069   //      for (subfs: FS) {
1070   //        recursive(subfs, root_name);
1071   //      }
1072   //   }
1073   //
1074   // Here is an example.
1075   //
1076   // SampleProfile:
1077   // foo:12345:1000
1078   // 1: 1000
1079   // 2.1: 1000
1080   // 15: 5000
1081   // 4: bar:1000
1082   //  1: 1000
1083   //  2: goo:3000
1084   //   1: 3000
1085   // 8: bar:40000
1086   //  1: 10000
1087   //  2: goo:30000
1088   //   1: 30000
1089   //
1090   // InstrProfile has two entries:
1091   //  foo
1092   //  bar.cc;bar
1093   //
1094   // After BuildMaxSampleMap, we should have the following in FlattenSampleMap:
1095   // {"foo", {1000, 5000}}
1096   // {"bar.cc;bar", {11000, 30000}}
1097   //
1098   // foo's has an entry count of 1000, and max body count of 5000.
1099   // bar.cc;bar has an entry count of 11000 (sum two callsites of 1000 and
1100   // 10000), and max count of 30000 (from the callsite in line 8).
1101   //
1102   // Note that goo's count will remain in bar.cc;bar() as it does not have an
1103   // entry in InstrProfile.
1104   llvm::StringMap<std::pair<uint64_t, uint64_t>> FlattenSampleMap;
1105   auto BuildMaxSampleMap = [&FlattenSampleMap, &StaticFuncMap,
1106                             &InstrProfileMap](const FunctionSamples &FS,
1107                                               const StringRef &RootName) {
1108     auto BuildMaxSampleMapImpl = [&](const FunctionSamples &FS,
1109                                      const StringRef &RootName,
1110                                      auto &BuildImpl) -> void {
1111       std::string NameStr = FS.getFunction().str();
1112       const StringRef Name = NameStr;
1113       const StringRef *NewRootName = &RootName;
1114       uint64_t EntrySample = FS.getHeadSamplesEstimate();
1115       uint64_t MaxBodySample = FS.getMaxCountInside(/* SkipCallSite*/ true);
1116 
1117       auto It = InstrProfileMap.find(Name);
1118       if (It != InstrProfileMap.end()) {
1119         NewRootName = &Name;
1120       } else {
1121         auto NewName = StaticFuncMap.find(Name);
1122         if (NewName != StaticFuncMap.end()) {
1123           It = InstrProfileMap.find(NewName->second.str());
1124           if (NewName->second != DuplicateNameStr) {
1125             NewRootName = &NewName->second;
1126           }
1127         } else {
1128           // Here the EntrySample is of an inlined function, so we should not
1129           // update the EntrySample in the map.
1130           EntrySample = 0;
1131         }
1132       }
1133       EntrySample += FlattenSampleMap[*NewRootName].first;
1134       MaxBodySample =
1135           std::max(FlattenSampleMap[*NewRootName].second, MaxBodySample);
1136       FlattenSampleMap[*NewRootName] =
1137           std::make_pair(EntrySample, MaxBodySample);
1138 
1139       for (const auto &C : FS.getCallsiteSamples())
1140         for (const auto &F : C.second)
1141           BuildImpl(F.second, *NewRootName, BuildImpl);
1142     };
1143     BuildMaxSampleMapImpl(FS, RootName, BuildMaxSampleMapImpl);
1144   };
1145 
1146   for (auto &PD : WC->Writer.getProfileData()) {
1147     // Populate IPBuilder.
1148     for (const auto &PDV : PD.getValue()) {
1149       InstrProfRecord Record = PDV.second;
1150       IPBuilder.addRecord(Record);
1151     }
1152 
1153     // If a function has multiple entries in instr profile, skip it.
1154     if (PD.getValue().size() != 1)
1155       continue;
1156 
1157     // Initialize InstrProfileMap.
1158     InstrProfRecord *R = &PD.getValue().begin()->second;
1159     StringRef FullName = PD.getKey();
1160     InstrProfileMap[FullName] = InstrProfileEntry(R);
1161     buildStaticFuncMap(FullName);
1162   }
1163 
1164   for (auto &PD : Reader->getProfiles()) {
1165     sampleprof::FunctionSamples &FS = PD.second;
1166     std::string Name = FS.getFunction().str();
1167     BuildMaxSampleMap(FS, Name);
1168   }
1169 
1170   ProfileSummary InstrPS = *IPBuilder.getSummary();
1171   ProfileSummary SamplePS = Reader->getSummary();
1172 
1173   // Compute cold thresholds for instr profile and sample profile.
1174   uint64_t HotSampleThreshold =
1175       ProfileSummaryBuilder::getEntryForPercentile(
1176           SamplePS.getDetailedSummary(),
1177           ProfileSummaryBuilder::DefaultCutoffs[HotPercentileIdx])
1178           .MinCount;
1179   uint64_t ColdSampleThreshold =
1180       ProfileSummaryBuilder::getEntryForPercentile(
1181           SamplePS.getDetailedSummary(),
1182           ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
1183           .MinCount;
1184   uint64_t HotInstrThreshold =
1185       ProfileSummaryBuilder::getEntryForPercentile(
1186           InstrPS.getDetailedSummary(),
1187           ProfileSummaryBuilder::DefaultCutoffs[HotPercentileIdx])
1188           .MinCount;
1189   uint64_t ColdInstrThreshold =
1190       InstrProfColdThreshold
1191           ? InstrProfColdThreshold
1192           : ProfileSummaryBuilder::getEntryForPercentile(
1193                 InstrPS.getDetailedSummary(),
1194                 ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
1195                 .MinCount;
1196 
1197   // Find hot/warm functions in sample profile which is cold in instr profile
1198   // and adjust the profiles of those functions in the instr profile.
1199   for (const auto &E : FlattenSampleMap) {
1200     uint64_t SampleMaxCount = std::max(E.second.first, E.second.second);
1201     if (SampleMaxCount < ColdSampleThreshold)
1202       continue;
1203     StringRef Name = E.first();
1204     auto It = InstrProfileMap.find(Name);
1205     if (It == InstrProfileMap.end()) {
1206       auto NewName = StaticFuncMap.find(Name);
1207       if (NewName != StaticFuncMap.end()) {
1208         It = InstrProfileMap.find(NewName->second.str());
1209         if (NewName->second == DuplicateNameStr) {
1210           WithColor::warning()
1211               << "Static function " << Name
1212               << " has multiple promoted names, cannot adjust profile.\n";
1213         }
1214       }
1215     }
1216     if (It == InstrProfileMap.end() ||
1217         It->second.MaxCount > ColdInstrThreshold ||
1218         It->second.NumEdgeCounters < SupplMinSizeThreshold)
1219       continue;
1220     bool SetToHot = SampleMaxCount >= HotSampleThreshold;
1221     updateInstrProfileEntry(It->second, SetToHot, HotInstrThreshold,
1222                             ColdInstrThreshold, ZeroCounterThreshold);
1223   }
1224 }
1225 
1226 /// The main function to supplement instr profile with sample profile.
1227 /// \Inputs contains the instr profile. \p SampleFilename specifies the
1228 /// sample profile. \p OutputFilename specifies the output profile name.
1229 /// \p OutputFormat specifies the output profile format. \p OutputSparse
1230 /// specifies whether to generate sparse profile. \p SupplMinSizeThreshold
1231 /// specifies the minimal size for the functions whose profile will be
1232 /// adjusted. \p ZeroCounterThreshold is the threshold to check whether
1233 /// a function contains too many zero counters and whether its profile
1234 /// should be dropped. \p InstrProfColdThreshold is the user specified
1235 /// cold threshold which will override the cold threshold got from the
1236 /// instr profile summary.
1237 static void supplementInstrProfile(const WeightedFileVector &Inputs,
1238                                    StringRef SampleFilename, bool OutputSparse,
1239                                    unsigned SupplMinSizeThreshold,
1240                                    float ZeroCounterThreshold,
1241                                    unsigned InstrProfColdThreshold) {
1242   if (OutputFilename.compare("-") == 0)
1243     exitWithError("cannot write indexed profdata format to stdout");
1244   if (Inputs.size() != 1)
1245     exitWithError("expect one input to be an instr profile");
1246   if (Inputs[0].Weight != 1)
1247     exitWithError("expect instr profile doesn't have weight");
1248 
1249   StringRef InstrFilename = Inputs[0].Filename;
1250 
1251   // Read sample profile.
1252   LLVMContext Context;
1253   auto FS = vfs::getRealFileSystem();
1254   auto ReaderOrErr = sampleprof::SampleProfileReader::create(
1255       SampleFilename.str(), Context, *FS, FSDiscriminatorPassOption);
1256   if (std::error_code EC = ReaderOrErr.getError())
1257     exitWithErrorCode(EC, SampleFilename);
1258   auto Reader = std::move(ReaderOrErr.get());
1259   if (std::error_code EC = Reader->read())
1260     exitWithErrorCode(EC, SampleFilename);
1261 
1262   // Read instr profile.
1263   std::mutex ErrorLock;
1264   SmallSet<instrprof_error, 4> WriterErrorCodes;
1265   auto WC = std::make_unique<WriterContext>(OutputSparse, ErrorLock,
1266                                             WriterErrorCodes);
1267   loadInput(Inputs[0], nullptr, nullptr, /*ProfiledBinary=*/"", WC.get());
1268   if (WC->Errors.size() > 0)
1269     exitWithError(std::move(WC->Errors[0].first), InstrFilename);
1270 
1271   adjustInstrProfile(WC, Reader, SupplMinSizeThreshold, ZeroCounterThreshold,
1272                      InstrProfColdThreshold);
1273   writeInstrProfile(OutputFilename, OutputFormat, WC->Writer);
1274 }
1275 
1276 /// Make a copy of the given function samples with all symbol names remapped
1277 /// by the provided symbol remapper.
1278 static sampleprof::FunctionSamples
1279 remapSamples(const sampleprof::FunctionSamples &Samples,
1280              SymbolRemapper &Remapper, sampleprof_error &Error) {
1281   sampleprof::FunctionSamples Result;
1282   Result.setFunction(Remapper(Samples.getFunction()));
1283   Result.addTotalSamples(Samples.getTotalSamples());
1284   Result.addHeadSamples(Samples.getHeadSamples());
1285   for (const auto &BodySample : Samples.getBodySamples()) {
1286     uint32_t MaskedDiscriminator =
1287         BodySample.first.Discriminator & getDiscriminatorMask();
1288     Result.addBodySamples(BodySample.first.LineOffset, MaskedDiscriminator,
1289                           BodySample.second.getSamples());
1290     for (const auto &Target : BodySample.second.getCallTargets()) {
1291       Result.addCalledTargetSamples(BodySample.first.LineOffset,
1292                                     MaskedDiscriminator,
1293                                     Remapper(Target.first), Target.second);
1294     }
1295   }
1296   for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
1297     sampleprof::FunctionSamplesMap &Target =
1298         Result.functionSamplesAt(CallsiteSamples.first);
1299     for (const auto &Callsite : CallsiteSamples.second) {
1300       sampleprof::FunctionSamples Remapped =
1301           remapSamples(Callsite.second, Remapper, Error);
1302       MergeResult(Error, Target[Remapped.getFunction()].merge(Remapped));
1303     }
1304   }
1305   return Result;
1306 }
1307 
1308 static sampleprof::SampleProfileFormat FormatMap[] = {
1309     sampleprof::SPF_None,
1310     sampleprof::SPF_Text,
1311     sampleprof::SPF_None,
1312     sampleprof::SPF_Ext_Binary,
1313     sampleprof::SPF_GCC,
1314     sampleprof::SPF_Binary};
1315 
1316 static std::unique_ptr<MemoryBuffer>
1317 getInputFileBuf(const StringRef &InputFile) {
1318   if (InputFile == "")
1319     return {};
1320 
1321   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
1322   if (!BufOrError)
1323     exitWithErrorCode(BufOrError.getError(), InputFile);
1324 
1325   return std::move(*BufOrError);
1326 }
1327 
1328 static void populateProfileSymbolList(MemoryBuffer *Buffer,
1329                                       sampleprof::ProfileSymbolList &PSL) {
1330   if (!Buffer)
1331     return;
1332 
1333   SmallVector<StringRef, 32> SymbolVec;
1334   StringRef Data = Buffer->getBuffer();
1335   Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
1336 
1337   for (StringRef SymbolStr : SymbolVec)
1338     PSL.add(SymbolStr.trim());
1339 }
1340 
1341 static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer,
1342                                   ProfileFormat OutputFormat,
1343                                   MemoryBuffer *Buffer,
1344                                   sampleprof::ProfileSymbolList &WriterList,
1345                                   bool CompressAllSections, bool UseMD5,
1346                                   bool GenPartialProfile) {
1347   populateProfileSymbolList(Buffer, WriterList);
1348   if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
1349     warn("Profile Symbol list is not empty but the output format is not "
1350          "ExtBinary format. The list will be lost in the output. ");
1351 
1352   Writer.setProfileSymbolList(&WriterList);
1353 
1354   if (CompressAllSections) {
1355     if (OutputFormat != PF_Ext_Binary)
1356       warn("-compress-all-section is ignored. Specify -extbinary to enable it");
1357     else
1358       Writer.setToCompressAllSections();
1359   }
1360   if (UseMD5) {
1361     if (OutputFormat != PF_Ext_Binary)
1362       warn("-use-md5 is ignored. Specify -extbinary to enable it");
1363     else
1364       Writer.setUseMD5();
1365   }
1366   if (GenPartialProfile) {
1367     if (OutputFormat != PF_Ext_Binary)
1368       warn("-gen-partial-profile is ignored. Specify -extbinary to enable it");
1369     else
1370       Writer.setPartialProfile();
1371   }
1372 }
1373 
1374 static void mergeSampleProfile(const WeightedFileVector &Inputs,
1375                                SymbolRemapper *Remapper,
1376                                StringRef ProfileSymbolListFile,
1377                                size_t OutputSizeLimit) {
1378   using namespace sampleprof;
1379   SampleProfileMap ProfileMap;
1380   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
1381   LLVMContext Context;
1382   sampleprof::ProfileSymbolList WriterList;
1383   std::optional<bool> ProfileIsProbeBased;
1384   std::optional<bool> ProfileIsCS;
1385   for (const auto &Input : Inputs) {
1386     auto FS = vfs::getRealFileSystem();
1387     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context, *FS,
1388                                                    FSDiscriminatorPassOption);
1389     if (std::error_code EC = ReaderOrErr.getError()) {
1390       warnOrExitGivenError(FailMode, EC, Input.Filename);
1391       continue;
1392     }
1393 
1394     // We need to keep the readers around until after all the files are
1395     // read so that we do not lose the function names stored in each
1396     // reader's memory. The function names are needed to write out the
1397     // merged profile map.
1398     Readers.push_back(std::move(ReaderOrErr.get()));
1399     const auto Reader = Readers.back().get();
1400     if (std::error_code EC = Reader->read()) {
1401       warnOrExitGivenError(FailMode, EC, Input.Filename);
1402       Readers.pop_back();
1403       continue;
1404     }
1405 
1406     SampleProfileMap &Profiles = Reader->getProfiles();
1407     if (ProfileIsProbeBased &&
1408         ProfileIsProbeBased != FunctionSamples::ProfileIsProbeBased)
1409       exitWithError(
1410           "cannot merge probe-based profile with non-probe-based profile");
1411     ProfileIsProbeBased = FunctionSamples::ProfileIsProbeBased;
1412     if (ProfileIsCS && ProfileIsCS != FunctionSamples::ProfileIsCS)
1413       exitWithError("cannot merge CS profile with non-CS profile");
1414     ProfileIsCS = FunctionSamples::ProfileIsCS;
1415     for (SampleProfileMap::iterator I = Profiles.begin(), E = Profiles.end();
1416          I != E; ++I) {
1417       sampleprof_error Result = sampleprof_error::success;
1418       FunctionSamples Remapped =
1419           Remapper ? remapSamples(I->second, *Remapper, Result)
1420                    : FunctionSamples();
1421       FunctionSamples &Samples = Remapper ? Remapped : I->second;
1422       SampleContext FContext = Samples.getContext();
1423       MergeResult(Result, ProfileMap[FContext].merge(Samples, Input.Weight));
1424       if (Result != sampleprof_error::success) {
1425         std::error_code EC = make_error_code(Result);
1426         handleMergeWriterError(errorCodeToError(EC), Input.Filename,
1427                                FContext.toString());
1428       }
1429     }
1430 
1431     if (!DropProfileSymbolList) {
1432       std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
1433           Reader->getProfileSymbolList();
1434       if (ReaderList)
1435         WriterList.merge(*ReaderList);
1436     }
1437   }
1438 
1439   if (ProfileIsCS && (SampleMergeColdContext || SampleTrimColdContext)) {
1440     // Use threshold calculated from profile summary unless specified.
1441     SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1442     auto Summary = Builder.computeSummaryForProfiles(ProfileMap);
1443     uint64_t SampleProfColdThreshold =
1444         ProfileSummaryBuilder::getColdCountThreshold(
1445             (Summary->getDetailedSummary()));
1446 
1447     // Trim and merge cold context profile using cold threshold above;
1448     SampleContextTrimmer(ProfileMap)
1449         .trimAndMergeColdContextProfiles(
1450             SampleProfColdThreshold, SampleTrimColdContext,
1451             SampleMergeColdContext, SampleColdContextFrameDepth, false);
1452   }
1453 
1454   if (ProfileLayout == llvm::sampleprof::SPL_Flat) {
1455     ProfileConverter::flattenProfile(ProfileMap, FunctionSamples::ProfileIsCS);
1456     ProfileIsCS = FunctionSamples::ProfileIsCS = false;
1457   } else if (ProfileIsCS && ProfileLayout == llvm::sampleprof::SPL_Nest) {
1458     ProfileConverter CSConverter(ProfileMap);
1459     CSConverter.convertCSProfiles();
1460     ProfileIsCS = FunctionSamples::ProfileIsCS = false;
1461   }
1462 
1463   auto WriterOrErr =
1464       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
1465   if (std::error_code EC = WriterOrErr.getError())
1466     exitWithErrorCode(EC, OutputFilename);
1467 
1468   auto Writer = std::move(WriterOrErr.get());
1469   // WriterList will have StringRef refering to string in Buffer.
1470   // Make sure Buffer lives as long as WriterList.
1471   auto Buffer = getInputFileBuf(ProfileSymbolListFile);
1472   handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList,
1473                         CompressAllSections, UseMD5, GenPartialProfile);
1474 
1475   // If OutputSizeLimit is 0 (default), it is the same as write().
1476   if (std::error_code EC =
1477           Writer->writeWithSizeLimit(ProfileMap, OutputSizeLimit))
1478     exitWithErrorCode(std::move(EC));
1479 }
1480 
1481 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
1482   StringRef WeightStr, FileName;
1483   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
1484 
1485   uint64_t Weight;
1486   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
1487     exitWithError("input weight must be a positive integer");
1488 
1489   return {std::string(FileName), Weight};
1490 }
1491 
1492 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
1493   StringRef Filename = WF.Filename;
1494   uint64_t Weight = WF.Weight;
1495 
1496   // If it's STDIN just pass it on.
1497   if (Filename == "-") {
1498     WNI.push_back({std::string(Filename), Weight});
1499     return;
1500   }
1501 
1502   llvm::sys::fs::file_status Status;
1503   llvm::sys::fs::status(Filename, Status);
1504   if (!llvm::sys::fs::exists(Status))
1505     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
1506                       Filename);
1507   // If it's a source file, collect it.
1508   if (llvm::sys::fs::is_regular_file(Status)) {
1509     WNI.push_back({std::string(Filename), Weight});
1510     return;
1511   }
1512 
1513   if (llvm::sys::fs::is_directory(Status)) {
1514     std::error_code EC;
1515     for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
1516          F != E && !EC; F.increment(EC)) {
1517       if (llvm::sys::fs::is_regular_file(F->path())) {
1518         addWeightedInput(WNI, {F->path(), Weight});
1519       }
1520     }
1521     if (EC)
1522       exitWithErrorCode(EC, Filename);
1523   }
1524 }
1525 
1526 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
1527                                     WeightedFileVector &WFV) {
1528   if (!Buffer)
1529     return;
1530 
1531   SmallVector<StringRef, 8> Entries;
1532   StringRef Data = Buffer->getBuffer();
1533   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
1534   for (const StringRef &FileWeightEntry : Entries) {
1535     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
1536     // Skip comments.
1537     if (SanitizedEntry.starts_with("#"))
1538       continue;
1539     // If there's no comma, it's an unweighted profile.
1540     else if (!SanitizedEntry.contains(','))
1541       addWeightedInput(WFV, {std::string(SanitizedEntry), 1});
1542     else
1543       addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
1544   }
1545 }
1546 
1547 static int merge_main(int argc, const char *argv[]) {
1548   WeightedFileVector WeightedInputs;
1549   for (StringRef Filename : InputFilenames)
1550     addWeightedInput(WeightedInputs, {std::string(Filename), 1});
1551   for (StringRef WeightedFilename : WeightedInputFilenames)
1552     addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
1553 
1554   // Make sure that the file buffer stays alive for the duration of the
1555   // weighted input vector's lifetime.
1556   auto Buffer = getInputFileBuf(InputFilenamesFile);
1557   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
1558 
1559   if (WeightedInputs.empty())
1560     exitWithError("no input files specified. See " +
1561                   sys::path::filename(argv[0]) + " " + argv[1] + " -help");
1562 
1563   if (DumpInputFileList) {
1564     for (auto &WF : WeightedInputs)
1565       outs() << WF.Weight << "," << WF.Filename << "\n";
1566     return 0;
1567   }
1568 
1569   std::unique_ptr<SymbolRemapper> Remapper;
1570   if (!RemappingFile.empty())
1571     Remapper = SymbolRemapper::create(RemappingFile);
1572 
1573   if (!SupplInstrWithSample.empty()) {
1574     if (ProfileKind != instr)
1575       exitWithError(
1576           "-supplement-instr-with-sample can only work with -instr. ");
1577 
1578     supplementInstrProfile(WeightedInputs, SupplInstrWithSample, OutputSparse,
1579                            SupplMinSizeThreshold, ZeroCounterThreshold,
1580                            InstrProfColdThreshold);
1581     return 0;
1582   }
1583 
1584   if (ProfileKind == instr)
1585     mergeInstrProfile(WeightedInputs, Remapper.get(), MaxDbgCorrelationWarnings,
1586                       ProfiledBinary);
1587   else
1588     mergeSampleProfile(WeightedInputs, Remapper.get(), ProfileSymbolListFile,
1589                        OutputSizeLimit);
1590   return 0;
1591 }
1592 
1593 /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
1594 static void overlapInstrProfile(const std::string &BaseFilename,
1595                                 const std::string &TestFilename,
1596                                 const OverlapFuncFilters &FuncFilter,
1597                                 raw_fd_ostream &OS, bool IsCS) {
1598   std::mutex ErrorLock;
1599   SmallSet<instrprof_error, 4> WriterErrorCodes;
1600   WriterContext Context(false, ErrorLock, WriterErrorCodes);
1601   WeightedFile WeightedInput{BaseFilename, 1};
1602   OverlapStats Overlap;
1603   Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS);
1604   if (E)
1605     exitWithError(std::move(E), "error in getting profile count sums");
1606   if (Overlap.Base.CountSum < 1.0f) {
1607     OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
1608     exit(0);
1609   }
1610   if (Overlap.Test.CountSum < 1.0f) {
1611     OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
1612     exit(0);
1613   }
1614   loadInput(WeightedInput, nullptr, nullptr, /*ProfiledBinary=*/"", &Context);
1615   overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
1616                IsCS);
1617   Overlap.dump(OS);
1618 }
1619 
1620 namespace {
1621 struct SampleOverlapStats {
1622   SampleContext BaseName;
1623   SampleContext TestName;
1624   // Number of overlap units
1625   uint64_t OverlapCount = 0;
1626   // Total samples of overlap units
1627   uint64_t OverlapSample = 0;
1628   // Number of and total samples of units that only present in base or test
1629   // profile
1630   uint64_t BaseUniqueCount = 0;
1631   uint64_t BaseUniqueSample = 0;
1632   uint64_t TestUniqueCount = 0;
1633   uint64_t TestUniqueSample = 0;
1634   // Number of units and total samples in base or test profile
1635   uint64_t BaseCount = 0;
1636   uint64_t BaseSample = 0;
1637   uint64_t TestCount = 0;
1638   uint64_t TestSample = 0;
1639   // Number of and total samples of units that present in at least one profile
1640   uint64_t UnionCount = 0;
1641   uint64_t UnionSample = 0;
1642   // Weighted similarity
1643   double Similarity = 0.0;
1644   // For SampleOverlapStats instances representing functions, weights of the
1645   // function in base and test profiles
1646   double BaseWeight = 0.0;
1647   double TestWeight = 0.0;
1648 
1649   SampleOverlapStats() = default;
1650 };
1651 } // end anonymous namespace
1652 
1653 namespace {
1654 struct FuncSampleStats {
1655   uint64_t SampleSum = 0;
1656   uint64_t MaxSample = 0;
1657   uint64_t HotBlockCount = 0;
1658   FuncSampleStats() = default;
1659   FuncSampleStats(uint64_t SampleSum, uint64_t MaxSample,
1660                   uint64_t HotBlockCount)
1661       : SampleSum(SampleSum), MaxSample(MaxSample),
1662         HotBlockCount(HotBlockCount) {}
1663 };
1664 } // end anonymous namespace
1665 
1666 namespace {
1667 enum MatchStatus { MS_Match, MS_FirstUnique, MS_SecondUnique, MS_None };
1668 
1669 // Class for updating merging steps for two sorted maps. The class should be
1670 // instantiated with a map iterator type.
1671 template <class T> class MatchStep {
1672 public:
1673   MatchStep() = delete;
1674 
1675   MatchStep(T FirstIter, T FirstEnd, T SecondIter, T SecondEnd)
1676       : FirstIter(FirstIter), FirstEnd(FirstEnd), SecondIter(SecondIter),
1677         SecondEnd(SecondEnd), Status(MS_None) {}
1678 
1679   bool areBothFinished() const {
1680     return (FirstIter == FirstEnd && SecondIter == SecondEnd);
1681   }
1682 
1683   bool isFirstFinished() const { return FirstIter == FirstEnd; }
1684 
1685   bool isSecondFinished() const { return SecondIter == SecondEnd; }
1686 
1687   /// Advance one step based on the previous match status unless the previous
1688   /// status is MS_None. Then update Status based on the comparison between two
1689   /// container iterators at the current step. If the previous status is
1690   /// MS_None, it means two iterators are at the beginning and no comparison has
1691   /// been made, so we simply update Status without advancing the iterators.
1692   void updateOneStep();
1693 
1694   T getFirstIter() const { return FirstIter; }
1695 
1696   T getSecondIter() const { return SecondIter; }
1697 
1698   MatchStatus getMatchStatus() const { return Status; }
1699 
1700 private:
1701   // Current iterator and end iterator of the first container.
1702   T FirstIter;
1703   T FirstEnd;
1704   // Current iterator and end iterator of the second container.
1705   T SecondIter;
1706   T SecondEnd;
1707   // Match status of the current step.
1708   MatchStatus Status;
1709 };
1710 } // end anonymous namespace
1711 
1712 template <class T> void MatchStep<T>::updateOneStep() {
1713   switch (Status) {
1714   case MS_Match:
1715     ++FirstIter;
1716     ++SecondIter;
1717     break;
1718   case MS_FirstUnique:
1719     ++FirstIter;
1720     break;
1721   case MS_SecondUnique:
1722     ++SecondIter;
1723     break;
1724   case MS_None:
1725     break;
1726   }
1727 
1728   // Update Status according to iterators at the current step.
1729   if (areBothFinished())
1730     return;
1731   if (FirstIter != FirstEnd &&
1732       (SecondIter == SecondEnd || FirstIter->first < SecondIter->first))
1733     Status = MS_FirstUnique;
1734   else if (SecondIter != SecondEnd &&
1735            (FirstIter == FirstEnd || SecondIter->first < FirstIter->first))
1736     Status = MS_SecondUnique;
1737   else
1738     Status = MS_Match;
1739 }
1740 
1741 // Return the sum of line/block samples, the max line/block sample, and the
1742 // number of line/block samples above the given threshold in a function
1743 // including its inlinees.
1744 static void getFuncSampleStats(const sampleprof::FunctionSamples &Func,
1745                                FuncSampleStats &FuncStats,
1746                                uint64_t HotThreshold) {
1747   for (const auto &L : Func.getBodySamples()) {
1748     uint64_t Sample = L.second.getSamples();
1749     FuncStats.SampleSum += Sample;
1750     FuncStats.MaxSample = std::max(FuncStats.MaxSample, Sample);
1751     if (Sample >= HotThreshold)
1752       ++FuncStats.HotBlockCount;
1753   }
1754 
1755   for (const auto &C : Func.getCallsiteSamples()) {
1756     for (const auto &F : C.second)
1757       getFuncSampleStats(F.second, FuncStats, HotThreshold);
1758   }
1759 }
1760 
1761 /// Predicate that determines if a function is hot with a given threshold. We
1762 /// keep it separate from its callsites for possible extension in the future.
1763 static bool isFunctionHot(const FuncSampleStats &FuncStats,
1764                           uint64_t HotThreshold) {
1765   // We intentionally compare the maximum sample count in a function with the
1766   // HotThreshold to get an approximate determination on hot functions.
1767   return (FuncStats.MaxSample >= HotThreshold);
1768 }
1769 
1770 namespace {
1771 class SampleOverlapAggregator {
1772 public:
1773   SampleOverlapAggregator(const std::string &BaseFilename,
1774                           const std::string &TestFilename,
1775                           double LowSimilarityThreshold, double Epsilon,
1776                           const OverlapFuncFilters &FuncFilter)
1777       : BaseFilename(BaseFilename), TestFilename(TestFilename),
1778         LowSimilarityThreshold(LowSimilarityThreshold), Epsilon(Epsilon),
1779         FuncFilter(FuncFilter) {}
1780 
1781   /// Detect 0-sample input profile and report to output stream. This interface
1782   /// should be called after loadProfiles().
1783   bool detectZeroSampleProfile(raw_fd_ostream &OS) const;
1784 
1785   /// Write out function-level similarity statistics for functions specified by
1786   /// options --function, --value-cutoff, and --similarity-cutoff.
1787   void dumpFuncSimilarity(raw_fd_ostream &OS) const;
1788 
1789   /// Write out program-level similarity and overlap statistics.
1790   void dumpProgramSummary(raw_fd_ostream &OS) const;
1791 
1792   /// Write out hot-function and hot-block statistics for base_profile,
1793   /// test_profile, and their overlap. For both cases, the overlap HO is
1794   /// calculated as follows:
1795   ///    Given the number of functions (or blocks) that are hot in both profiles
1796   ///    HCommon and the number of functions (or blocks) that are hot in at
1797   ///    least one profile HUnion, HO = HCommon / HUnion.
1798   void dumpHotFuncAndBlockOverlap(raw_fd_ostream &OS) const;
1799 
1800   /// This function tries matching functions in base and test profiles. For each
1801   /// pair of matched functions, it aggregates the function-level
1802   /// similarity into a profile-level similarity. It also dump function-level
1803   /// similarity information of functions specified by --function,
1804   /// --value-cutoff, and --similarity-cutoff options. The program-level
1805   /// similarity PS is computed as follows:
1806   ///     Given function-level similarity FS(A) for all function A, the
1807   ///     weight of function A in base profile WB(A), and the weight of function
1808   ///     A in test profile WT(A), compute PS(base_profile, test_profile) =
1809   ///     sum_A(FS(A) * avg(WB(A), WT(A))) ranging in [0.0f to 1.0f] with 0.0
1810   ///     meaning no-overlap.
1811   void computeSampleProfileOverlap(raw_fd_ostream &OS);
1812 
1813   /// Initialize ProfOverlap with the sum of samples in base and test
1814   /// profiles. This function also computes and keeps the sum of samples and
1815   /// max sample counts of each function in BaseStats and TestStats for later
1816   /// use to avoid re-computations.
1817   void initializeSampleProfileOverlap();
1818 
1819   /// Load profiles specified by BaseFilename and TestFilename.
1820   std::error_code loadProfiles();
1821 
1822   using FuncSampleStatsMap =
1823       std::unordered_map<SampleContext, FuncSampleStats, SampleContext::Hash>;
1824 
1825 private:
1826   SampleOverlapStats ProfOverlap;
1827   SampleOverlapStats HotFuncOverlap;
1828   SampleOverlapStats HotBlockOverlap;
1829   std::string BaseFilename;
1830   std::string TestFilename;
1831   std::unique_ptr<sampleprof::SampleProfileReader> BaseReader;
1832   std::unique_ptr<sampleprof::SampleProfileReader> TestReader;
1833   // BaseStats and TestStats hold FuncSampleStats for each function, with
1834   // function name as the key.
1835   FuncSampleStatsMap BaseStats;
1836   FuncSampleStatsMap TestStats;
1837   // Low similarity threshold in floating point number
1838   double LowSimilarityThreshold;
1839   // Block samples above BaseHotThreshold or TestHotThreshold are considered hot
1840   // for tracking hot blocks.
1841   uint64_t BaseHotThreshold;
1842   uint64_t TestHotThreshold;
1843   // A small threshold used to round the results of floating point accumulations
1844   // to resolve imprecision.
1845   const double Epsilon;
1846   std::multimap<double, SampleOverlapStats, std::greater<double>>
1847       FuncSimilarityDump;
1848   // FuncFilter carries specifications in options --value-cutoff and
1849   // --function.
1850   OverlapFuncFilters FuncFilter;
1851   // Column offsets for printing the function-level details table.
1852   static const unsigned int TestWeightCol = 15;
1853   static const unsigned int SimilarityCol = 30;
1854   static const unsigned int OverlapCol = 43;
1855   static const unsigned int BaseUniqueCol = 53;
1856   static const unsigned int TestUniqueCol = 67;
1857   static const unsigned int BaseSampleCol = 81;
1858   static const unsigned int TestSampleCol = 96;
1859   static const unsigned int FuncNameCol = 111;
1860 
1861   /// Return a similarity of two line/block sample counters in the same
1862   /// function in base and test profiles. The line/block-similarity BS(i) is
1863   /// computed as follows:
1864   ///    For an offsets i, given the sample count at i in base profile BB(i),
1865   ///    the sample count at i in test profile BT(i), the sum of sample counts
1866   ///    in this function in base profile SB, and the sum of sample counts in
1867   ///    this function in test profile ST, compute BS(i) = 1.0 - fabs(BB(i)/SB -
1868   ///    BT(i)/ST), ranging in [0.0f to 1.0f] with 0.0 meaning no-overlap.
1869   double computeBlockSimilarity(uint64_t BaseSample, uint64_t TestSample,
1870                                 const SampleOverlapStats &FuncOverlap) const;
1871 
1872   void updateHotBlockOverlap(uint64_t BaseSample, uint64_t TestSample,
1873                              uint64_t HotBlockCount);
1874 
1875   void getHotFunctions(const FuncSampleStatsMap &ProfStats,
1876                        FuncSampleStatsMap &HotFunc,
1877                        uint64_t HotThreshold) const;
1878 
1879   void computeHotFuncOverlap();
1880 
1881   /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
1882   /// Difference for two sample units in a matched function according to the
1883   /// given match status.
1884   void updateOverlapStatsForFunction(uint64_t BaseSample, uint64_t TestSample,
1885                                      uint64_t HotBlockCount,
1886                                      SampleOverlapStats &FuncOverlap,
1887                                      double &Difference, MatchStatus Status);
1888 
1889   /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
1890   /// Difference for unmatched callees that only present in one profile in a
1891   /// matched caller function.
1892   void updateForUnmatchedCallee(const sampleprof::FunctionSamples &Func,
1893                                 SampleOverlapStats &FuncOverlap,
1894                                 double &Difference, MatchStatus Status);
1895 
1896   /// This function updates sample overlap statistics of an overlap function in
1897   /// base and test profile. It also calculates a function-internal similarity
1898   /// FIS as follows:
1899   ///    For offsets i that have samples in at least one profile in this
1900   ///    function A, given BS(i) returned by computeBlockSimilarity(), compute
1901   ///    FIS(A) = (2.0 - sum_i(1.0 - BS(i))) / 2, ranging in [0.0f to 1.0f] with
1902   ///    0.0 meaning no overlap.
1903   double computeSampleFunctionInternalOverlap(
1904       const sampleprof::FunctionSamples &BaseFunc,
1905       const sampleprof::FunctionSamples &TestFunc,
1906       SampleOverlapStats &FuncOverlap);
1907 
1908   /// Function-level similarity (FS) is a weighted value over function internal
1909   /// similarity (FIS). This function computes a function's FS from its FIS by
1910   /// applying the weight.
1911   double weightForFuncSimilarity(double FuncSimilarity, uint64_t BaseFuncSample,
1912                                  uint64_t TestFuncSample) const;
1913 
1914   /// The function-level similarity FS(A) for a function A is computed as
1915   /// follows:
1916   ///     Compute a function-internal similarity FIS(A) by
1917   ///     computeSampleFunctionInternalOverlap(). Then, with the weight of
1918   ///     function A in base profile WB(A), and the weight of function A in test
1919   ///     profile WT(A), compute FS(A) = FIS(A) * (1.0 - fabs(WB(A) - WT(A)))
1920   ///     ranging in [0.0f to 1.0f] with 0.0 meaning no overlap.
1921   double
1922   computeSampleFunctionOverlap(const sampleprof::FunctionSamples *BaseFunc,
1923                                const sampleprof::FunctionSamples *TestFunc,
1924                                SampleOverlapStats *FuncOverlap,
1925                                uint64_t BaseFuncSample,
1926                                uint64_t TestFuncSample);
1927 
1928   /// Profile-level similarity (PS) is a weighted aggregate over function-level
1929   /// similarities (FS). This method weights the FS value by the function
1930   /// weights in the base and test profiles for the aggregation.
1931   double weightByImportance(double FuncSimilarity, uint64_t BaseFuncSample,
1932                             uint64_t TestFuncSample) const;
1933 };
1934 } // end anonymous namespace
1935 
1936 bool SampleOverlapAggregator::detectZeroSampleProfile(
1937     raw_fd_ostream &OS) const {
1938   bool HaveZeroSample = false;
1939   if (ProfOverlap.BaseSample == 0) {
1940     OS << "Sum of sample counts for profile " << BaseFilename << " is 0.\n";
1941     HaveZeroSample = true;
1942   }
1943   if (ProfOverlap.TestSample == 0) {
1944     OS << "Sum of sample counts for profile " << TestFilename << " is 0.\n";
1945     HaveZeroSample = true;
1946   }
1947   return HaveZeroSample;
1948 }
1949 
1950 double SampleOverlapAggregator::computeBlockSimilarity(
1951     uint64_t BaseSample, uint64_t TestSample,
1952     const SampleOverlapStats &FuncOverlap) const {
1953   double BaseFrac = 0.0;
1954   double TestFrac = 0.0;
1955   if (FuncOverlap.BaseSample > 0)
1956     BaseFrac = static_cast<double>(BaseSample) / FuncOverlap.BaseSample;
1957   if (FuncOverlap.TestSample > 0)
1958     TestFrac = static_cast<double>(TestSample) / FuncOverlap.TestSample;
1959   return 1.0 - std::fabs(BaseFrac - TestFrac);
1960 }
1961 
1962 void SampleOverlapAggregator::updateHotBlockOverlap(uint64_t BaseSample,
1963                                                     uint64_t TestSample,
1964                                                     uint64_t HotBlockCount) {
1965   bool IsBaseHot = (BaseSample >= BaseHotThreshold);
1966   bool IsTestHot = (TestSample >= TestHotThreshold);
1967   if (!IsBaseHot && !IsTestHot)
1968     return;
1969 
1970   HotBlockOverlap.UnionCount += HotBlockCount;
1971   if (IsBaseHot)
1972     HotBlockOverlap.BaseCount += HotBlockCount;
1973   if (IsTestHot)
1974     HotBlockOverlap.TestCount += HotBlockCount;
1975   if (IsBaseHot && IsTestHot)
1976     HotBlockOverlap.OverlapCount += HotBlockCount;
1977 }
1978 
1979 void SampleOverlapAggregator::getHotFunctions(
1980     const FuncSampleStatsMap &ProfStats, FuncSampleStatsMap &HotFunc,
1981     uint64_t HotThreshold) const {
1982   for (const auto &F : ProfStats) {
1983     if (isFunctionHot(F.second, HotThreshold))
1984       HotFunc.emplace(F.first, F.second);
1985   }
1986 }
1987 
1988 void SampleOverlapAggregator::computeHotFuncOverlap() {
1989   FuncSampleStatsMap BaseHotFunc;
1990   getHotFunctions(BaseStats, BaseHotFunc, BaseHotThreshold);
1991   HotFuncOverlap.BaseCount = BaseHotFunc.size();
1992 
1993   FuncSampleStatsMap TestHotFunc;
1994   getHotFunctions(TestStats, TestHotFunc, TestHotThreshold);
1995   HotFuncOverlap.TestCount = TestHotFunc.size();
1996   HotFuncOverlap.UnionCount = HotFuncOverlap.TestCount;
1997 
1998   for (const auto &F : BaseHotFunc) {
1999     if (TestHotFunc.count(F.first))
2000       ++HotFuncOverlap.OverlapCount;
2001     else
2002       ++HotFuncOverlap.UnionCount;
2003   }
2004 }
2005 
2006 void SampleOverlapAggregator::updateOverlapStatsForFunction(
2007     uint64_t BaseSample, uint64_t TestSample, uint64_t HotBlockCount,
2008     SampleOverlapStats &FuncOverlap, double &Difference, MatchStatus Status) {
2009   assert(Status != MS_None &&
2010          "Match status should be updated before updating overlap statistics");
2011   if (Status == MS_FirstUnique) {
2012     TestSample = 0;
2013     FuncOverlap.BaseUniqueSample += BaseSample;
2014   } else if (Status == MS_SecondUnique) {
2015     BaseSample = 0;
2016     FuncOverlap.TestUniqueSample += TestSample;
2017   } else {
2018     ++FuncOverlap.OverlapCount;
2019   }
2020 
2021   FuncOverlap.UnionSample += std::max(BaseSample, TestSample);
2022   FuncOverlap.OverlapSample += std::min(BaseSample, TestSample);
2023   Difference +=
2024       1.0 - computeBlockSimilarity(BaseSample, TestSample, FuncOverlap);
2025   updateHotBlockOverlap(BaseSample, TestSample, HotBlockCount);
2026 }
2027 
2028 void SampleOverlapAggregator::updateForUnmatchedCallee(
2029     const sampleprof::FunctionSamples &Func, SampleOverlapStats &FuncOverlap,
2030     double &Difference, MatchStatus Status) {
2031   assert((Status == MS_FirstUnique || Status == MS_SecondUnique) &&
2032          "Status must be either of the two unmatched cases");
2033   FuncSampleStats FuncStats;
2034   if (Status == MS_FirstUnique) {
2035     getFuncSampleStats(Func, FuncStats, BaseHotThreshold);
2036     updateOverlapStatsForFunction(FuncStats.SampleSum, 0,
2037                                   FuncStats.HotBlockCount, FuncOverlap,
2038                                   Difference, Status);
2039   } else {
2040     getFuncSampleStats(Func, FuncStats, TestHotThreshold);
2041     updateOverlapStatsForFunction(0, FuncStats.SampleSum,
2042                                   FuncStats.HotBlockCount, FuncOverlap,
2043                                   Difference, Status);
2044   }
2045 }
2046 
2047 double SampleOverlapAggregator::computeSampleFunctionInternalOverlap(
2048     const sampleprof::FunctionSamples &BaseFunc,
2049     const sampleprof::FunctionSamples &TestFunc,
2050     SampleOverlapStats &FuncOverlap) {
2051 
2052   using namespace sampleprof;
2053 
2054   double Difference = 0;
2055 
2056   // Accumulate Difference for regular line/block samples in the function.
2057   // We match them through sort-merge join algorithm because
2058   // FunctionSamples::getBodySamples() returns a map of sample counters ordered
2059   // by their offsets.
2060   MatchStep<BodySampleMap::const_iterator> BlockIterStep(
2061       BaseFunc.getBodySamples().cbegin(), BaseFunc.getBodySamples().cend(),
2062       TestFunc.getBodySamples().cbegin(), TestFunc.getBodySamples().cend());
2063   BlockIterStep.updateOneStep();
2064   while (!BlockIterStep.areBothFinished()) {
2065     uint64_t BaseSample =
2066         BlockIterStep.isFirstFinished()
2067             ? 0
2068             : BlockIterStep.getFirstIter()->second.getSamples();
2069     uint64_t TestSample =
2070         BlockIterStep.isSecondFinished()
2071             ? 0
2072             : BlockIterStep.getSecondIter()->second.getSamples();
2073     updateOverlapStatsForFunction(BaseSample, TestSample, 1, FuncOverlap,
2074                                   Difference, BlockIterStep.getMatchStatus());
2075 
2076     BlockIterStep.updateOneStep();
2077   }
2078 
2079   // Accumulate Difference for callsite lines in the function. We match
2080   // them through sort-merge algorithm because
2081   // FunctionSamples::getCallsiteSamples() returns a map of callsite records
2082   // ordered by their offsets.
2083   MatchStep<CallsiteSampleMap::const_iterator> CallsiteIterStep(
2084       BaseFunc.getCallsiteSamples().cbegin(),
2085       BaseFunc.getCallsiteSamples().cend(),
2086       TestFunc.getCallsiteSamples().cbegin(),
2087       TestFunc.getCallsiteSamples().cend());
2088   CallsiteIterStep.updateOneStep();
2089   while (!CallsiteIterStep.areBothFinished()) {
2090     MatchStatus CallsiteStepStatus = CallsiteIterStep.getMatchStatus();
2091     assert(CallsiteStepStatus != MS_None &&
2092            "Match status should be updated before entering loop body");
2093 
2094     if (CallsiteStepStatus != MS_Match) {
2095       auto Callsite = (CallsiteStepStatus == MS_FirstUnique)
2096                           ? CallsiteIterStep.getFirstIter()
2097                           : CallsiteIterStep.getSecondIter();
2098       for (const auto &F : Callsite->second)
2099         updateForUnmatchedCallee(F.second, FuncOverlap, Difference,
2100                                  CallsiteStepStatus);
2101     } else {
2102       // There may be multiple inlinees at the same offset, so we need to try
2103       // matching all of them. This match is implemented through sort-merge
2104       // algorithm because callsite records at the same offset are ordered by
2105       // function names.
2106       MatchStep<FunctionSamplesMap::const_iterator> CalleeIterStep(
2107           CallsiteIterStep.getFirstIter()->second.cbegin(),
2108           CallsiteIterStep.getFirstIter()->second.cend(),
2109           CallsiteIterStep.getSecondIter()->second.cbegin(),
2110           CallsiteIterStep.getSecondIter()->second.cend());
2111       CalleeIterStep.updateOneStep();
2112       while (!CalleeIterStep.areBothFinished()) {
2113         MatchStatus CalleeStepStatus = CalleeIterStep.getMatchStatus();
2114         if (CalleeStepStatus != MS_Match) {
2115           auto Callee = (CalleeStepStatus == MS_FirstUnique)
2116                             ? CalleeIterStep.getFirstIter()
2117                             : CalleeIterStep.getSecondIter();
2118           updateForUnmatchedCallee(Callee->second, FuncOverlap, Difference,
2119                                    CalleeStepStatus);
2120         } else {
2121           // An inlined function can contain other inlinees inside, so compute
2122           // the Difference recursively.
2123           Difference += 2.0 - 2 * computeSampleFunctionInternalOverlap(
2124                                       CalleeIterStep.getFirstIter()->second,
2125                                       CalleeIterStep.getSecondIter()->second,
2126                                       FuncOverlap);
2127         }
2128         CalleeIterStep.updateOneStep();
2129       }
2130     }
2131     CallsiteIterStep.updateOneStep();
2132   }
2133 
2134   // Difference reflects the total differences of line/block samples in this
2135   // function and ranges in [0.0f to 2.0f]. Take (2.0 - Difference) / 2 to
2136   // reflect the similarity between function profiles in [0.0f to 1.0f].
2137   return (2.0 - Difference) / 2;
2138 }
2139 
2140 double SampleOverlapAggregator::weightForFuncSimilarity(
2141     double FuncInternalSimilarity, uint64_t BaseFuncSample,
2142     uint64_t TestFuncSample) const {
2143   // Compute the weight as the distance between the function weights in two
2144   // profiles.
2145   double BaseFrac = 0.0;
2146   double TestFrac = 0.0;
2147   assert(ProfOverlap.BaseSample > 0 &&
2148          "Total samples in base profile should be greater than 0");
2149   BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample;
2150   assert(ProfOverlap.TestSample > 0 &&
2151          "Total samples in test profile should be greater than 0");
2152   TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample;
2153   double WeightDistance = std::fabs(BaseFrac - TestFrac);
2154 
2155   // Take WeightDistance into the similarity.
2156   return FuncInternalSimilarity * (1 - WeightDistance);
2157 }
2158 
2159 double
2160 SampleOverlapAggregator::weightByImportance(double FuncSimilarity,
2161                                             uint64_t BaseFuncSample,
2162                                             uint64_t TestFuncSample) const {
2163 
2164   double BaseFrac = 0.0;
2165   double TestFrac = 0.0;
2166   assert(ProfOverlap.BaseSample > 0 &&
2167          "Total samples in base profile should be greater than 0");
2168   BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample / 2.0;
2169   assert(ProfOverlap.TestSample > 0 &&
2170          "Total samples in test profile should be greater than 0");
2171   TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample / 2.0;
2172   return FuncSimilarity * (BaseFrac + TestFrac);
2173 }
2174 
2175 double SampleOverlapAggregator::computeSampleFunctionOverlap(
2176     const sampleprof::FunctionSamples *BaseFunc,
2177     const sampleprof::FunctionSamples *TestFunc,
2178     SampleOverlapStats *FuncOverlap, uint64_t BaseFuncSample,
2179     uint64_t TestFuncSample) {
2180   // Default function internal similarity before weighted, meaning two functions
2181   // has no overlap.
2182   const double DefaultFuncInternalSimilarity = 0;
2183   double FuncSimilarity;
2184   double FuncInternalSimilarity;
2185 
2186   // If BaseFunc or TestFunc is nullptr, it means the functions do not overlap.
2187   // In this case, we use DefaultFuncInternalSimilarity as the function internal
2188   // similarity.
2189   if (!BaseFunc || !TestFunc) {
2190     FuncInternalSimilarity = DefaultFuncInternalSimilarity;
2191   } else {
2192     assert(FuncOverlap != nullptr &&
2193            "FuncOverlap should be provided in this case");
2194     FuncInternalSimilarity = computeSampleFunctionInternalOverlap(
2195         *BaseFunc, *TestFunc, *FuncOverlap);
2196     // Now, FuncInternalSimilarity may be a little less than 0 due to
2197     // imprecision of floating point accumulations. Make it zero if the
2198     // difference is below Epsilon.
2199     FuncInternalSimilarity = (std::fabs(FuncInternalSimilarity - 0) < Epsilon)
2200                                  ? 0
2201                                  : FuncInternalSimilarity;
2202   }
2203   FuncSimilarity = weightForFuncSimilarity(FuncInternalSimilarity,
2204                                            BaseFuncSample, TestFuncSample);
2205   return FuncSimilarity;
2206 }
2207 
2208 void SampleOverlapAggregator::computeSampleProfileOverlap(raw_fd_ostream &OS) {
2209   using namespace sampleprof;
2210 
2211   std::unordered_map<SampleContext, const FunctionSamples *,
2212                      SampleContext::Hash>
2213       BaseFuncProf;
2214   const auto &BaseProfiles = BaseReader->getProfiles();
2215   for (const auto &BaseFunc : BaseProfiles) {
2216     BaseFuncProf.emplace(BaseFunc.second.getContext(), &(BaseFunc.second));
2217   }
2218   ProfOverlap.UnionCount = BaseFuncProf.size();
2219 
2220   const auto &TestProfiles = TestReader->getProfiles();
2221   for (const auto &TestFunc : TestProfiles) {
2222     SampleOverlapStats FuncOverlap;
2223     FuncOverlap.TestName = TestFunc.second.getContext();
2224     assert(TestStats.count(FuncOverlap.TestName) &&
2225            "TestStats should have records for all functions in test profile "
2226            "except inlinees");
2227     FuncOverlap.TestSample = TestStats[FuncOverlap.TestName].SampleSum;
2228 
2229     bool Matched = false;
2230     const auto Match = BaseFuncProf.find(FuncOverlap.TestName);
2231     if (Match == BaseFuncProf.end()) {
2232       const FuncSampleStats &FuncStats = TestStats[FuncOverlap.TestName];
2233       ++ProfOverlap.TestUniqueCount;
2234       ProfOverlap.TestUniqueSample += FuncStats.SampleSum;
2235       FuncOverlap.TestUniqueSample = FuncStats.SampleSum;
2236 
2237       updateHotBlockOverlap(0, FuncStats.SampleSum, FuncStats.HotBlockCount);
2238 
2239       double FuncSimilarity = computeSampleFunctionOverlap(
2240           nullptr, nullptr, nullptr, 0, FuncStats.SampleSum);
2241       ProfOverlap.Similarity +=
2242           weightByImportance(FuncSimilarity, 0, FuncStats.SampleSum);
2243 
2244       ++ProfOverlap.UnionCount;
2245       ProfOverlap.UnionSample += FuncStats.SampleSum;
2246     } else {
2247       ++ProfOverlap.OverlapCount;
2248 
2249       // Two functions match with each other. Compute function-level overlap and
2250       // aggregate them into profile-level overlap.
2251       FuncOverlap.BaseName = Match->second->getContext();
2252       assert(BaseStats.count(FuncOverlap.BaseName) &&
2253              "BaseStats should have records for all functions in base profile "
2254              "except inlinees");
2255       FuncOverlap.BaseSample = BaseStats[FuncOverlap.BaseName].SampleSum;
2256 
2257       FuncOverlap.Similarity = computeSampleFunctionOverlap(
2258           Match->second, &TestFunc.second, &FuncOverlap, FuncOverlap.BaseSample,
2259           FuncOverlap.TestSample);
2260       ProfOverlap.Similarity +=
2261           weightByImportance(FuncOverlap.Similarity, FuncOverlap.BaseSample,
2262                              FuncOverlap.TestSample);
2263       ProfOverlap.OverlapSample += FuncOverlap.OverlapSample;
2264       ProfOverlap.UnionSample += FuncOverlap.UnionSample;
2265 
2266       // Accumulate the percentage of base unique and test unique samples into
2267       // ProfOverlap.
2268       ProfOverlap.BaseUniqueSample += FuncOverlap.BaseUniqueSample;
2269       ProfOverlap.TestUniqueSample += FuncOverlap.TestUniqueSample;
2270 
2271       // Remove matched base functions for later reporting functions not found
2272       // in test profile.
2273       BaseFuncProf.erase(Match);
2274       Matched = true;
2275     }
2276 
2277     // Print function-level similarity information if specified by options.
2278     assert(TestStats.count(FuncOverlap.TestName) &&
2279            "TestStats should have records for all functions in test profile "
2280            "except inlinees");
2281     if (TestStats[FuncOverlap.TestName].MaxSample >= FuncFilter.ValueCutoff ||
2282         (Matched && FuncOverlap.Similarity < LowSimilarityThreshold) ||
2283         (Matched && !FuncFilter.NameFilter.empty() &&
2284          FuncOverlap.BaseName.toString().find(FuncFilter.NameFilter) !=
2285              std::string::npos)) {
2286       assert(ProfOverlap.BaseSample > 0 &&
2287              "Total samples in base profile should be greater than 0");
2288       FuncOverlap.BaseWeight =
2289           static_cast<double>(FuncOverlap.BaseSample) / ProfOverlap.BaseSample;
2290       assert(ProfOverlap.TestSample > 0 &&
2291              "Total samples in test profile should be greater than 0");
2292       FuncOverlap.TestWeight =
2293           static_cast<double>(FuncOverlap.TestSample) / ProfOverlap.TestSample;
2294       FuncSimilarityDump.emplace(FuncOverlap.BaseWeight, FuncOverlap);
2295     }
2296   }
2297 
2298   // Traverse through functions in base profile but not in test profile.
2299   for (const auto &F : BaseFuncProf) {
2300     assert(BaseStats.count(F.second->getContext()) &&
2301            "BaseStats should have records for all functions in base profile "
2302            "except inlinees");
2303     const FuncSampleStats &FuncStats = BaseStats[F.second->getContext()];
2304     ++ProfOverlap.BaseUniqueCount;
2305     ProfOverlap.BaseUniqueSample += FuncStats.SampleSum;
2306 
2307     updateHotBlockOverlap(FuncStats.SampleSum, 0, FuncStats.HotBlockCount);
2308 
2309     double FuncSimilarity = computeSampleFunctionOverlap(
2310         nullptr, nullptr, nullptr, FuncStats.SampleSum, 0);
2311     ProfOverlap.Similarity +=
2312         weightByImportance(FuncSimilarity, FuncStats.SampleSum, 0);
2313 
2314     ProfOverlap.UnionSample += FuncStats.SampleSum;
2315   }
2316 
2317   // Now, ProfSimilarity may be a little greater than 1 due to imprecision
2318   // of floating point accumulations. Make it 1.0 if the difference is below
2319   // Epsilon.
2320   ProfOverlap.Similarity = (std::fabs(ProfOverlap.Similarity - 1) < Epsilon)
2321                                ? 1
2322                                : ProfOverlap.Similarity;
2323 
2324   computeHotFuncOverlap();
2325 }
2326 
2327 void SampleOverlapAggregator::initializeSampleProfileOverlap() {
2328   const auto &BaseProf = BaseReader->getProfiles();
2329   for (const auto &I : BaseProf) {
2330     ++ProfOverlap.BaseCount;
2331     FuncSampleStats FuncStats;
2332     getFuncSampleStats(I.second, FuncStats, BaseHotThreshold);
2333     ProfOverlap.BaseSample += FuncStats.SampleSum;
2334     BaseStats.emplace(I.second.getContext(), FuncStats);
2335   }
2336 
2337   const auto &TestProf = TestReader->getProfiles();
2338   for (const auto &I : TestProf) {
2339     ++ProfOverlap.TestCount;
2340     FuncSampleStats FuncStats;
2341     getFuncSampleStats(I.second, FuncStats, TestHotThreshold);
2342     ProfOverlap.TestSample += FuncStats.SampleSum;
2343     TestStats.emplace(I.second.getContext(), FuncStats);
2344   }
2345 
2346   ProfOverlap.BaseName = StringRef(BaseFilename);
2347   ProfOverlap.TestName = StringRef(TestFilename);
2348 }
2349 
2350 void SampleOverlapAggregator::dumpFuncSimilarity(raw_fd_ostream &OS) const {
2351   using namespace sampleprof;
2352 
2353   if (FuncSimilarityDump.empty())
2354     return;
2355 
2356   formatted_raw_ostream FOS(OS);
2357   FOS << "Function-level details:\n";
2358   FOS << "Base weight";
2359   FOS.PadToColumn(TestWeightCol);
2360   FOS << "Test weight";
2361   FOS.PadToColumn(SimilarityCol);
2362   FOS << "Similarity";
2363   FOS.PadToColumn(OverlapCol);
2364   FOS << "Overlap";
2365   FOS.PadToColumn(BaseUniqueCol);
2366   FOS << "Base unique";
2367   FOS.PadToColumn(TestUniqueCol);
2368   FOS << "Test unique";
2369   FOS.PadToColumn(BaseSampleCol);
2370   FOS << "Base samples";
2371   FOS.PadToColumn(TestSampleCol);
2372   FOS << "Test samples";
2373   FOS.PadToColumn(FuncNameCol);
2374   FOS << "Function name\n";
2375   for (const auto &F : FuncSimilarityDump) {
2376     double OverlapPercent =
2377         F.second.UnionSample > 0
2378             ? static_cast<double>(F.second.OverlapSample) / F.second.UnionSample
2379             : 0;
2380     double BaseUniquePercent =
2381         F.second.BaseSample > 0
2382             ? static_cast<double>(F.second.BaseUniqueSample) /
2383                   F.second.BaseSample
2384             : 0;
2385     double TestUniquePercent =
2386         F.second.TestSample > 0
2387             ? static_cast<double>(F.second.TestUniqueSample) /
2388                   F.second.TestSample
2389             : 0;
2390 
2391     FOS << format("%.2f%%", F.second.BaseWeight * 100);
2392     FOS.PadToColumn(TestWeightCol);
2393     FOS << format("%.2f%%", F.second.TestWeight * 100);
2394     FOS.PadToColumn(SimilarityCol);
2395     FOS << format("%.2f%%", F.second.Similarity * 100);
2396     FOS.PadToColumn(OverlapCol);
2397     FOS << format("%.2f%%", OverlapPercent * 100);
2398     FOS.PadToColumn(BaseUniqueCol);
2399     FOS << format("%.2f%%", BaseUniquePercent * 100);
2400     FOS.PadToColumn(TestUniqueCol);
2401     FOS << format("%.2f%%", TestUniquePercent * 100);
2402     FOS.PadToColumn(BaseSampleCol);
2403     FOS << F.second.BaseSample;
2404     FOS.PadToColumn(TestSampleCol);
2405     FOS << F.second.TestSample;
2406     FOS.PadToColumn(FuncNameCol);
2407     FOS << F.second.TestName.toString() << "\n";
2408   }
2409 }
2410 
2411 void SampleOverlapAggregator::dumpProgramSummary(raw_fd_ostream &OS) const {
2412   OS << "Profile overlap infomation for base_profile: "
2413      << ProfOverlap.BaseName.toString()
2414      << " and test_profile: " << ProfOverlap.TestName.toString()
2415      << "\nProgram level:\n";
2416 
2417   OS << "  Whole program profile similarity: "
2418      << format("%.3f%%", ProfOverlap.Similarity * 100) << "\n";
2419 
2420   assert(ProfOverlap.UnionSample > 0 &&
2421          "Total samples in two profile should be greater than 0");
2422   double OverlapPercent =
2423       static_cast<double>(ProfOverlap.OverlapSample) / ProfOverlap.UnionSample;
2424   assert(ProfOverlap.BaseSample > 0 &&
2425          "Total samples in base profile should be greater than 0");
2426   double BaseUniquePercent = static_cast<double>(ProfOverlap.BaseUniqueSample) /
2427                              ProfOverlap.BaseSample;
2428   assert(ProfOverlap.TestSample > 0 &&
2429          "Total samples in test profile should be greater than 0");
2430   double TestUniquePercent = static_cast<double>(ProfOverlap.TestUniqueSample) /
2431                              ProfOverlap.TestSample;
2432 
2433   OS << "  Whole program sample overlap: "
2434      << format("%.3f%%", OverlapPercent * 100) << "\n";
2435   OS << "    percentage of samples unique in base profile: "
2436      << format("%.3f%%", BaseUniquePercent * 100) << "\n";
2437   OS << "    percentage of samples unique in test profile: "
2438      << format("%.3f%%", TestUniquePercent * 100) << "\n";
2439   OS << "    total samples in base profile: " << ProfOverlap.BaseSample << "\n"
2440      << "    total samples in test profile: " << ProfOverlap.TestSample << "\n";
2441 
2442   assert(ProfOverlap.UnionCount > 0 &&
2443          "There should be at least one function in two input profiles");
2444   double FuncOverlapPercent =
2445       static_cast<double>(ProfOverlap.OverlapCount) / ProfOverlap.UnionCount;
2446   OS << "  Function overlap: " << format("%.3f%%", FuncOverlapPercent * 100)
2447      << "\n";
2448   OS << "    overlap functions: " << ProfOverlap.OverlapCount << "\n";
2449   OS << "    functions unique in base profile: " << ProfOverlap.BaseUniqueCount
2450      << "\n";
2451   OS << "    functions unique in test profile: " << ProfOverlap.TestUniqueCount
2452      << "\n";
2453 }
2454 
2455 void SampleOverlapAggregator::dumpHotFuncAndBlockOverlap(
2456     raw_fd_ostream &OS) const {
2457   assert(HotFuncOverlap.UnionCount > 0 &&
2458          "There should be at least one hot function in two input profiles");
2459   OS << "  Hot-function overlap: "
2460      << format("%.3f%%", static_cast<double>(HotFuncOverlap.OverlapCount) /
2461                              HotFuncOverlap.UnionCount * 100)
2462      << "\n";
2463   OS << "    overlap hot functions: " << HotFuncOverlap.OverlapCount << "\n";
2464   OS << "    hot functions unique in base profile: "
2465      << HotFuncOverlap.BaseCount - HotFuncOverlap.OverlapCount << "\n";
2466   OS << "    hot functions unique in test profile: "
2467      << HotFuncOverlap.TestCount - HotFuncOverlap.OverlapCount << "\n";
2468 
2469   assert(HotBlockOverlap.UnionCount > 0 &&
2470          "There should be at least one hot block in two input profiles");
2471   OS << "  Hot-block overlap: "
2472      << format("%.3f%%", static_cast<double>(HotBlockOverlap.OverlapCount) /
2473                              HotBlockOverlap.UnionCount * 100)
2474      << "\n";
2475   OS << "    overlap hot blocks: " << HotBlockOverlap.OverlapCount << "\n";
2476   OS << "    hot blocks unique in base profile: "
2477      << HotBlockOverlap.BaseCount - HotBlockOverlap.OverlapCount << "\n";
2478   OS << "    hot blocks unique in test profile: "
2479      << HotBlockOverlap.TestCount - HotBlockOverlap.OverlapCount << "\n";
2480 }
2481 
2482 std::error_code SampleOverlapAggregator::loadProfiles() {
2483   using namespace sampleprof;
2484 
2485   LLVMContext Context;
2486   auto FS = vfs::getRealFileSystem();
2487   auto BaseReaderOrErr = SampleProfileReader::create(BaseFilename, Context, *FS,
2488                                                      FSDiscriminatorPassOption);
2489   if (std::error_code EC = BaseReaderOrErr.getError())
2490     exitWithErrorCode(EC, BaseFilename);
2491 
2492   auto TestReaderOrErr = SampleProfileReader::create(TestFilename, Context, *FS,
2493                                                      FSDiscriminatorPassOption);
2494   if (std::error_code EC = TestReaderOrErr.getError())
2495     exitWithErrorCode(EC, TestFilename);
2496 
2497   BaseReader = std::move(BaseReaderOrErr.get());
2498   TestReader = std::move(TestReaderOrErr.get());
2499 
2500   if (std::error_code EC = BaseReader->read())
2501     exitWithErrorCode(EC, BaseFilename);
2502   if (std::error_code EC = TestReader->read())
2503     exitWithErrorCode(EC, TestFilename);
2504   if (BaseReader->profileIsProbeBased() != TestReader->profileIsProbeBased())
2505     exitWithError(
2506         "cannot compare probe-based profile with non-probe-based profile");
2507   if (BaseReader->profileIsCS() != TestReader->profileIsCS())
2508     exitWithError("cannot compare CS profile with non-CS profile");
2509 
2510   // Load BaseHotThreshold and TestHotThreshold as 99-percentile threshold in
2511   // profile summary.
2512   ProfileSummary &BasePS = BaseReader->getSummary();
2513   ProfileSummary &TestPS = TestReader->getSummary();
2514   BaseHotThreshold =
2515       ProfileSummaryBuilder::getHotCountThreshold(BasePS.getDetailedSummary());
2516   TestHotThreshold =
2517       ProfileSummaryBuilder::getHotCountThreshold(TestPS.getDetailedSummary());
2518 
2519   return std::error_code();
2520 }
2521 
2522 void overlapSampleProfile(const std::string &BaseFilename,
2523                           const std::string &TestFilename,
2524                           const OverlapFuncFilters &FuncFilter,
2525                           uint64_t SimilarityCutoff, raw_fd_ostream &OS) {
2526   using namespace sampleprof;
2527 
2528   // We use 0.000005 to initialize OverlapAggr.Epsilon because the final metrics
2529   // report 2--3 places after decimal point in percentage numbers.
2530   SampleOverlapAggregator OverlapAggr(
2531       BaseFilename, TestFilename,
2532       static_cast<double>(SimilarityCutoff) / 1000000, 0.000005, FuncFilter);
2533   if (std::error_code EC = OverlapAggr.loadProfiles())
2534     exitWithErrorCode(EC);
2535 
2536   OverlapAggr.initializeSampleProfileOverlap();
2537   if (OverlapAggr.detectZeroSampleProfile(OS))
2538     return;
2539 
2540   OverlapAggr.computeSampleProfileOverlap(OS);
2541 
2542   OverlapAggr.dumpProgramSummary(OS);
2543   OverlapAggr.dumpHotFuncAndBlockOverlap(OS);
2544   OverlapAggr.dumpFuncSimilarity(OS);
2545 }
2546 
2547 static int overlap_main(int argc, const char *argv[]) {
2548   std::error_code EC;
2549   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF);
2550   if (EC)
2551     exitWithErrorCode(EC, OutputFilename);
2552 
2553   if (ProfileKind == instr)
2554     overlapInstrProfile(BaseFilename, TestFilename,
2555                         OverlapFuncFilters{OverlapValueCutoff, FuncNameFilter},
2556                         OS, IsCS);
2557   else
2558     overlapSampleProfile(BaseFilename, TestFilename,
2559                          OverlapFuncFilters{OverlapValueCutoff, FuncNameFilter},
2560                          SimilarityCutoff, OS);
2561 
2562   return 0;
2563 }
2564 
2565 namespace {
2566 struct ValueSitesStats {
2567   ValueSitesStats() = default;
2568   uint64_t TotalNumValueSites = 0;
2569   uint64_t TotalNumValueSitesWithValueProfile = 0;
2570   uint64_t TotalNumValues = 0;
2571   std::vector<unsigned> ValueSitesHistogram;
2572 };
2573 } // namespace
2574 
2575 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
2576                                   ValueSitesStats &Stats, raw_fd_ostream &OS,
2577                                   InstrProfSymtab *Symtab) {
2578   uint32_t NS = Func.getNumValueSites(VK);
2579   Stats.TotalNumValueSites += NS;
2580   for (size_t I = 0; I < NS; ++I) {
2581     uint32_t NV = Func.getNumValueDataForSite(VK, I);
2582     std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
2583     Stats.TotalNumValues += NV;
2584     if (NV) {
2585       Stats.TotalNumValueSitesWithValueProfile++;
2586       if (NV > Stats.ValueSitesHistogram.size())
2587         Stats.ValueSitesHistogram.resize(NV, 0);
2588       Stats.ValueSitesHistogram[NV - 1]++;
2589     }
2590 
2591     uint64_t SiteSum = 0;
2592     for (uint32_t V = 0; V < NV; V++)
2593       SiteSum += VD[V].Count;
2594     if (SiteSum == 0)
2595       SiteSum = 1;
2596 
2597     for (uint32_t V = 0; V < NV; V++) {
2598       OS << "\t[ " << format("%2u", I) << ", ";
2599       if (Symtab == nullptr)
2600         OS << format("%4" PRIu64, VD[V].Value);
2601       else
2602         OS << Symtab->getFuncOrVarName(VD[V].Value);
2603       OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
2604          << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
2605     }
2606   }
2607 }
2608 
2609 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
2610                                 ValueSitesStats &Stats) {
2611   OS << "  Total number of sites: " << Stats.TotalNumValueSites << "\n";
2612   OS << "  Total number of sites with values: "
2613      << Stats.TotalNumValueSitesWithValueProfile << "\n";
2614   OS << "  Total number of profiled values: " << Stats.TotalNumValues << "\n";
2615 
2616   OS << "  Value sites histogram:\n\tNumTargets, SiteCount\n";
2617   for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
2618     if (Stats.ValueSitesHistogram[I] > 0)
2619       OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
2620   }
2621 }
2622 
2623 static int showInstrProfile(ShowFormat SFormat, raw_fd_ostream &OS) {
2624   if (SFormat == ShowFormat::Json)
2625     exitWithError("JSON output is not supported for instr profiles");
2626   if (SFormat == ShowFormat::Yaml)
2627     exitWithError("YAML output is not supported for instr profiles");
2628   auto FS = vfs::getRealFileSystem();
2629   auto ReaderOrErr = InstrProfReader::create(Filename, *FS);
2630   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
2631   if (ShowDetailedSummary && Cutoffs.empty()) {
2632     Cutoffs = ProfileSummaryBuilder::DefaultCutoffs;
2633   }
2634   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
2635   if (Error E = ReaderOrErr.takeError())
2636     exitWithError(std::move(E), Filename);
2637 
2638   auto Reader = std::move(ReaderOrErr.get());
2639   bool IsIRInstr = Reader->isIRLevelProfile();
2640   size_t ShownFunctions = 0;
2641   size_t BelowCutoffFunctions = 0;
2642   int NumVPKind = IPVK_Last - IPVK_First + 1;
2643   std::vector<ValueSitesStats> VPStats(NumVPKind);
2644 
2645   auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
2646                    const std::pair<std::string, uint64_t> &v2) {
2647     return v1.second > v2.second;
2648   };
2649 
2650   std::priority_queue<std::pair<std::string, uint64_t>,
2651                       std::vector<std::pair<std::string, uint64_t>>,
2652                       decltype(MinCmp)>
2653       HottestFuncs(MinCmp);
2654 
2655   if (!TextFormat && OnlyListBelow) {
2656     OS << "The list of functions with the maximum counter less than "
2657        << ShowValueCutoff << ":\n";
2658   }
2659 
2660   // Add marker so that IR-level instrumentation round-trips properly.
2661   if (TextFormat && IsIRInstr)
2662     OS << ":ir\n";
2663 
2664   for (const auto &Func : *Reader) {
2665     if (Reader->isIRLevelProfile()) {
2666       bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
2667       if (FuncIsCS != ShowCS)
2668         continue;
2669     }
2670     bool Show = ShowAllFunctions ||
2671                 (!FuncNameFilter.empty() && Func.Name.contains(FuncNameFilter));
2672 
2673     bool doTextFormatDump = (Show && TextFormat);
2674 
2675     if (doTextFormatDump) {
2676       InstrProfSymtab &Symtab = Reader->getSymtab();
2677       InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
2678                                          OS);
2679       continue;
2680     }
2681 
2682     assert(Func.Counts.size() > 0 && "function missing entry counter");
2683     Builder.addRecord(Func);
2684 
2685     if (ShowCovered) {
2686       if (llvm::any_of(Func.Counts, [](uint64_t C) { return C; }))
2687         OS << Func.Name << "\n";
2688       continue;
2689     }
2690 
2691     uint64_t FuncMax = 0;
2692     uint64_t FuncSum = 0;
2693 
2694     auto PseudoKind = Func.getCountPseudoKind();
2695     if (PseudoKind != InstrProfRecord::NotPseudo) {
2696       if (Show) {
2697         if (!ShownFunctions)
2698           OS << "Counters:\n";
2699         ++ShownFunctions;
2700         OS << "  " << Func.Name << ":\n"
2701            << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
2702            << "    Counters: " << Func.Counts.size();
2703         if (PseudoKind == InstrProfRecord::PseudoHot)
2704           OS << "    <PseudoHot>\n";
2705         else if (PseudoKind == InstrProfRecord::PseudoWarm)
2706           OS << "    <PseudoWarm>\n";
2707         else
2708           llvm_unreachable("Unknown PseudoKind");
2709       }
2710       continue;
2711     }
2712 
2713     for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
2714       FuncMax = std::max(FuncMax, Func.Counts[I]);
2715       FuncSum += Func.Counts[I];
2716     }
2717 
2718     if (FuncMax < ShowValueCutoff) {
2719       ++BelowCutoffFunctions;
2720       if (OnlyListBelow) {
2721         OS << "  " << Func.Name << ": (Max = " << FuncMax
2722            << " Sum = " << FuncSum << ")\n";
2723       }
2724       continue;
2725     } else if (OnlyListBelow)
2726       continue;
2727 
2728     if (TopNFunctions) {
2729       if (HottestFuncs.size() == TopNFunctions) {
2730         if (HottestFuncs.top().second < FuncMax) {
2731           HottestFuncs.pop();
2732           HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
2733         }
2734       } else
2735         HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
2736     }
2737 
2738     if (Show) {
2739       if (!ShownFunctions)
2740         OS << "Counters:\n";
2741 
2742       ++ShownFunctions;
2743 
2744       OS << "  " << Func.Name << ":\n"
2745          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
2746          << "    Counters: " << Func.Counts.size() << "\n";
2747       if (!IsIRInstr)
2748         OS << "    Function count: " << Func.Counts[0] << "\n";
2749 
2750       if (ShowIndirectCallTargets)
2751         OS << "    Indirect Call Site Count: "
2752            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
2753 
2754       uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
2755       if (ShowMemOPSizes && NumMemOPCalls > 0)
2756         OS << "    Number of Memory Intrinsics Calls: " << NumMemOPCalls
2757            << "\n";
2758 
2759       if (ShowCounts) {
2760         OS << "    Block counts: [";
2761         size_t Start = (IsIRInstr ? 0 : 1);
2762         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
2763           OS << (I == Start ? "" : ", ") << Func.Counts[I];
2764         }
2765         OS << "]\n";
2766       }
2767 
2768       if (ShowIndirectCallTargets) {
2769         OS << "    Indirect Target Results:\n";
2770         traverseAllValueSites(Func, IPVK_IndirectCallTarget,
2771                               VPStats[IPVK_IndirectCallTarget], OS,
2772                               &(Reader->getSymtab()));
2773       }
2774 
2775       if (ShowMemOPSizes && NumMemOPCalls > 0) {
2776         OS << "    Memory Intrinsic Size Results:\n";
2777         traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
2778                               nullptr);
2779       }
2780     }
2781   }
2782   if (Reader->hasError())
2783     exitWithError(Reader->getError(), Filename);
2784 
2785   if (TextFormat || ShowCovered)
2786     return 0;
2787   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
2788   bool IsIR = Reader->isIRLevelProfile();
2789   OS << "Instrumentation level: " << (IsIR ? "IR" : "Front-end");
2790   if (IsIR)
2791     OS << "  entry_first = " << Reader->instrEntryBBEnabled();
2792   OS << "\n";
2793   if (ShowAllFunctions || !FuncNameFilter.empty())
2794     OS << "Functions shown: " << ShownFunctions << "\n";
2795   OS << "Total functions: " << PS->getNumFunctions() << "\n";
2796   if (ShowValueCutoff > 0) {
2797     OS << "Number of functions with maximum count (< " << ShowValueCutoff
2798        << "): " << BelowCutoffFunctions << "\n";
2799     OS << "Number of functions with maximum count (>= " << ShowValueCutoff
2800        << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
2801   }
2802   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
2803   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
2804 
2805   if (TopNFunctions) {
2806     std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
2807     while (!HottestFuncs.empty()) {
2808       SortedHottestFuncs.emplace_back(HottestFuncs.top());
2809       HottestFuncs.pop();
2810     }
2811     OS << "Top " << TopNFunctions
2812        << " functions with the largest internal block counts: \n";
2813     for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
2814       OS << "  " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
2815   }
2816 
2817   if (ShownFunctions && ShowIndirectCallTargets) {
2818     OS << "Statistics for indirect call sites profile:\n";
2819     showValueSitesStats(OS, IPVK_IndirectCallTarget,
2820                         VPStats[IPVK_IndirectCallTarget]);
2821   }
2822 
2823   if (ShownFunctions && ShowMemOPSizes) {
2824     OS << "Statistics for memory intrinsic calls sizes profile:\n";
2825     showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
2826   }
2827 
2828   if (ShowDetailedSummary) {
2829     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
2830     OS << "Total count: " << PS->getTotalCount() << "\n";
2831     PS->printDetailedSummary(OS);
2832   }
2833 
2834   if (ShowBinaryIds)
2835     if (Error E = Reader->printBinaryIds(OS))
2836       exitWithError(std::move(E), Filename);
2837 
2838   if (ShowProfileVersion)
2839     OS << "Profile version: " << Reader->getVersion() << "\n";
2840 
2841   if (ShowTemporalProfTraces) {
2842     auto &Traces = Reader->getTemporalProfTraces();
2843     OS << "Temporal Profile Traces (samples=" << Traces.size()
2844        << " seen=" << Reader->getTemporalProfTraceStreamSize() << "):\n";
2845     for (unsigned i = 0; i < Traces.size(); i++) {
2846       OS << "  Temporal Profile Trace " << i << " (weight=" << Traces[i].Weight
2847          << " count=" << Traces[i].FunctionNameRefs.size() << "):\n";
2848       for (auto &NameRef : Traces[i].FunctionNameRefs)
2849         OS << "    " << Reader->getSymtab().getFuncOrVarName(NameRef) << "\n";
2850     }
2851   }
2852 
2853   return 0;
2854 }
2855 
2856 static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
2857                             raw_fd_ostream &OS) {
2858   if (!Reader->dumpSectionInfo(OS)) {
2859     WithColor::warning() << "-show-sec-info-only is only supported for "
2860                          << "sample profile in extbinary format and is "
2861                          << "ignored for other formats.\n";
2862     return;
2863   }
2864 }
2865 
2866 namespace {
2867 struct HotFuncInfo {
2868   std::string FuncName;
2869   uint64_t TotalCount = 0;
2870   double TotalCountPercent = 0.0f;
2871   uint64_t MaxCount = 0;
2872   uint64_t EntryCount = 0;
2873 
2874   HotFuncInfo() = default;
2875 
2876   HotFuncInfo(StringRef FN, uint64_t TS, double TSP, uint64_t MS, uint64_t ES)
2877       : FuncName(FN.begin(), FN.end()), TotalCount(TS), TotalCountPercent(TSP),
2878         MaxCount(MS), EntryCount(ES) {}
2879 };
2880 } // namespace
2881 
2882 // Print out detailed information about hot functions in PrintValues vector.
2883 // Users specify titles and offset of every columns through ColumnTitle and
2884 // ColumnOffset. The size of ColumnTitle and ColumnOffset need to be the same
2885 // and at least 4. Besides, users can optionally give a HotFuncMetric string to
2886 // print out or let it be an empty string.
2887 static void dumpHotFunctionList(const std::vector<std::string> &ColumnTitle,
2888                                 const std::vector<int> &ColumnOffset,
2889                                 const std::vector<HotFuncInfo> &PrintValues,
2890                                 uint64_t HotFuncCount, uint64_t TotalFuncCount,
2891                                 uint64_t HotProfCount, uint64_t TotalProfCount,
2892                                 const std::string &HotFuncMetric,
2893                                 uint32_t TopNFunctions, raw_fd_ostream &OS) {
2894   assert(ColumnOffset.size() == ColumnTitle.size() &&
2895          "ColumnOffset and ColumnTitle should have the same size");
2896   assert(ColumnTitle.size() >= 4 &&
2897          "ColumnTitle should have at least 4 elements");
2898   assert(TotalFuncCount > 0 &&
2899          "There should be at least one function in the profile");
2900   double TotalProfPercent = 0;
2901   if (TotalProfCount > 0)
2902     TotalProfPercent = static_cast<double>(HotProfCount) / TotalProfCount * 100;
2903 
2904   formatted_raw_ostream FOS(OS);
2905   FOS << HotFuncCount << " out of " << TotalFuncCount
2906       << " functions with profile ("
2907       << format("%.2f%%",
2908                 (static_cast<double>(HotFuncCount) / TotalFuncCount * 100))
2909       << ") are considered hot functions";
2910   if (!HotFuncMetric.empty())
2911     FOS << " (" << HotFuncMetric << ")";
2912   FOS << ".\n";
2913   FOS << HotProfCount << " out of " << TotalProfCount << " profile counts ("
2914       << format("%.2f%%", TotalProfPercent) << ") are from hot functions.\n";
2915 
2916   for (size_t I = 0; I < ColumnTitle.size(); ++I) {
2917     FOS.PadToColumn(ColumnOffset[I]);
2918     FOS << ColumnTitle[I];
2919   }
2920   FOS << "\n";
2921 
2922   uint32_t Count = 0;
2923   for (const auto &R : PrintValues) {
2924     if (TopNFunctions && (Count++ == TopNFunctions))
2925       break;
2926     FOS.PadToColumn(ColumnOffset[0]);
2927     FOS << R.TotalCount << " (" << format("%.2f%%", R.TotalCountPercent) << ")";
2928     FOS.PadToColumn(ColumnOffset[1]);
2929     FOS << R.MaxCount;
2930     FOS.PadToColumn(ColumnOffset[2]);
2931     FOS << R.EntryCount;
2932     FOS.PadToColumn(ColumnOffset[3]);
2933     FOS << R.FuncName << "\n";
2934   }
2935 }
2936 
2937 static int showHotFunctionList(const sampleprof::SampleProfileMap &Profiles,
2938                                ProfileSummary &PS, uint32_t TopN,
2939                                raw_fd_ostream &OS) {
2940   using namespace sampleprof;
2941 
2942   const uint32_t HotFuncCutoff = 990000;
2943   auto &SummaryVector = PS.getDetailedSummary();
2944   uint64_t MinCountThreshold = 0;
2945   for (const ProfileSummaryEntry &SummaryEntry : SummaryVector) {
2946     if (SummaryEntry.Cutoff == HotFuncCutoff) {
2947       MinCountThreshold = SummaryEntry.MinCount;
2948       break;
2949     }
2950   }
2951 
2952   // Traverse all functions in the profile and keep only hot functions.
2953   // The following loop also calculates the sum of total samples of all
2954   // functions.
2955   std::multimap<uint64_t, std::pair<const FunctionSamples *, const uint64_t>,
2956                 std::greater<uint64_t>>
2957       HotFunc;
2958   uint64_t ProfileTotalSample = 0;
2959   uint64_t HotFuncSample = 0;
2960   uint64_t HotFuncCount = 0;
2961 
2962   for (const auto &I : Profiles) {
2963     FuncSampleStats FuncStats;
2964     const FunctionSamples &FuncProf = I.second;
2965     ProfileTotalSample += FuncProf.getTotalSamples();
2966     getFuncSampleStats(FuncProf, FuncStats, MinCountThreshold);
2967 
2968     if (isFunctionHot(FuncStats, MinCountThreshold)) {
2969       HotFunc.emplace(FuncProf.getTotalSamples(),
2970                       std::make_pair(&(I.second), FuncStats.MaxSample));
2971       HotFuncSample += FuncProf.getTotalSamples();
2972       ++HotFuncCount;
2973     }
2974   }
2975 
2976   std::vector<std::string> ColumnTitle{"Total sample (%)", "Max sample",
2977                                        "Entry sample", "Function name"};
2978   std::vector<int> ColumnOffset{0, 24, 42, 58};
2979   std::string Metric =
2980       std::string("max sample >= ") + std::to_string(MinCountThreshold);
2981   std::vector<HotFuncInfo> PrintValues;
2982   for (const auto &FuncPair : HotFunc) {
2983     const FunctionSamples &Func = *FuncPair.second.first;
2984     double TotalSamplePercent =
2985         (ProfileTotalSample > 0)
2986             ? (Func.getTotalSamples() * 100.0) / ProfileTotalSample
2987             : 0;
2988     PrintValues.emplace_back(
2989         HotFuncInfo(Func.getContext().toString(), Func.getTotalSamples(),
2990                     TotalSamplePercent, FuncPair.second.second,
2991                     Func.getHeadSamplesEstimate()));
2992   }
2993   dumpHotFunctionList(ColumnTitle, ColumnOffset, PrintValues, HotFuncCount,
2994                       Profiles.size(), HotFuncSample, ProfileTotalSample,
2995                       Metric, TopN, OS);
2996 
2997   return 0;
2998 }
2999 
3000 static int showSampleProfile(ShowFormat SFormat, raw_fd_ostream &OS) {
3001   if (SFormat == ShowFormat::Yaml)
3002     exitWithError("YAML output is not supported for sample profiles");
3003   using namespace sampleprof;
3004   LLVMContext Context;
3005   auto FS = vfs::getRealFileSystem();
3006   auto ReaderOrErr = SampleProfileReader::create(Filename, Context, *FS,
3007                                                  FSDiscriminatorPassOption);
3008   if (std::error_code EC = ReaderOrErr.getError())
3009     exitWithErrorCode(EC, Filename);
3010 
3011   auto Reader = std::move(ReaderOrErr.get());
3012   if (ShowSectionInfoOnly) {
3013     showSectionInfo(Reader.get(), OS);
3014     return 0;
3015   }
3016 
3017   if (std::error_code EC = Reader->read())
3018     exitWithErrorCode(EC, Filename);
3019 
3020   if (ShowAllFunctions || FuncNameFilter.empty()) {
3021     if (SFormat == ShowFormat::Json)
3022       Reader->dumpJson(OS);
3023     else
3024       Reader->dump(OS);
3025   } else {
3026     if (SFormat == ShowFormat::Json)
3027       exitWithError(
3028           "the JSON format is supported only when all functions are to "
3029           "be printed");
3030 
3031     // TODO: parse context string to support filtering by contexts.
3032     FunctionSamples *FS = Reader->getSamplesFor(StringRef(FuncNameFilter));
3033     Reader->dumpFunctionProfile(FS ? *FS : FunctionSamples(), OS);
3034   }
3035 
3036   if (ShowProfileSymbolList) {
3037     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
3038         Reader->getProfileSymbolList();
3039     ReaderList->dump(OS);
3040   }
3041 
3042   if (ShowDetailedSummary) {
3043     auto &PS = Reader->getSummary();
3044     PS.printSummary(OS);
3045     PS.printDetailedSummary(OS);
3046   }
3047 
3048   if (ShowHotFuncList || TopNFunctions)
3049     showHotFunctionList(Reader->getProfiles(), Reader->getSummary(),
3050                         TopNFunctions, OS);
3051 
3052   return 0;
3053 }
3054 
3055 static int showMemProfProfile(ShowFormat SFormat, raw_fd_ostream &OS) {
3056   if (SFormat == ShowFormat::Json)
3057     exitWithError("JSON output is not supported for MemProf");
3058   auto ReaderOr = llvm::memprof::RawMemProfReader::create(
3059       Filename, ProfiledBinary, /*KeepNames=*/true);
3060   if (Error E = ReaderOr.takeError())
3061     // Since the error can be related to the profile or the binary we do not
3062     // pass whence. Instead additional context is provided where necessary in
3063     // the error message.
3064     exitWithError(std::move(E), /*Whence*/ "");
3065 
3066   std::unique_ptr<llvm::memprof::RawMemProfReader> Reader(
3067       ReaderOr.get().release());
3068 
3069   Reader->printYAML(OS);
3070   return 0;
3071 }
3072 
3073 static int showDebugInfoCorrelation(const std::string &Filename,
3074                                     ShowFormat SFormat, raw_fd_ostream &OS) {
3075   if (SFormat == ShowFormat::Json)
3076     exitWithError("JSON output is not supported for debug info correlation");
3077   std::unique_ptr<InstrProfCorrelator> Correlator;
3078   if (auto Err =
3079           InstrProfCorrelator::get(Filename, InstrProfCorrelator::DEBUG_INFO)
3080               .moveInto(Correlator))
3081     exitWithError(std::move(Err), Filename);
3082   if (SFormat == ShowFormat::Yaml) {
3083     if (auto Err = Correlator->dumpYaml(MaxDbgCorrelationWarnings, OS))
3084       exitWithError(std::move(Err), Filename);
3085     return 0;
3086   }
3087 
3088   if (auto Err = Correlator->correlateProfileData(MaxDbgCorrelationWarnings))
3089     exitWithError(std::move(Err), Filename);
3090 
3091   InstrProfSymtab Symtab;
3092   if (auto Err = Symtab.create(
3093           StringRef(Correlator->getNamesPointer(), Correlator->getNamesSize())))
3094     exitWithError(std::move(Err), Filename);
3095 
3096   if (ShowProfileSymbolList)
3097     Symtab.dumpNames(OS);
3098   // TODO: Read "Profile Data Type" from debug info to compute and show how many
3099   // counters the section holds.
3100   if (ShowDetailedSummary)
3101     OS << "Counters section size: 0x"
3102        << Twine::utohexstr(Correlator->getCountersSectionSize()) << " bytes\n";
3103   OS << "Found " << Correlator->getDataSize() << " functions\n";
3104 
3105   return 0;
3106 }
3107 
3108 static int show_main(int argc, const char *argv[]) {
3109   if (Filename.empty() && DebugInfoFilename.empty())
3110     exitWithError(
3111         "the positional argument '<profdata-file>' is required unless '--" +
3112         DebugInfoFilename.ArgStr + "' is provided");
3113 
3114   if (Filename == OutputFilename) {
3115     errs() << sys::path::filename(argv[0]) << " " << argv[1]
3116            << ": Input file name cannot be the same as the output file name!\n";
3117     return 1;
3118   }
3119   if (JsonFormat)
3120     SFormat = ShowFormat::Json;
3121 
3122   std::error_code EC;
3123   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF);
3124   if (EC)
3125     exitWithErrorCode(EC, OutputFilename);
3126 
3127   if (ShowAllFunctions && !FuncNameFilter.empty())
3128     WithColor::warning() << "-function argument ignored: showing all functions\n";
3129 
3130   if (!DebugInfoFilename.empty())
3131     return showDebugInfoCorrelation(DebugInfoFilename, SFormat, OS);
3132 
3133   if (ShowProfileKind == instr)
3134     return showInstrProfile(SFormat, OS);
3135   if (ShowProfileKind == sample)
3136     return showSampleProfile(SFormat, OS);
3137   return showMemProfProfile(SFormat, OS);
3138 }
3139 
3140 static int order_main(int argc, const char *argv[]) {
3141   std::error_code EC;
3142   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF);
3143   if (EC)
3144     exitWithErrorCode(EC, OutputFilename);
3145   auto FS = vfs::getRealFileSystem();
3146   auto ReaderOrErr = InstrProfReader::create(Filename, *FS);
3147   if (Error E = ReaderOrErr.takeError())
3148     exitWithError(std::move(E), Filename);
3149 
3150   auto Reader = std::move(ReaderOrErr.get());
3151   for (auto &I : *Reader) {
3152     // Read all entries
3153     (void)I;
3154   }
3155   auto &Traces = Reader->getTemporalProfTraces();
3156   auto Nodes = TemporalProfTraceTy::createBPFunctionNodes(Traces);
3157   BalancedPartitioningConfig Config;
3158   BalancedPartitioning BP(Config);
3159   BP.run(Nodes);
3160 
3161   OS << "# Ordered " << Nodes.size() << " functions\n";
3162   OS << "# Warning: Mach-O may prefix symbols with \"_\" depending on the "
3163         "linkage and this output does not take that into account. Some "
3164         "post-processing may be required before passing to the linker via "
3165         "-order_file.\n";
3166   for (auto &N : Nodes) {
3167     auto [Filename, ParsedFuncName] =
3168         getParsedIRPGOFuncName(Reader->getSymtab().getFuncOrVarName(N.Id));
3169     if (!Filename.empty())
3170       OS << "# " << Filename << "\n";
3171     OS << ParsedFuncName << "\n";
3172   }
3173   return 0;
3174 }
3175 
3176 int llvm_profdata_main(int argc, char **argvNonConst,
3177                        const llvm::ToolContext &) {
3178   const char **argv = const_cast<const char **>(argvNonConst);
3179   InitLLVM X(argc, argv);
3180 
3181   StringRef ProgName(sys::path::filename(argv[0]));
3182 
3183   if (argc < 2) {
3184     errs() << ProgName
3185            << ": No subcommand specified! Run llvm-profata --help for usage.\n";
3186     return 1;
3187   }
3188 
3189   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data\n");
3190 
3191   if (ShowSubcommand)
3192     return show_main(argc, argv);
3193 
3194   if (OrderSubcommand)
3195     return order_main(argc, argv);
3196 
3197   if (OverlapSubcommand)
3198     return overlap_main(argc, argv);
3199 
3200   if (MergeSubcommand)
3201     return merge_main(argc, argv);
3202 
3203   errs() << ProgName
3204          << ": Unknown command. Run llvm-profdata --help for usage.\n";
3205   return 1;
3206 }
3207