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