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 ((WC->Err = ReaderOrErr.takeError()))
144     return;
145 
146   auto Reader = std::move(ReaderOrErr.get());
147   bool IsIRProfile = Reader->isIRLevelProfile();
148   if (WC->Writer.setIsIRLevelProfile(IsIRProfile)) {
149     WC->Err = make_error<StringError>(
150         "Merge IR generated profile with Clang generated profile.",
151         std::error_code());
152     return;
153   }
154 
155   for (auto &I : *Reader) {
156     if (Error E = WC->Writer.addRecord(std::move(I), Input.Weight)) {
157       // Only show hint the first time an error occurs.
158       instrprof_error IPE = InstrProfError::take(std::move(E));
159       std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
160       bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
161       handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
162                              I.Name, firstTime);
163     }
164   }
165   if (Reader->hasError())
166     WC->Err = Reader->getError();
167 }
168 
169 /// Merge the \p Src writer context into \p Dst.
170 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
171   if (Error E = Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer)))
172     Dst->Err = std::move(E);
173 }
174 
175 static void mergeInstrProfile(const WeightedFileVector &Inputs,
176                               StringRef OutputFilename,
177                               ProfileFormat OutputFormat, bool OutputSparse,
178                               unsigned NumThreads) {
179   if (OutputFilename.compare("-") == 0)
180     exitWithError("Cannot write indexed profdata format to stdout.");
181 
182   if (OutputFormat != PF_Binary && OutputFormat != PF_Text)
183     exitWithError("Unknown format is specified.");
184 
185   std::error_code EC;
186   raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
187   if (EC)
188     exitWithErrorCode(EC, OutputFilename);
189 
190   std::mutex ErrorLock;
191   SmallSet<instrprof_error, 4> WriterErrorCodes;
192 
193   // If NumThreads is not specified, auto-detect a good default.
194   if (NumThreads == 0)
195     NumThreads = std::max(1U, std::min(std::thread::hardware_concurrency(),
196                                        unsigned(Inputs.size() / 2)));
197 
198   // Initialize the writer contexts.
199   SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
200   for (unsigned I = 0; I < NumThreads; ++I)
201     Contexts.emplace_back(llvm::make_unique<WriterContext>(
202         OutputSparse, ErrorLock, WriterErrorCodes));
203 
204   if (NumThreads == 1) {
205     for (const auto &Input : Inputs)
206       loadInput(Input, Contexts[0].get());
207   } else {
208     ThreadPool Pool(NumThreads);
209 
210     // Load the inputs in parallel (N/NumThreads serial steps).
211     unsigned Ctx = 0;
212     for (const auto &Input : Inputs) {
213       Pool.async(loadInput, Input, Contexts[Ctx].get());
214       Ctx = (Ctx + 1) % NumThreads;
215     }
216     Pool.wait();
217 
218     // Merge the writer contexts together (~ lg(NumThreads) serial steps).
219     unsigned Mid = Contexts.size() / 2;
220     unsigned End = Contexts.size();
221     assert(Mid > 0 && "Expected more than one context");
222     do {
223       for (unsigned I = 0; I < Mid; ++I)
224         Pool.async(mergeWriterContexts, Contexts[I].get(),
225                    Contexts[I + Mid].get());
226       Pool.wait();
227       if (End & 1) {
228         Pool.async(mergeWriterContexts, Contexts[0].get(),
229                    Contexts[End - 1].get());
230         Pool.wait();
231       }
232       End = Mid;
233       Mid /= 2;
234     } while (Mid > 0);
235   }
236 
237   // Handle deferred hard errors encountered during merging.
238   for (std::unique_ptr<WriterContext> &WC : Contexts)
239     if (WC->Err)
240       exitWithError(std::move(WC->Err), WC->ErrWhence);
241 
242   InstrProfWriter &Writer = Contexts[0]->Writer;
243   if (OutputFormat == PF_Text)
244     Writer.writeText(Output);
245   else
246     Writer.write(Output);
247 }
248 
249 static sampleprof::SampleProfileFormat FormatMap[] = {
250     sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Binary,
251     sampleprof::SPF_GCC};
252 
253 static void mergeSampleProfile(const WeightedFileVector &Inputs,
254                                StringRef OutputFilename,
255                                ProfileFormat OutputFormat) {
256   using namespace sampleprof;
257   auto WriterOrErr =
258       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
259   if (std::error_code EC = WriterOrErr.getError())
260     exitWithErrorCode(EC, OutputFilename);
261 
262   auto Writer = std::move(WriterOrErr.get());
263   StringMap<FunctionSamples> ProfileMap;
264   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
265   LLVMContext Context;
266   for (const auto &Input : Inputs) {
267     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
268     if (std::error_code EC = ReaderOrErr.getError())
269       exitWithErrorCode(EC, Input.Filename);
270 
271     // We need to keep the readers around until after all the files are
272     // read so that we do not lose the function names stored in each
273     // reader's memory. The function names are needed to write out the
274     // merged profile map.
275     Readers.push_back(std::move(ReaderOrErr.get()));
276     const auto Reader = Readers.back().get();
277     if (std::error_code EC = Reader->read())
278       exitWithErrorCode(EC, Input.Filename);
279 
280     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
281     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
282                                               E = Profiles.end();
283          I != E; ++I) {
284       StringRef FName = I->first();
285       FunctionSamples &Samples = I->second;
286       sampleprof_error Result = ProfileMap[FName].merge(Samples, Input.Weight);
287       if (Result != sampleprof_error::success) {
288         std::error_code EC = make_error_code(Result);
289         handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
290       }
291     }
292   }
293   Writer->write(ProfileMap);
294 }
295 
296 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
297   StringRef WeightStr, FileName;
298   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
299 
300   uint64_t Weight;
301   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
302     exitWithError("Input weight must be a positive integer.");
303 
304   return {FileName, Weight};
305 }
306 
307 static std::unique_ptr<MemoryBuffer>
308 getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) {
309   if (InputFilenamesFile == "")
310     return {};
311 
312   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile);
313   if (!BufOrError)
314     exitWithErrorCode(BufOrError.getError(), InputFilenamesFile);
315 
316   return std::move(*BufOrError);
317 }
318 
319 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
320   StringRef Filename = WF.Filename;
321   uint64_t Weight = WF.Weight;
322 
323   // If it's STDIN just pass it on.
324   if (Filename == "-") {
325     WNI.push_back({Filename, Weight});
326     return;
327   }
328 
329   llvm::sys::fs::file_status Status;
330   llvm::sys::fs::status(Filename, Status);
331   if (!llvm::sys::fs::exists(Status))
332     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
333                       Filename);
334   // If it's a source file, collect it.
335   if (llvm::sys::fs::is_regular_file(Status)) {
336     WNI.push_back({Filename, Weight});
337     return;
338   }
339 
340   if (llvm::sys::fs::is_directory(Status)) {
341     std::error_code EC;
342     for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
343          F != E && !EC; F.increment(EC)) {
344       if (llvm::sys::fs::is_regular_file(F->path())) {
345         addWeightedInput(WNI, {F->path(), Weight});
346       }
347     }
348     if (EC)
349       exitWithErrorCode(EC, Filename);
350   }
351 }
352 
353 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
354                                     WeightedFileVector &WFV) {
355   if (!Buffer)
356     return;
357 
358   SmallVector<StringRef, 8> Entries;
359   StringRef Data = Buffer->getBuffer();
360   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
361   for (const StringRef &FileWeightEntry : Entries) {
362     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
363     // Skip comments.
364     if (SanitizedEntry.startswith("#"))
365       continue;
366     // If there's no comma, it's an unweighted profile.
367     else if (SanitizedEntry.find(',') == StringRef::npos)
368       addWeightedInput(WFV, {SanitizedEntry, 1});
369     else
370       addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
371   }
372 }
373 
374 static int merge_main(int argc, const char *argv[]) {
375   cl::list<std::string> InputFilenames(cl::Positional,
376                                        cl::desc("<filename...>"));
377   cl::list<std::string> WeightedInputFilenames("weighted-input",
378                                                cl::desc("<weight>,<filename>"));
379   cl::opt<std::string> InputFilenamesFile(
380       "input-files", cl::init(""),
381       cl::desc("Path to file containing newline-separated "
382                "[<weight>,]<filename> entries"));
383   cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
384                                 cl::aliasopt(InputFilenamesFile));
385   cl::opt<bool> DumpInputFileList(
386       "dump-input-file-list", cl::init(false), cl::Hidden,
387       cl::desc("Dump the list of input files and their weights, then exit"));
388   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
389                                       cl::init("-"), cl::Required,
390                                       cl::desc("Output file"));
391   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
392                             cl::aliasopt(OutputFilename));
393   cl::opt<ProfileKinds> ProfileKind(
394       cl::desc("Profile kind:"), cl::init(instr),
395       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
396                  clEnumVal(sample, "Sample profile")));
397   cl::opt<ProfileFormat> OutputFormat(
398       cl::desc("Format of output profile"), cl::init(PF_Binary),
399       cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
400                  clEnumValN(PF_Text, "text", "Text encoding"),
401                  clEnumValN(PF_GCC, "gcc",
402                             "GCC encoding (only meaningful for -sample)")));
403   cl::opt<bool> OutputSparse("sparse", cl::init(false),
404       cl::desc("Generate a sparse profile (only meaningful for -instr)"));
405   cl::opt<unsigned> NumThreads(
406       "num-threads", cl::init(0),
407       cl::desc("Number of merge threads to use (default: autodetect)"));
408   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
409                         cl::aliasopt(NumThreads));
410 
411   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
412 
413   WeightedFileVector WeightedInputs;
414   for (StringRef Filename : InputFilenames)
415     addWeightedInput(WeightedInputs, {Filename, 1});
416   for (StringRef WeightedFilename : WeightedInputFilenames)
417     addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
418 
419   // Make sure that the file buffer stays alive for the duration of the
420   // weighted input vector's lifetime.
421   auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile);
422   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
423 
424   if (WeightedInputs.empty())
425     exitWithError("No input files specified. See " +
426                   sys::path::filename(argv[0]) + " -help");
427 
428   if (DumpInputFileList) {
429     for (auto &WF : WeightedInputs)
430       outs() << WF.Weight << "," << WF.Filename << "\n";
431     return 0;
432   }
433 
434   if (ProfileKind == instr)
435     mergeInstrProfile(WeightedInputs, OutputFilename, OutputFormat,
436                       OutputSparse, NumThreads);
437   else
438     mergeSampleProfile(WeightedInputs, OutputFilename, OutputFormat);
439 
440   return 0;
441 }
442 
443 static int showInstrProfile(const std::string &Filename, bool ShowCounts,
444                             bool ShowIndirectCallTargets,
445                             bool ShowDetailedSummary,
446                             std::vector<uint32_t> DetailedSummaryCutoffs,
447                             bool ShowAllFunctions,
448                             const std::string &ShowFunction, bool TextFormat,
449                             raw_fd_ostream &OS) {
450   auto ReaderOrErr = InstrProfReader::create(Filename);
451   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
452   if (ShowDetailedSummary && Cutoffs.empty()) {
453     Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
454   }
455   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
456   if (Error E = ReaderOrErr.takeError())
457     exitWithError(std::move(E), Filename);
458 
459   auto Reader = std::move(ReaderOrErr.get());
460   bool IsIRInstr = Reader->isIRLevelProfile();
461   size_t ShownFunctions = 0;
462   uint64_t TotalNumValueSites = 0;
463   uint64_t TotalNumValueSitesWithValueProfile = 0;
464   uint64_t TotalNumValues = 0;
465   std::vector<unsigned> ICHistogram;
466   for (const auto &Func : *Reader) {
467     bool Show =
468         ShowAllFunctions || (!ShowFunction.empty() &&
469                              Func.Name.find(ShowFunction) != Func.Name.npos);
470 
471     bool doTextFormatDump = (Show && ShowCounts && TextFormat);
472 
473     if (doTextFormatDump) {
474       InstrProfSymtab &Symtab = Reader->getSymtab();
475       InstrProfWriter::writeRecordInText(Func, Symtab, OS);
476       continue;
477     }
478 
479     assert(Func.Counts.size() > 0 && "function missing entry counter");
480     Builder.addRecord(Func);
481 
482     if (Show) {
483 
484       if (!ShownFunctions)
485         OS << "Counters:\n";
486 
487       ++ShownFunctions;
488 
489       OS << "  " << Func.Name << ":\n"
490          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
491          << "    Counters: " << Func.Counts.size() << "\n";
492       if (!IsIRInstr)
493         OS << "    Function count: " << Func.Counts[0] << "\n";
494 
495       if (ShowIndirectCallTargets)
496         OS << "    Indirect Call Site Count: "
497            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
498 
499       if (ShowCounts) {
500         OS << "    Block counts: [";
501         size_t Start = (IsIRInstr ? 0 : 1);
502         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
503           OS << (I == Start ? "" : ", ") << Func.Counts[I];
504         }
505         OS << "]\n";
506       }
507 
508       if (ShowIndirectCallTargets) {
509         InstrProfSymtab &Symtab = Reader->getSymtab();
510         uint32_t NS = Func.getNumValueSites(IPVK_IndirectCallTarget);
511         OS << "    Indirect Target Results: \n";
512         TotalNumValueSites += NS;
513         for (size_t I = 0; I < NS; ++I) {
514           uint32_t NV = Func.getNumValueDataForSite(IPVK_IndirectCallTarget, I);
515           std::unique_ptr<InstrProfValueData[]> VD =
516               Func.getValueForSite(IPVK_IndirectCallTarget, I);
517           TotalNumValues += NV;
518           if (NV) {
519             TotalNumValueSitesWithValueProfile++;
520             if (NV > ICHistogram.size())
521               ICHistogram.resize(NV, 0);
522             ICHistogram[NV - 1]++;
523           }
524           for (uint32_t V = 0; V < NV; V++) {
525             OS << "\t[ " << I << ", ";
526             OS << Symtab.getFuncName(VD[V].Value) << ", " << VD[V].Count
527                << " ]\n";
528           }
529         }
530       }
531     }
532   }
533   if (Reader->hasError())
534     exitWithError(Reader->getError(), Filename);
535 
536   if (ShowCounts && TextFormat)
537     return 0;
538   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
539   if (ShowAllFunctions || !ShowFunction.empty())
540     OS << "Functions shown: " << ShownFunctions << "\n";
541   OS << "Total functions: " << PS->getNumFunctions() << "\n";
542   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
543   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
544   if (ShownFunctions && ShowIndirectCallTargets) {
545     OS << "Total Number of Indirect Call Sites : " << TotalNumValueSites
546        << "\n";
547     OS << "Total Number of Sites With Values : "
548        << TotalNumValueSitesWithValueProfile << "\n";
549     OS << "Total Number of Profiled Values : " << TotalNumValues << "\n";
550 
551     OS << "IC Value histogram : \n\tNumTargets, SiteCount\n";
552     for (unsigned I = 0; I < ICHistogram.size(); I++) {
553       OS << "\t" << I + 1 << ", " << ICHistogram[I] << "\n";
554     }
555   }
556 
557   if (ShowDetailedSummary) {
558     OS << "Detailed summary:\n";
559     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
560     OS << "Total count: " << PS->getTotalCount() << "\n";
561     for (auto Entry : PS->getDetailedSummary()) {
562       OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
563          << " account for "
564          << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
565          << " percentage of the total counts.\n";
566     }
567   }
568   return 0;
569 }
570 
571 static int showSampleProfile(const std::string &Filename, bool ShowCounts,
572                              bool ShowAllFunctions,
573                              const std::string &ShowFunction,
574                              raw_fd_ostream &OS) {
575   using namespace sampleprof;
576   LLVMContext Context;
577   auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
578   if (std::error_code EC = ReaderOrErr.getError())
579     exitWithErrorCode(EC, Filename);
580 
581   auto Reader = std::move(ReaderOrErr.get());
582   if (std::error_code EC = Reader->read())
583     exitWithErrorCode(EC, Filename);
584 
585   if (ShowAllFunctions || ShowFunction.empty())
586     Reader->dump(OS);
587   else
588     Reader->dumpFunctionProfile(ShowFunction, OS);
589 
590   return 0;
591 }
592 
593 static int show_main(int argc, const char *argv[]) {
594   cl::opt<std::string> Filename(cl::Positional, cl::Required,
595                                 cl::desc("<profdata-file>"));
596 
597   cl::opt<bool> ShowCounts("counts", cl::init(false),
598                            cl::desc("Show counter values for shown functions"));
599   cl::opt<bool> TextFormat(
600       "text", cl::init(false),
601       cl::desc("Show instr profile data in text dump format"));
602   cl::opt<bool> ShowIndirectCallTargets(
603       "ic-targets", cl::init(false),
604       cl::desc("Show indirect call site target values for shown functions"));
605   cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
606                                     cl::desc("Show detailed profile summary"));
607   cl::list<uint32_t> DetailedSummaryCutoffs(
608       cl::CommaSeparated, "detailed-summary-cutoffs",
609       cl::desc(
610           "Cutoff percentages (times 10000) for generating detailed summary"),
611       cl::value_desc("800000,901000,999999"));
612   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
613                                  cl::desc("Details for every function"));
614   cl::opt<std::string> ShowFunction("function",
615                                     cl::desc("Details for matching functions"));
616 
617   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
618                                       cl::init("-"), cl::desc("Output file"));
619   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
620                             cl::aliasopt(OutputFilename));
621   cl::opt<ProfileKinds> ProfileKind(
622       cl::desc("Profile kind:"), cl::init(instr),
623       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
624                  clEnumVal(sample, "Sample profile")));
625 
626   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
627 
628   if (OutputFilename.empty())
629     OutputFilename = "-";
630 
631   std::error_code EC;
632   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
633   if (EC)
634     exitWithErrorCode(EC, OutputFilename);
635 
636   if (ShowAllFunctions && !ShowFunction.empty())
637     errs() << "warning: -function argument ignored: showing all functions\n";
638 
639   std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs.begin(),
640                                 DetailedSummaryCutoffs.end());
641   if (ProfileKind == instr)
642     return showInstrProfile(Filename, ShowCounts, ShowIndirectCallTargets,
643                             ShowDetailedSummary, DetailedSummaryCutoffs,
644                             ShowAllFunctions, ShowFunction, TextFormat, OS);
645   else
646     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
647                              ShowFunction, OS);
648 }
649 
650 int main(int argc, const char *argv[]) {
651   // Print a stack trace if we signal out.
652   sys::PrintStackTraceOnErrorSignal(argv[0]);
653   PrettyStackTraceProgram X(argc, argv);
654   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
655 
656   StringRef ProgName(sys::path::filename(argv[0]));
657   if (argc > 1) {
658     int (*func)(int, const char *[]) = nullptr;
659 
660     if (strcmp(argv[1], "merge") == 0)
661       func = merge_main;
662     else if (strcmp(argv[1], "show") == 0)
663       func = show_main;
664 
665     if (func) {
666       std::string Invocation(ProgName.str() + " " + argv[1]);
667       argv[1] = Invocation.c_str();
668       return func(argc - 1, argv + 1);
669     }
670 
671     if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
672         strcmp(argv[1], "--help") == 0) {
673 
674       errs() << "OVERVIEW: LLVM profile data tools\n\n"
675              << "USAGE: " << ProgName << " <command> [args...]\n"
676              << "USAGE: " << ProgName << " <command> -help\n\n"
677              << "See each individual command --help for more details.\n"
678              << "Available commands: merge, show\n";
679       return 0;
680     }
681   }
682 
683   if (argc < 2)
684     errs() << ProgName << ": No command specified!\n";
685   else
686     errs() << ProgName << ": Unknown command!\n";
687 
688   errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
689   return 1;
690 }
691