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