1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // llvm-profdata merges .profdata files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/SmallSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/ProfileData/InstrProfReader.h"
19 #include "llvm/ProfileData/InstrProfWriter.h"
20 #include "llvm/ProfileData/ProfileCommon.h"
21 #include "llvm/ProfileData/SampleProfReader.h"
22 #include "llvm/ProfileData/SampleProfWriter.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Errc.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/Signals.h"
32 #include "llvm/Support/ThreadPool.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <algorithm>
35 
36 using namespace llvm;
37 
38 enum ProfileFormat { PF_None = 0, PF_Text, PF_Binary, PF_GCC };
39 
40 static void exitWithError(const Twine &Message, StringRef Whence = "",
41                           StringRef Hint = "") {
42   errs() << "error: ";
43   if (!Whence.empty())
44     errs() << Whence << ": ";
45   errs() << Message << "\n";
46   if (!Hint.empty())
47     errs() << Hint << "\n";
48   ::exit(1);
49 }
50 
51 static void exitWithError(Error E, StringRef Whence = "") {
52   if (E.isA<InstrProfError>()) {
53     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
54       instrprof_error instrError = IPE.get();
55       StringRef Hint = "";
56       if (instrError == instrprof_error::unrecognized_format) {
57         // Hint for common error of forgetting -sample for sample profiles.
58         Hint = "Perhaps you forgot to use the -sample option?";
59       }
60       exitWithError(IPE.message(), Whence, Hint);
61     });
62   }
63 
64   exitWithError(toString(std::move(E)), Whence);
65 }
66 
67 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
68   exitWithError(EC.message(), Whence);
69 }
70 
71 namespace {
72 enum ProfileKinds { instr, sample };
73 }
74 
75 static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
76                                    StringRef WhenceFunction = "",
77                                    bool ShowHint = true) {
78   if (!WhenceFile.empty())
79     errs() << WhenceFile << ": ";
80   if (!WhenceFunction.empty())
81     errs() << WhenceFunction << ": ";
82 
83   auto IPE = instrprof_error::success;
84   E = handleErrors(std::move(E),
85                    [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
86                      IPE = E->get();
87                      return Error(std::move(E));
88                    });
89   errs() << toString(std::move(E)) << "\n";
90 
91   if (ShowHint) {
92     StringRef Hint = "";
93     if (IPE != instrprof_error::success) {
94       switch (IPE) {
95       case instrprof_error::hash_mismatch:
96       case instrprof_error::count_mismatch:
97       case instrprof_error::value_site_count_mismatch:
98         Hint = "Make sure that all profile data to be merged is generated "
99                "from the same binary.";
100         break;
101       default:
102         break;
103       }
104     }
105 
106     if (!Hint.empty())
107       errs() << Hint << "\n";
108   }
109 }
110 
111 struct WeightedFile {
112   std::string Filename;
113   uint64_t Weight;
114 };
115 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
116 
117 /// Keep track of merged data and reported errors.
118 struct WriterContext {
119   std::mutex Lock;
120   InstrProfWriter Writer;
121   Error Err;
122   StringRef ErrWhence;
123   std::mutex &ErrLock;
124   SmallSet<instrprof_error, 4> &WriterErrorCodes;
125 
126   WriterContext(bool IsSparse, std::mutex &ErrLock,
127                 SmallSet<instrprof_error, 4> &WriterErrorCodes)
128       : Lock(), Writer(IsSparse), Err(Error::success()), ErrWhence(""),
129         ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {}
130 };
131 
132 /// Load an input into a writer context.
133 static void loadInput(const WeightedFile &Input, WriterContext *WC) {
134   std::unique_lock<std::mutex> CtxGuard{WC->Lock};
135 
136   // If there's a pending hard error, don't do more work.
137   if (WC->Err)
138     return;
139 
140   WC->ErrWhence = Input.Filename;
141 
142   auto ReaderOrErr = InstrProfReader::create(Input.Filename);
143   if (Error E = ReaderOrErr.takeError()) {
144     // Skip the empty profiles by returning sliently.
145     instrprof_error IPE = InstrProfError::take(std::move(E));
146     if (IPE != instrprof_error::empty_raw_profile)
147       WC->Err = make_error<InstrProfError>(IPE);
148     return;
149   }
150 
151   auto Reader = std::move(ReaderOrErr.get());
152   bool IsIRProfile = Reader->isIRLevelProfile();
153   if (WC->Writer.setIsIRLevelProfile(IsIRProfile)) {
154     WC->Err = make_error<StringError>(
155         "Merge IR generated profile with Clang generated profile.",
156         std::error_code());
157     return;
158   }
159 
160   for (auto &I : *Reader) {
161     const StringRef FuncName = I.Name;
162     if (Error E = WC->Writer.addRecord(std::move(I), Input.Weight)) {
163       // Only show hint the first time an error occurs.
164       instrprof_error IPE = InstrProfError::take(std::move(E));
165       std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
166       bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
167       handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
168                              FuncName, firstTime);
169     }
170   }
171   if (Reader->hasError())
172     WC->Err = Reader->getError();
173 }
174 
175 /// Merge the \p Src writer context into \p Dst.
176 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
177   if (Error E = Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer)))
178     Dst->Err = std::move(E);
179 }
180 
181 static void mergeInstrProfile(const WeightedFileVector &Inputs,
182                               StringRef OutputFilename,
183                               ProfileFormat OutputFormat, bool OutputSparse,
184                               unsigned NumThreads) {
185   if (OutputFilename.compare("-") == 0)
186     exitWithError("Cannot write indexed profdata format to stdout.");
187 
188   if (OutputFormat != PF_Binary && OutputFormat != PF_Text)
189     exitWithError("Unknown format is specified.");
190 
191   std::error_code EC;
192   raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
193   if (EC)
194     exitWithErrorCode(EC, OutputFilename);
195 
196   std::mutex ErrorLock;
197   SmallSet<instrprof_error, 4> WriterErrorCodes;
198 
199   // If NumThreads is not specified, auto-detect a good default.
200   if (NumThreads == 0)
201     NumThreads = std::max(1U, std::min(std::thread::hardware_concurrency(),
202                                        unsigned(Inputs.size() / 2)));
203 
204   // Initialize the writer contexts.
205   SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
206   for (unsigned I = 0; I < NumThreads; ++I)
207     Contexts.emplace_back(llvm::make_unique<WriterContext>(
208         OutputSparse, ErrorLock, WriterErrorCodes));
209 
210   if (NumThreads == 1) {
211     for (const auto &Input : Inputs)
212       loadInput(Input, Contexts[0].get());
213   } else {
214     ThreadPool Pool(NumThreads);
215 
216     // Load the inputs in parallel (N/NumThreads serial steps).
217     unsigned Ctx = 0;
218     for (const auto &Input : Inputs) {
219       Pool.async(loadInput, Input, Contexts[Ctx].get());
220       Ctx = (Ctx + 1) % NumThreads;
221     }
222     Pool.wait();
223 
224     // Merge the writer contexts together (~ lg(NumThreads) serial steps).
225     unsigned Mid = Contexts.size() / 2;
226     unsigned End = Contexts.size();
227     assert(Mid > 0 && "Expected more than one context");
228     do {
229       for (unsigned I = 0; I < Mid; ++I)
230         Pool.async(mergeWriterContexts, Contexts[I].get(),
231                    Contexts[I + Mid].get());
232       Pool.wait();
233       if (End & 1) {
234         Pool.async(mergeWriterContexts, Contexts[0].get(),
235                    Contexts[End - 1].get());
236         Pool.wait();
237       }
238       End = Mid;
239       Mid /= 2;
240     } while (Mid > 0);
241   }
242 
243   // Handle deferred hard errors encountered during merging.
244   for (std::unique_ptr<WriterContext> &WC : Contexts)
245     if (WC->Err)
246       exitWithError(std::move(WC->Err), WC->ErrWhence);
247 
248   InstrProfWriter &Writer = Contexts[0]->Writer;
249   if (OutputFormat == PF_Text) {
250     if (Error E = Writer.writeText(Output))
251       exitWithError(std::move(E));
252   } else {
253     Writer.write(Output);
254   }
255 }
256 
257 static sampleprof::SampleProfileFormat FormatMap[] = {
258     sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Binary,
259     sampleprof::SPF_GCC};
260 
261 static void mergeSampleProfile(const WeightedFileVector &Inputs,
262                                StringRef OutputFilename,
263                                ProfileFormat OutputFormat) {
264   using namespace sampleprof;
265   auto WriterOrErr =
266       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
267   if (std::error_code EC = WriterOrErr.getError())
268     exitWithErrorCode(EC, OutputFilename);
269 
270   auto Writer = std::move(WriterOrErr.get());
271   StringMap<FunctionSamples> ProfileMap;
272   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
273   LLVMContext Context;
274   for (const auto &Input : Inputs) {
275     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
276     if (std::error_code EC = ReaderOrErr.getError())
277       exitWithErrorCode(EC, Input.Filename);
278 
279     // We need to keep the readers around until after all the files are
280     // read so that we do not lose the function names stored in each
281     // reader's memory. The function names are needed to write out the
282     // merged profile map.
283     Readers.push_back(std::move(ReaderOrErr.get()));
284     const auto Reader = Readers.back().get();
285     if (std::error_code EC = Reader->read())
286       exitWithErrorCode(EC, Input.Filename);
287 
288     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
289     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
290                                               E = Profiles.end();
291          I != E; ++I) {
292       StringRef FName = I->first();
293       FunctionSamples &Samples = I->second;
294       sampleprof_error Result = ProfileMap[FName].merge(Samples, Input.Weight);
295       if (Result != sampleprof_error::success) {
296         std::error_code EC = make_error_code(Result);
297         handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
298       }
299     }
300   }
301   Writer->write(ProfileMap);
302 }
303 
304 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
305   StringRef WeightStr, FileName;
306   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
307 
308   uint64_t Weight;
309   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
310     exitWithError("Input weight must be a positive integer.");
311 
312   return {FileName, Weight};
313 }
314 
315 static std::unique_ptr<MemoryBuffer>
316 getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) {
317   if (InputFilenamesFile == "")
318     return {};
319 
320   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile);
321   if (!BufOrError)
322     exitWithErrorCode(BufOrError.getError(), InputFilenamesFile);
323 
324   return std::move(*BufOrError);
325 }
326 
327 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
328   StringRef Filename = WF.Filename;
329   uint64_t Weight = WF.Weight;
330 
331   // If it's STDIN just pass it on.
332   if (Filename == "-") {
333     WNI.push_back({Filename, Weight});
334     return;
335   }
336 
337   llvm::sys::fs::file_status Status;
338   llvm::sys::fs::status(Filename, Status);
339   if (!llvm::sys::fs::exists(Status))
340     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
341                       Filename);
342   // If it's a source file, collect it.
343   if (llvm::sys::fs::is_regular_file(Status)) {
344     WNI.push_back({Filename, Weight});
345     return;
346   }
347 
348   if (llvm::sys::fs::is_directory(Status)) {
349     std::error_code EC;
350     for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
351          F != E && !EC; F.increment(EC)) {
352       if (llvm::sys::fs::is_regular_file(F->path())) {
353         addWeightedInput(WNI, {F->path(), Weight});
354       }
355     }
356     if (EC)
357       exitWithErrorCode(EC, Filename);
358   }
359 }
360 
361 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
362                                     WeightedFileVector &WFV) {
363   if (!Buffer)
364     return;
365 
366   SmallVector<StringRef, 8> Entries;
367   StringRef Data = Buffer->getBuffer();
368   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
369   for (const StringRef &FileWeightEntry : Entries) {
370     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
371     // Skip comments.
372     if (SanitizedEntry.startswith("#"))
373       continue;
374     // If there's no comma, it's an unweighted profile.
375     else if (SanitizedEntry.find(',') == StringRef::npos)
376       addWeightedInput(WFV, {SanitizedEntry, 1});
377     else
378       addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
379   }
380 }
381 
382 static int merge_main(int argc, const char *argv[]) {
383   cl::list<std::string> InputFilenames(cl::Positional,
384                                        cl::desc("<filename...>"));
385   cl::list<std::string> WeightedInputFilenames("weighted-input",
386                                                cl::desc("<weight>,<filename>"));
387   cl::opt<std::string> InputFilenamesFile(
388       "input-files", cl::init(""),
389       cl::desc("Path to file containing newline-separated "
390                "[<weight>,]<filename> entries"));
391   cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
392                                 cl::aliasopt(InputFilenamesFile));
393   cl::opt<bool> DumpInputFileList(
394       "dump-input-file-list", cl::init(false), cl::Hidden,
395       cl::desc("Dump the list of input files and their weights, then exit"));
396   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
397                                       cl::init("-"), cl::Required,
398                                       cl::desc("Output file"));
399   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
400                             cl::aliasopt(OutputFilename));
401   cl::opt<ProfileKinds> ProfileKind(
402       cl::desc("Profile kind:"), cl::init(instr),
403       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
404                  clEnumVal(sample, "Sample profile")));
405   cl::opt<ProfileFormat> OutputFormat(
406       cl::desc("Format of output profile"), cl::init(PF_Binary),
407       cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
408                  clEnumValN(PF_Text, "text", "Text encoding"),
409                  clEnumValN(PF_GCC, "gcc",
410                             "GCC encoding (only meaningful for -sample)")));
411   cl::opt<bool> OutputSparse("sparse", cl::init(false),
412       cl::desc("Generate a sparse profile (only meaningful for -instr)"));
413   cl::opt<unsigned> NumThreads(
414       "num-threads", cl::init(0),
415       cl::desc("Number of merge threads to use (default: autodetect)"));
416   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
417                         cl::aliasopt(NumThreads));
418 
419   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
420 
421   WeightedFileVector WeightedInputs;
422   for (StringRef Filename : InputFilenames)
423     addWeightedInput(WeightedInputs, {Filename, 1});
424   for (StringRef WeightedFilename : WeightedInputFilenames)
425     addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
426 
427   // Make sure that the file buffer stays alive for the duration of the
428   // weighted input vector's lifetime.
429   auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile);
430   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
431 
432   if (WeightedInputs.empty())
433     exitWithError("No input files specified. See " +
434                   sys::path::filename(argv[0]) + " -help");
435 
436   if (DumpInputFileList) {
437     for (auto &WF : WeightedInputs)
438       outs() << WF.Weight << "," << WF.Filename << "\n";
439     return 0;
440   }
441 
442   if (ProfileKind == instr)
443     mergeInstrProfile(WeightedInputs, OutputFilename, OutputFormat,
444                       OutputSparse, NumThreads);
445   else
446     mergeSampleProfile(WeightedInputs, OutputFilename, OutputFormat);
447 
448   return 0;
449 }
450 
451 typedef struct ValueSitesStats {
452   ValueSitesStats()
453       : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
454         TotalNumValues(0) {}
455   uint64_t TotalNumValueSites;
456   uint64_t TotalNumValueSitesWithValueProfile;
457   uint64_t TotalNumValues;
458   std::vector<unsigned> ValueSitesHistogram;
459 } ValueSitesStats;
460 
461 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
462                                   ValueSitesStats &Stats, raw_fd_ostream &OS,
463                                   InstrProfSymtab *Symtab) {
464   uint32_t NS = Func.getNumValueSites(VK);
465   Stats.TotalNumValueSites += NS;
466   for (size_t I = 0; I < NS; ++I) {
467     uint32_t NV = Func.getNumValueDataForSite(VK, I);
468     std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
469     Stats.TotalNumValues += NV;
470     if (NV) {
471       Stats.TotalNumValueSitesWithValueProfile++;
472       if (NV > Stats.ValueSitesHistogram.size())
473         Stats.ValueSitesHistogram.resize(NV, 0);
474       Stats.ValueSitesHistogram[NV - 1]++;
475     }
476     for (uint32_t V = 0; V < NV; V++) {
477       OS << "\t[ " << I << ", ";
478       if (Symtab == nullptr)
479         OS << VD[V].Value;
480       else
481         OS << Symtab->getFuncName(VD[V].Value);
482       OS << ", " << VD[V].Count << " ]\n";
483     }
484   }
485 }
486 
487 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
488                                 ValueSitesStats &Stats) {
489   OS << "  Total number of sites: " << Stats.TotalNumValueSites << "\n";
490   OS << "  Total number of sites with values: "
491      << Stats.TotalNumValueSitesWithValueProfile << "\n";
492   OS << "  Total number of profiled values: " << Stats.TotalNumValues << "\n";
493 
494   OS << "  Value sites histogram:\n\tNumTargets, SiteCount\n";
495   for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
496     if (Stats.ValueSitesHistogram[I] > 0)
497       OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
498   }
499 }
500 
501 static int showInstrProfile(const std::string &Filename, bool ShowCounts,
502                             bool ShowIndirectCallTargets, bool ShowMemOPSizes,
503                             bool ShowDetailedSummary,
504                             std::vector<uint32_t> DetailedSummaryCutoffs,
505                             bool ShowAllFunctions,
506                             const std::string &ShowFunction, bool TextFormat,
507                             raw_fd_ostream &OS) {
508   auto ReaderOrErr = InstrProfReader::create(Filename);
509   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
510   if (ShowDetailedSummary && Cutoffs.empty()) {
511     Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
512   }
513   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
514   if (Error E = ReaderOrErr.takeError())
515     exitWithError(std::move(E), Filename);
516 
517   auto Reader = std::move(ReaderOrErr.get());
518   bool IsIRInstr = Reader->isIRLevelProfile();
519   size_t ShownFunctions = 0;
520   int NumVPKind = IPVK_Last - IPVK_First + 1;
521   std::vector<ValueSitesStats> VPStats(NumVPKind);
522   for (const auto &Func : *Reader) {
523     bool Show =
524         ShowAllFunctions || (!ShowFunction.empty() &&
525                              Func.Name.find(ShowFunction) != Func.Name.npos);
526 
527     bool doTextFormatDump = (Show && ShowCounts && TextFormat);
528 
529     if (doTextFormatDump) {
530       InstrProfSymtab &Symtab = Reader->getSymtab();
531       InstrProfWriter::writeRecordInText(Func, Symtab, OS);
532       continue;
533     }
534 
535     assert(Func.Counts.size() > 0 && "function missing entry counter");
536     Builder.addRecord(Func);
537 
538     if (Show) {
539 
540       if (!ShownFunctions)
541         OS << "Counters:\n";
542 
543       ++ShownFunctions;
544 
545       OS << "  " << Func.Name << ":\n"
546          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
547          << "    Counters: " << Func.Counts.size() << "\n";
548       if (!IsIRInstr)
549         OS << "    Function count: " << Func.Counts[0] << "\n";
550 
551       if (ShowIndirectCallTargets)
552         OS << "    Indirect Call Site Count: "
553            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
554 
555       uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
556       if (ShowMemOPSizes && NumMemOPCalls > 0)
557         OS << "    Number of Memory Intrinsics Calls: " << NumMemOPCalls
558            << "\n";
559 
560       if (ShowCounts) {
561         OS << "    Block counts: [";
562         size_t Start = (IsIRInstr ? 0 : 1);
563         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
564           OS << (I == Start ? "" : ", ") << Func.Counts[I];
565         }
566         OS << "]\n";
567       }
568 
569       if (ShowIndirectCallTargets) {
570         OS << "    Indirect Target Results:\n";
571         traverseAllValueSites(Func, IPVK_IndirectCallTarget,
572                               VPStats[IPVK_IndirectCallTarget], OS,
573                               &(Reader->getSymtab()));
574       }
575 
576       if (ShowMemOPSizes && NumMemOPCalls > 0) {
577         OS << "    Memory Intrinsic Size Results:\n";
578         traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
579                               nullptr);
580       }
581     }
582   }
583   if (Reader->hasError())
584     exitWithError(Reader->getError(), Filename);
585 
586   if (ShowCounts && TextFormat)
587     return 0;
588   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
589   if (ShowAllFunctions || !ShowFunction.empty())
590     OS << "Functions shown: " << ShownFunctions << "\n";
591   OS << "Total functions: " << PS->getNumFunctions() << "\n";
592   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
593   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
594 
595   if (ShownFunctions && ShowIndirectCallTargets) {
596     OS << "Statistics for indirect call sites profile:\n";
597     showValueSitesStats(OS, IPVK_IndirectCallTarget,
598                         VPStats[IPVK_IndirectCallTarget]);
599   }
600 
601   if (ShownFunctions && ShowMemOPSizes) {
602     OS << "Statistics for memory intrinsic calls sizes profile:\n";
603     showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
604   }
605 
606   if (ShowDetailedSummary) {
607     OS << "Detailed summary:\n";
608     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
609     OS << "Total count: " << PS->getTotalCount() << "\n";
610     for (auto Entry : PS->getDetailedSummary()) {
611       OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
612          << " account for "
613          << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
614          << " percentage of the total counts.\n";
615     }
616   }
617   return 0;
618 }
619 
620 static int showSampleProfile(const std::string &Filename, bool ShowCounts,
621                              bool ShowAllFunctions,
622                              const std::string &ShowFunction,
623                              raw_fd_ostream &OS) {
624   using namespace sampleprof;
625   LLVMContext Context;
626   auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
627   if (std::error_code EC = ReaderOrErr.getError())
628     exitWithErrorCode(EC, Filename);
629 
630   auto Reader = std::move(ReaderOrErr.get());
631   if (std::error_code EC = Reader->read())
632     exitWithErrorCode(EC, Filename);
633 
634   if (ShowAllFunctions || ShowFunction.empty())
635     Reader->dump(OS);
636   else
637     Reader->dumpFunctionProfile(ShowFunction, OS);
638 
639   return 0;
640 }
641 
642 static int show_main(int argc, const char *argv[]) {
643   cl::opt<std::string> Filename(cl::Positional, cl::Required,
644                                 cl::desc("<profdata-file>"));
645 
646   cl::opt<bool> ShowCounts("counts", cl::init(false),
647                            cl::desc("Show counter values for shown functions"));
648   cl::opt<bool> TextFormat(
649       "text", cl::init(false),
650       cl::desc("Show instr profile data in text dump format"));
651   cl::opt<bool> ShowIndirectCallTargets(
652       "ic-targets", cl::init(false),
653       cl::desc("Show indirect call site target values for shown functions"));
654   cl::opt<bool> ShowMemOPSizes(
655       "memop-sizes", cl::init(false),
656       cl::desc("Show the profiled sizes of the memory intrinsic calls "
657                "for shown functions"));
658   cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
659                                     cl::desc("Show detailed profile summary"));
660   cl::list<uint32_t> DetailedSummaryCutoffs(
661       cl::CommaSeparated, "detailed-summary-cutoffs",
662       cl::desc(
663           "Cutoff percentages (times 10000) for generating detailed summary"),
664       cl::value_desc("800000,901000,999999"));
665   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
666                                  cl::desc("Details for every function"));
667   cl::opt<std::string> ShowFunction("function",
668                                     cl::desc("Details for matching functions"));
669 
670   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
671                                       cl::init("-"), cl::desc("Output file"));
672   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
673                             cl::aliasopt(OutputFilename));
674   cl::opt<ProfileKinds> ProfileKind(
675       cl::desc("Profile kind:"), cl::init(instr),
676       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
677                  clEnumVal(sample, "Sample profile")));
678 
679   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
680 
681   if (OutputFilename.empty())
682     OutputFilename = "-";
683 
684   std::error_code EC;
685   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
686   if (EC)
687     exitWithErrorCode(EC, OutputFilename);
688 
689   if (ShowAllFunctions && !ShowFunction.empty())
690     errs() << "warning: -function argument ignored: showing all functions\n";
691 
692   std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs.begin(),
693                                 DetailedSummaryCutoffs.end());
694   if (ProfileKind == instr)
695     return showInstrProfile(Filename, ShowCounts, ShowIndirectCallTargets,
696                             ShowMemOPSizes, ShowDetailedSummary,
697                             DetailedSummaryCutoffs, ShowAllFunctions,
698                             ShowFunction, TextFormat, OS);
699   else
700     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
701                              ShowFunction, OS);
702 }
703 
704 int main(int argc, const char *argv[]) {
705   // Print a stack trace if we signal out.
706   sys::PrintStackTraceOnErrorSignal(argv[0]);
707   PrettyStackTraceProgram X(argc, argv);
708   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
709 
710   StringRef ProgName(sys::path::filename(argv[0]));
711   if (argc > 1) {
712     int (*func)(int, const char *[]) = nullptr;
713 
714     if (strcmp(argv[1], "merge") == 0)
715       func = merge_main;
716     else if (strcmp(argv[1], "show") == 0)
717       func = show_main;
718 
719     if (func) {
720       std::string Invocation(ProgName.str() + " " + argv[1]);
721       argv[1] = Invocation.c_str();
722       return func(argc - 1, argv + 1);
723     }
724 
725     if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
726         strcmp(argv[1], "--help") == 0) {
727 
728       errs() << "OVERVIEW: LLVM profile data tools\n\n"
729              << "USAGE: " << ProgName << " <command> [args...]\n"
730              << "USAGE: " << ProgName << " <command> -help\n\n"
731              << "See each individual command --help for more details.\n"
732              << "Available commands: merge, show\n";
733       return 0;
734     }
735   }
736 
737   if (argc < 2)
738     errs() << ProgName << ": No command specified!\n";
739   else
740     errs() << ProgName << ": Unknown command!\n";
741 
742   errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
743   return 1;
744 }
745