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