]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-profdata/llvm-profdata.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llvm-profdata / llvm-profdata.cpp
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     Writer.writeText(Output);
251   else
252     Writer.write(Output);
253 }
254
255 static sampleprof::SampleProfileFormat FormatMap[] = {
256     sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Binary,
257     sampleprof::SPF_GCC};
258
259 static void mergeSampleProfile(const WeightedFileVector &Inputs,
260                                StringRef OutputFilename,
261                                ProfileFormat OutputFormat) {
262   using namespace sampleprof;
263   auto WriterOrErr =
264       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
265   if (std::error_code EC = WriterOrErr.getError())
266     exitWithErrorCode(EC, OutputFilename);
267
268   auto Writer = std::move(WriterOrErr.get());
269   StringMap<FunctionSamples> ProfileMap;
270   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
271   LLVMContext Context;
272   for (const auto &Input : Inputs) {
273     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
274     if (std::error_code EC = ReaderOrErr.getError())
275       exitWithErrorCode(EC, Input.Filename);
276
277     // We need to keep the readers around until after all the files are
278     // read so that we do not lose the function names stored in each
279     // reader's memory. The function names are needed to write out the
280     // merged profile map.
281     Readers.push_back(std::move(ReaderOrErr.get()));
282     const auto Reader = Readers.back().get();
283     if (std::error_code EC = Reader->read())
284       exitWithErrorCode(EC, Input.Filename);
285
286     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
287     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
288                                               E = Profiles.end();
289          I != E; ++I) {
290       StringRef FName = I->first();
291       FunctionSamples &Samples = I->second;
292       sampleprof_error Result = ProfileMap[FName].merge(Samples, Input.Weight);
293       if (Result != sampleprof_error::success) {
294         std::error_code EC = make_error_code(Result);
295         handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
296       }
297     }
298   }
299   Writer->write(ProfileMap);
300 }
301
302 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
303   StringRef WeightStr, FileName;
304   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
305
306   uint64_t Weight;
307   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
308     exitWithError("Input weight must be a positive integer.");
309
310   return {FileName, Weight};
311 }
312
313 static std::unique_ptr<MemoryBuffer>
314 getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) {
315   if (InputFilenamesFile == "")
316     return {};
317
318   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile);
319   if (!BufOrError)
320     exitWithErrorCode(BufOrError.getError(), InputFilenamesFile);
321
322   return std::move(*BufOrError);
323 }
324
325 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
326   StringRef Filename = WF.Filename;
327   uint64_t Weight = WF.Weight;
328
329   // If it's STDIN just pass it on.
330   if (Filename == "-") {
331     WNI.push_back({Filename, Weight});
332     return;
333   }
334
335   llvm::sys::fs::file_status Status;
336   llvm::sys::fs::status(Filename, Status);
337   if (!llvm::sys::fs::exists(Status))
338     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
339                       Filename);
340   // If it's a source file, collect it.
341   if (llvm::sys::fs::is_regular_file(Status)) {
342     WNI.push_back({Filename, Weight});
343     return;
344   }
345
346   if (llvm::sys::fs::is_directory(Status)) {
347     std::error_code EC;
348     for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
349          F != E && !EC; F.increment(EC)) {
350       if (llvm::sys::fs::is_regular_file(F->path())) {
351         addWeightedInput(WNI, {F->path(), Weight});
352       }
353     }
354     if (EC)
355       exitWithErrorCode(EC, Filename);
356   }
357 }
358
359 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
360                                     WeightedFileVector &WFV) {
361   if (!Buffer)
362     return;
363
364   SmallVector<StringRef, 8> Entries;
365   StringRef Data = Buffer->getBuffer();
366   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
367   for (const StringRef &FileWeightEntry : Entries) {
368     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
369     // Skip comments.
370     if (SanitizedEntry.startswith("#"))
371       continue;
372     // If there's no comma, it's an unweighted profile.
373     else if (SanitizedEntry.find(',') == StringRef::npos)
374       addWeightedInput(WFV, {SanitizedEntry, 1});
375     else
376       addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
377   }
378 }
379
380 static int merge_main(int argc, const char *argv[]) {
381   cl::list<std::string> InputFilenames(cl::Positional,
382                                        cl::desc("<filename...>"));
383   cl::list<std::string> WeightedInputFilenames("weighted-input",
384                                                cl::desc("<weight>,<filename>"));
385   cl::opt<std::string> InputFilenamesFile(
386       "input-files", cl::init(""),
387       cl::desc("Path to file containing newline-separated "
388                "[<weight>,]<filename> entries"));
389   cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
390                                 cl::aliasopt(InputFilenamesFile));
391   cl::opt<bool> DumpInputFileList(
392       "dump-input-file-list", cl::init(false), cl::Hidden,
393       cl::desc("Dump the list of input files and their weights, then exit"));
394   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
395                                       cl::init("-"), cl::Required,
396                                       cl::desc("Output file"));
397   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
398                             cl::aliasopt(OutputFilename));
399   cl::opt<ProfileKinds> ProfileKind(
400       cl::desc("Profile kind:"), cl::init(instr),
401       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
402                  clEnumVal(sample, "Sample profile")));
403   cl::opt<ProfileFormat> OutputFormat(
404       cl::desc("Format of output profile"), cl::init(PF_Binary),
405       cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
406                  clEnumValN(PF_Text, "text", "Text encoding"),
407                  clEnumValN(PF_GCC, "gcc",
408                             "GCC encoding (only meaningful for -sample)")));
409   cl::opt<bool> OutputSparse("sparse", cl::init(false),
410       cl::desc("Generate a sparse profile (only meaningful for -instr)"));
411   cl::opt<unsigned> NumThreads(
412       "num-threads", cl::init(0),
413       cl::desc("Number of merge threads to use (default: autodetect)"));
414   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
415                         cl::aliasopt(NumThreads));
416
417   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
418
419   WeightedFileVector WeightedInputs;
420   for (StringRef Filename : InputFilenames)
421     addWeightedInput(WeightedInputs, {Filename, 1});
422   for (StringRef WeightedFilename : WeightedInputFilenames)
423     addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
424
425   // Make sure that the file buffer stays alive for the duration of the
426   // weighted input vector's lifetime.
427   auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile);
428   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
429
430   if (WeightedInputs.empty())
431     exitWithError("No input files specified. See " +
432                   sys::path::filename(argv[0]) + " -help");
433
434   if (DumpInputFileList) {
435     for (auto &WF : WeightedInputs)
436       outs() << WF.Weight << "," << WF.Filename << "\n";
437     return 0;
438   }
439
440   if (ProfileKind == instr)
441     mergeInstrProfile(WeightedInputs, OutputFilename, OutputFormat,
442                       OutputSparse, NumThreads);
443   else
444     mergeSampleProfile(WeightedInputs, OutputFilename, OutputFormat);
445
446   return 0;
447 }
448
449 typedef struct ValueSitesStats {
450   ValueSitesStats()
451       : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
452         TotalNumValues(0) {}
453   uint64_t TotalNumValueSites;
454   uint64_t TotalNumValueSitesWithValueProfile;
455   uint64_t TotalNumValues;
456   std::vector<unsigned> ValueSitesHistogram;
457 } ValueSitesStats;
458
459 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
460                                   ValueSitesStats &Stats, raw_fd_ostream &OS,
461                                   InstrProfSymtab *Symtab) {
462   uint32_t NS = Func.getNumValueSites(VK);
463   Stats.TotalNumValueSites += NS;
464   for (size_t I = 0; I < NS; ++I) {
465     uint32_t NV = Func.getNumValueDataForSite(VK, I);
466     std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
467     Stats.TotalNumValues += NV;
468     if (NV) {
469       Stats.TotalNumValueSitesWithValueProfile++;
470       if (NV > Stats.ValueSitesHistogram.size())
471         Stats.ValueSitesHistogram.resize(NV, 0);
472       Stats.ValueSitesHistogram[NV - 1]++;
473     }
474     for (uint32_t V = 0; V < NV; V++) {
475       OS << "\t[ " << I << ", ";
476       if (Symtab == nullptr)
477         OS << VD[V].Value;
478       else
479         OS << Symtab->getFuncName(VD[V].Value);
480       OS << ", " << VD[V].Count << " ]\n";
481     }
482   }
483 }
484
485 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
486                                 ValueSitesStats &Stats) {
487   OS << "  Total number of sites: " << Stats.TotalNumValueSites << "\n";
488   OS << "  Total number of sites with values: "
489      << Stats.TotalNumValueSitesWithValueProfile << "\n";
490   OS << "  Total number of profiled values: " << Stats.TotalNumValues << "\n";
491
492   OS << "  Value sites histogram:\n\tNumTargets, SiteCount\n";
493   for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
494     if (Stats.ValueSitesHistogram[I] > 0)
495       OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
496   }
497 }
498
499 static int showInstrProfile(const std::string &Filename, bool ShowCounts,
500                             bool ShowIndirectCallTargets, bool ShowMemOPSizes,
501                             bool ShowDetailedSummary,
502                             std::vector<uint32_t> DetailedSummaryCutoffs,
503                             bool ShowAllFunctions,
504                             const std::string &ShowFunction, bool TextFormat,
505                             raw_fd_ostream &OS) {
506   auto ReaderOrErr = InstrProfReader::create(Filename);
507   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
508   if (ShowDetailedSummary && Cutoffs.empty()) {
509     Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
510   }
511   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
512   if (Error E = ReaderOrErr.takeError())
513     exitWithError(std::move(E), Filename);
514
515   auto Reader = std::move(ReaderOrErr.get());
516   bool IsIRInstr = Reader->isIRLevelProfile();
517   size_t ShownFunctions = 0;
518   int NumVPKind = IPVK_Last - IPVK_First + 1;
519   std::vector<ValueSitesStats> VPStats(NumVPKind);
520   for (const auto &Func : *Reader) {
521     bool Show =
522         ShowAllFunctions || (!ShowFunction.empty() &&
523                              Func.Name.find(ShowFunction) != Func.Name.npos);
524
525     bool doTextFormatDump = (Show && ShowCounts && TextFormat);
526
527     if (doTextFormatDump) {
528       InstrProfSymtab &Symtab = Reader->getSymtab();
529       InstrProfWriter::writeRecordInText(Func, Symtab, OS);
530       continue;
531     }
532
533     assert(Func.Counts.size() > 0 && "function missing entry counter");
534     Builder.addRecord(Func);
535
536     if (Show) {
537
538       if (!ShownFunctions)
539         OS << "Counters:\n";
540
541       ++ShownFunctions;
542
543       OS << "  " << Func.Name << ":\n"
544          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
545          << "    Counters: " << Func.Counts.size() << "\n";
546       if (!IsIRInstr)
547         OS << "    Function count: " << Func.Counts[0] << "\n";
548
549       if (ShowIndirectCallTargets)
550         OS << "    Indirect Call Site Count: "
551            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
552
553       uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
554       if (ShowMemOPSizes && NumMemOPCalls > 0)
555         OS << "    Number of Memory Intrinsics Calls: " << NumMemOPCalls
556            << "\n";
557
558       if (ShowCounts) {
559         OS << "    Block counts: [";
560         size_t Start = (IsIRInstr ? 0 : 1);
561         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
562           OS << (I == Start ? "" : ", ") << Func.Counts[I];
563         }
564         OS << "]\n";
565       }
566
567       if (ShowIndirectCallTargets) {
568         OS << "    Indirect Target Results:\n";
569         traverseAllValueSites(Func, IPVK_IndirectCallTarget,
570                               VPStats[IPVK_IndirectCallTarget], OS,
571                               &(Reader->getSymtab()));
572       }
573
574       if (ShowMemOPSizes && NumMemOPCalls > 0) {
575         OS << "    Memory Intrinsic Size Results:\n";
576         traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
577                               nullptr);
578       }
579     }
580   }
581   if (Reader->hasError())
582     exitWithError(Reader->getError(), Filename);
583
584   if (ShowCounts && TextFormat)
585     return 0;
586   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
587   if (ShowAllFunctions || !ShowFunction.empty())
588     OS << "Functions shown: " << ShownFunctions << "\n";
589   OS << "Total functions: " << PS->getNumFunctions() << "\n";
590   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
591   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
592
593   if (ShownFunctions && ShowIndirectCallTargets) {
594     OS << "Statistics for indirect call sites profile:\n";
595     showValueSitesStats(OS, IPVK_IndirectCallTarget,
596                         VPStats[IPVK_IndirectCallTarget]);
597   }
598
599   if (ShownFunctions && ShowMemOPSizes) {
600     OS << "Statistics for memory intrinsic calls sizes profile:\n";
601     showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
602   }
603
604   if (ShowDetailedSummary) {
605     OS << "Detailed summary:\n";
606     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
607     OS << "Total count: " << PS->getTotalCount() << "\n";
608     for (auto Entry : PS->getDetailedSummary()) {
609       OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
610          << " account for "
611          << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
612          << " percentage of the total counts.\n";
613     }
614   }
615   return 0;
616 }
617
618 static int showSampleProfile(const std::string &Filename, bool ShowCounts,
619                              bool ShowAllFunctions,
620                              const std::string &ShowFunction,
621                              raw_fd_ostream &OS) {
622   using namespace sampleprof;
623   LLVMContext Context;
624   auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
625   if (std::error_code EC = ReaderOrErr.getError())
626     exitWithErrorCode(EC, Filename);
627
628   auto Reader = std::move(ReaderOrErr.get());
629   if (std::error_code EC = Reader->read())
630     exitWithErrorCode(EC, Filename);
631
632   if (ShowAllFunctions || ShowFunction.empty())
633     Reader->dump(OS);
634   else
635     Reader->dumpFunctionProfile(ShowFunction, OS);
636
637   return 0;
638 }
639
640 static int show_main(int argc, const char *argv[]) {
641   cl::opt<std::string> Filename(cl::Positional, cl::Required,
642                                 cl::desc("<profdata-file>"));
643
644   cl::opt<bool> ShowCounts("counts", cl::init(false),
645                            cl::desc("Show counter values for shown functions"));
646   cl::opt<bool> TextFormat(
647       "text", cl::init(false),
648       cl::desc("Show instr profile data in text dump format"));
649   cl::opt<bool> ShowIndirectCallTargets(
650       "ic-targets", cl::init(false),
651       cl::desc("Show indirect call site target values for shown functions"));
652   cl::opt<bool> ShowMemOPSizes(
653       "memop-sizes", cl::init(false),
654       cl::desc("Show the profiled sizes of the memory intrinsic calls "
655                "for shown functions"));
656   cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
657                                     cl::desc("Show detailed profile summary"));
658   cl::list<uint32_t> DetailedSummaryCutoffs(
659       cl::CommaSeparated, "detailed-summary-cutoffs",
660       cl::desc(
661           "Cutoff percentages (times 10000) for generating detailed summary"),
662       cl::value_desc("800000,901000,999999"));
663   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
664                                  cl::desc("Details for every function"));
665   cl::opt<std::string> ShowFunction("function",
666                                     cl::desc("Details for matching functions"));
667
668   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
669                                       cl::init("-"), cl::desc("Output file"));
670   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
671                             cl::aliasopt(OutputFilename));
672   cl::opt<ProfileKinds> ProfileKind(
673       cl::desc("Profile kind:"), cl::init(instr),
674       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
675                  clEnumVal(sample, "Sample profile")));
676
677   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
678
679   if (OutputFilename.empty())
680     OutputFilename = "-";
681
682   std::error_code EC;
683   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
684   if (EC)
685     exitWithErrorCode(EC, OutputFilename);
686
687   if (ShowAllFunctions && !ShowFunction.empty())
688     errs() << "warning: -function argument ignored: showing all functions\n";
689
690   std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs.begin(),
691                                 DetailedSummaryCutoffs.end());
692   if (ProfileKind == instr)
693     return showInstrProfile(Filename, ShowCounts, ShowIndirectCallTargets,
694                             ShowMemOPSizes, ShowDetailedSummary,
695                             DetailedSummaryCutoffs, ShowAllFunctions,
696                             ShowFunction, TextFormat, OS);
697   else
698     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
699                              ShowFunction, OS);
700 }
701
702 int main(int argc, const char *argv[]) {
703   // Print a stack trace if we signal out.
704   sys::PrintStackTraceOnErrorSignal(argv[0]);
705   PrettyStackTraceProgram X(argc, argv);
706   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
707
708   StringRef ProgName(sys::path::filename(argv[0]));
709   if (argc > 1) {
710     int (*func)(int, const char *[]) = nullptr;
711
712     if (strcmp(argv[1], "merge") == 0)
713       func = merge_main;
714     else if (strcmp(argv[1], "show") == 0)
715       func = show_main;
716
717     if (func) {
718       std::string Invocation(ProgName.str() + " " + argv[1]);
719       argv[1] = Invocation.c_str();
720       return func(argc - 1, argv + 1);
721     }
722
723     if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
724         strcmp(argv[1], "--help") == 0) {
725
726       errs() << "OVERVIEW: LLVM profile data tools\n\n"
727              << "USAGE: " << ProgName << " <command> [args...]\n"
728              << "USAGE: " << ProgName << " <command> -help\n\n"
729              << "See each individual command --help for more details.\n"
730              << "Available commands: merge, show\n";
731       return 0;
732     }
733   }
734
735   if (argc < 2)
736     errs() << ProgName << ": No command specified!\n";
737   else
738     errs() << ProgName << ": Unknown command!\n";
739
740   errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
741   return 1;
742 }