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