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