1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // llvm-profdata merges .profdata files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/SmallSet.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/ProfileData/InstrProfReader.h"
18 #include "llvm/ProfileData/InstrProfWriter.h"
19 #include "llvm/ProfileData/ProfileCommon.h"
20 #include "llvm/ProfileData/SampleProfReader.h"
21 #include "llvm/ProfileData/SampleProfWriter.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/InitLLVM.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/Threading.h"
30 #include "llvm/Support/ThreadPool.h"
31 #include "llvm/Support/WithColor.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 
35 using namespace llvm;
36 
37 enum ProfileFormat {
38   PF_None = 0,
39   PF_Text,
40   PF_Compact_Binary,
41   PF_Ext_Binary,
42   PF_GCC,
43   PF_Binary
44 };
45 
46 static void warn(Twine Message, std::string Whence = "",
47                  std::string Hint = "") {
48   WithColor::warning();
49   if (!Whence.empty())
50     errs() << Whence << ": ";
51   errs() << Message << "\n";
52   if (!Hint.empty())
53     WithColor::note() << Hint << "\n";
54 }
55 
56 static void exitWithError(Twine Message, std::string Whence = "",
57                           std::string Hint = "") {
58   WithColor::error();
59   if (!Whence.empty())
60     errs() << Whence << ": ";
61   errs() << Message << "\n";
62   if (!Hint.empty())
63     WithColor::note() << Hint << "\n";
64   ::exit(1);
65 }
66 
67 static void exitWithError(Error E, StringRef Whence = "") {
68   if (E.isA<InstrProfError>()) {
69     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
70       instrprof_error instrError = IPE.get();
71       StringRef Hint = "";
72       if (instrError == instrprof_error::unrecognized_format) {
73         // Hint for common error of forgetting --sample for sample profiles.
74         Hint = "Perhaps you forgot to use the --sample option?";
75       }
76       exitWithError(IPE.message(), std::string(Whence), std::string(Hint));
77     });
78   }
79 
80   exitWithError(toString(std::move(E)), std::string(Whence));
81 }
82 
83 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
84   exitWithError(EC.message(), std::string(Whence));
85 }
86 
87 namespace {
88 enum ProfileKinds { instr, sample };
89 enum FailureMode { failIfAnyAreInvalid, failIfAllAreInvalid };
90 }
91 
92 static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
93                                  StringRef Whence = "") {
94   if (FailMode == failIfAnyAreInvalid)
95     exitWithErrorCode(EC, Whence);
96   else
97     warn(EC.message(), std::string(Whence));
98 }
99 
100 static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
101                                    StringRef WhenceFunction = "",
102                                    bool ShowHint = true) {
103   if (!WhenceFile.empty())
104     errs() << WhenceFile << ": ";
105   if (!WhenceFunction.empty())
106     errs() << WhenceFunction << ": ";
107 
108   auto IPE = instrprof_error::success;
109   E = handleErrors(std::move(E),
110                    [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
111                      IPE = E->get();
112                      return Error(std::move(E));
113                    });
114   errs() << toString(std::move(E)) << "\n";
115 
116   if (ShowHint) {
117     StringRef Hint = "";
118     if (IPE != instrprof_error::success) {
119       switch (IPE) {
120       case instrprof_error::hash_mismatch:
121       case instrprof_error::count_mismatch:
122       case instrprof_error::value_site_count_mismatch:
123         Hint = "Make sure that all profile data to be merged is generated "
124                "from the same binary.";
125         break;
126       default:
127         break;
128       }
129     }
130 
131     if (!Hint.empty())
132       errs() << Hint << "\n";
133   }
134 }
135 
136 namespace {
137 /// A remapper from original symbol names to new symbol names based on a file
138 /// containing a list of mappings from old name to new name.
139 class SymbolRemapper {
140   std::unique_ptr<MemoryBuffer> File;
141   DenseMap<StringRef, StringRef> RemappingTable;
142 
143 public:
144   /// Build a SymbolRemapper from a file containing a list of old/new symbols.
145   static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
146     auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
147     if (!BufOrError)
148       exitWithErrorCode(BufOrError.getError(), InputFile);
149 
150     auto Remapper = std::make_unique<SymbolRemapper>();
151     Remapper->File = std::move(BufOrError.get());
152 
153     for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
154          !LineIt.is_at_eof(); ++LineIt) {
155       std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
156       if (Parts.first.empty() || Parts.second.empty() ||
157           Parts.second.count(' ')) {
158         exitWithError("unexpected line in remapping file",
159                       (InputFile + ":" + Twine(LineIt.line_number())).str(),
160                       "expected 'old_symbol new_symbol'");
161       }
162       Remapper->RemappingTable.insert(Parts);
163     }
164     return Remapper;
165   }
166 
167   /// Attempt to map the given old symbol into a new symbol.
168   ///
169   /// \return The new symbol, or \p Name if no such symbol was found.
170   StringRef operator()(StringRef Name) {
171     StringRef New = RemappingTable.lookup(Name);
172     return New.empty() ? Name : New;
173   }
174 };
175 }
176 
177 struct WeightedFile {
178   std::string Filename;
179   uint64_t Weight;
180 };
181 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
182 
183 /// Keep track of merged data and reported errors.
184 struct WriterContext {
185   std::mutex Lock;
186   InstrProfWriter Writer;
187   std::vector<std::pair<Error, std::string>> Errors;
188   std::mutex &ErrLock;
189   SmallSet<instrprof_error, 4> &WriterErrorCodes;
190 
191   WriterContext(bool IsSparse, std::mutex &ErrLock,
192                 SmallSet<instrprof_error, 4> &WriterErrorCodes)
193       : Lock(), Writer(IsSparse), Errors(), ErrLock(ErrLock),
194         WriterErrorCodes(WriterErrorCodes) {}
195 };
196 
197 /// Computer the overlap b/w profile BaseFilename and TestFileName,
198 /// and store the program level result to Overlap.
199 static void overlapInput(const std::string &BaseFilename,
200                          const std::string &TestFilename, WriterContext *WC,
201                          OverlapStats &Overlap,
202                          const OverlapFuncFilters &FuncFilter,
203                          raw_fd_ostream &OS, bool IsCS) {
204   auto ReaderOrErr = InstrProfReader::create(TestFilename);
205   if (Error E = ReaderOrErr.takeError()) {
206     // Skip the empty profiles by returning sliently.
207     instrprof_error IPE = InstrProfError::take(std::move(E));
208     if (IPE != instrprof_error::empty_raw_profile)
209       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), TestFilename);
210     return;
211   }
212 
213   auto Reader = std::move(ReaderOrErr.get());
214   for (auto &I : *Reader) {
215     OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
216     FuncOverlap.setFuncInfo(I.Name, I.Hash);
217 
218     WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
219     FuncOverlap.dump(OS);
220   }
221 }
222 
223 /// Load an input into a writer context.
224 static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
225                       WriterContext *WC) {
226   std::unique_lock<std::mutex> CtxGuard{WC->Lock};
227 
228   // Copy the filename, because llvm::ThreadPool copied the input "const
229   // WeightedFile &" by value, making a reference to the filename within it
230   // invalid outside of this packaged task.
231   std::string Filename = Input.Filename;
232 
233   auto ReaderOrErr = InstrProfReader::create(Input.Filename);
234   if (Error E = ReaderOrErr.takeError()) {
235     // Skip the empty profiles by returning sliently.
236     instrprof_error IPE = InstrProfError::take(std::move(E));
237     if (IPE != instrprof_error::empty_raw_profile)
238       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename);
239     return;
240   }
241 
242   auto Reader = std::move(ReaderOrErr.get());
243   bool IsIRProfile = Reader->isIRLevelProfile();
244   bool HasCSIRProfile = Reader->hasCSIRLevelProfile();
245   if (WC->Writer.setIsIRLevelProfile(IsIRProfile, HasCSIRProfile)) {
246     WC->Errors.emplace_back(
247         make_error<StringError>(
248             "Merge IR generated profile with Clang generated profile.",
249             std::error_code()),
250         Filename);
251     return;
252   }
253 
254   for (auto &I : *Reader) {
255     if (Remapper)
256       I.Name = (*Remapper)(I.Name);
257     const StringRef FuncName = I.Name;
258     bool Reported = false;
259     WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
260       if (Reported) {
261         consumeError(std::move(E));
262         return;
263       }
264       Reported = true;
265       // Only show hint the first time an error occurs.
266       instrprof_error IPE = InstrProfError::take(std::move(E));
267       std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
268       bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
269       handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
270                              FuncName, firstTime);
271     });
272   }
273   if (Reader->hasError())
274     if (Error E = Reader->getError())
275       WC->Errors.emplace_back(std::move(E), Filename);
276 }
277 
278 /// Merge the \p Src writer context into \p Dst.
279 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
280   for (auto &ErrorPair : Src->Errors)
281     Dst->Errors.push_back(std::move(ErrorPair));
282   Src->Errors.clear();
283 
284   Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
285     instrprof_error IPE = InstrProfError::take(std::move(E));
286     std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
287     bool firstTime = Dst->WriterErrorCodes.insert(IPE).second;
288     if (firstTime)
289       warn(toString(make_error<InstrProfError>(IPE)));
290   });
291 }
292 
293 static void mergeInstrProfile(const WeightedFileVector &Inputs,
294                               SymbolRemapper *Remapper,
295                               StringRef OutputFilename,
296                               ProfileFormat OutputFormat, bool OutputSparse,
297                               unsigned NumThreads, FailureMode FailMode) {
298   if (OutputFilename.compare("-") == 0)
299     exitWithError("Cannot write indexed profdata format to stdout.");
300 
301   if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
302       OutputFormat != PF_Ext_Binary && OutputFormat != PF_Text)
303     exitWithError("Unknown format is specified.");
304 
305   std::mutex ErrorLock;
306   SmallSet<instrprof_error, 4> WriterErrorCodes;
307 
308   // If NumThreads is not specified, auto-detect a good default.
309   if (NumThreads == 0)
310     NumThreads =
311         std::min(hardware_concurrency(), unsigned((Inputs.size() + 1) / 2));
312 
313   // Initialize the writer contexts.
314   SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
315   for (unsigned I = 0; I < NumThreads; ++I)
316     Contexts.emplace_back(std::make_unique<WriterContext>(
317         OutputSparse, ErrorLock, WriterErrorCodes));
318 
319   if (NumThreads == 1) {
320     for (const auto &Input : Inputs)
321       loadInput(Input, Remapper, Contexts[0].get());
322   } else {
323     ThreadPool Pool(NumThreads);
324 
325     // Load the inputs in parallel (N/NumThreads serial steps).
326     unsigned Ctx = 0;
327     for (const auto &Input : Inputs) {
328       Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get());
329       Ctx = (Ctx + 1) % NumThreads;
330     }
331     Pool.wait();
332 
333     // Merge the writer contexts together (~ lg(NumThreads) serial steps).
334     unsigned Mid = Contexts.size() / 2;
335     unsigned End = Contexts.size();
336     assert(Mid > 0 && "Expected more than one context");
337     do {
338       for (unsigned I = 0; I < Mid; ++I)
339         Pool.async(mergeWriterContexts, Contexts[I].get(),
340                    Contexts[I + Mid].get());
341       Pool.wait();
342       if (End & 1) {
343         Pool.async(mergeWriterContexts, Contexts[0].get(),
344                    Contexts[End - 1].get());
345         Pool.wait();
346       }
347       End = Mid;
348       Mid /= 2;
349     } while (Mid > 0);
350   }
351 
352   // Handle deferred errors encountered during merging. If the number of errors
353   // is equal to the number of inputs the merge failed.
354   unsigned NumErrors = 0;
355   for (std::unique_ptr<WriterContext> &WC : Contexts) {
356     for (auto &ErrorPair : WC->Errors) {
357       ++NumErrors;
358       warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
359     }
360   }
361   if (NumErrors == Inputs.size() ||
362       (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
363     exitWithError("No profiles could be merged.");
364 
365   std::error_code EC;
366   raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::OF_None);
367   if (EC)
368     exitWithErrorCode(EC, OutputFilename);
369 
370   InstrProfWriter &Writer = Contexts[0]->Writer;
371   if (OutputFormat == PF_Text) {
372     if (Error E = Writer.writeText(Output))
373       exitWithError(std::move(E));
374   } else {
375     Writer.write(Output);
376   }
377 }
378 
379 /// Make a copy of the given function samples with all symbol names remapped
380 /// by the provided symbol remapper.
381 static sampleprof::FunctionSamples
382 remapSamples(const sampleprof::FunctionSamples &Samples,
383              SymbolRemapper &Remapper, sampleprof_error &Error) {
384   sampleprof::FunctionSamples Result;
385   Result.setName(Remapper(Samples.getName()));
386   Result.addTotalSamples(Samples.getTotalSamples());
387   Result.addHeadSamples(Samples.getHeadSamples());
388   for (const auto &BodySample : Samples.getBodySamples()) {
389     Result.addBodySamples(BodySample.first.LineOffset,
390                           BodySample.first.Discriminator,
391                           BodySample.second.getSamples());
392     for (const auto &Target : BodySample.second.getCallTargets()) {
393       Result.addCalledTargetSamples(BodySample.first.LineOffset,
394                                     BodySample.first.Discriminator,
395                                     Remapper(Target.first()), Target.second);
396     }
397   }
398   for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
399     sampleprof::FunctionSamplesMap &Target =
400         Result.functionSamplesAt(CallsiteSamples.first);
401     for (const auto &Callsite : CallsiteSamples.second) {
402       sampleprof::FunctionSamples Remapped =
403           remapSamples(Callsite.second, Remapper, Error);
404       MergeResult(Error,
405                   Target[std::string(Remapped.getName())].merge(Remapped));
406     }
407   }
408   return Result;
409 }
410 
411 static sampleprof::SampleProfileFormat FormatMap[] = {
412     sampleprof::SPF_None,
413     sampleprof::SPF_Text,
414     sampleprof::SPF_Compact_Binary,
415     sampleprof::SPF_Ext_Binary,
416     sampleprof::SPF_GCC,
417     sampleprof::SPF_Binary};
418 
419 static std::unique_ptr<MemoryBuffer>
420 getInputFileBuf(const StringRef &InputFile) {
421   if (InputFile == "")
422     return {};
423 
424   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
425   if (!BufOrError)
426     exitWithErrorCode(BufOrError.getError(), InputFile);
427 
428   return std::move(*BufOrError);
429 }
430 
431 static void populateProfileSymbolList(MemoryBuffer *Buffer,
432                                       sampleprof::ProfileSymbolList &PSL) {
433   if (!Buffer)
434     return;
435 
436   SmallVector<StringRef, 32> SymbolVec;
437   StringRef Data = Buffer->getBuffer();
438   Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
439 
440   for (StringRef symbol : SymbolVec)
441     PSL.add(symbol);
442 }
443 
444 static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer,
445                                   ProfileFormat OutputFormat,
446                                   MemoryBuffer *Buffer,
447                                   sampleprof::ProfileSymbolList &WriterList,
448                                   bool CompressAllSections) {
449   populateProfileSymbolList(Buffer, WriterList);
450   if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
451     warn("Profile Symbol list is not empty but the output format is not "
452          "ExtBinary format. The list will be lost in the output. ");
453 
454   Writer.setProfileSymbolList(&WriterList);
455 
456   if (CompressAllSections) {
457     if (OutputFormat != PF_Ext_Binary) {
458       warn("-compress-all-section is ignored. Specify -extbinary to enable it");
459     } else {
460       auto ExtBinaryWriter =
461           static_cast<sampleprof::SampleProfileWriterExtBinary *>(&Writer);
462       ExtBinaryWriter->setToCompressAllSections();
463     }
464   }
465 }
466 
467 static void mergeSampleProfile(const WeightedFileVector &Inputs,
468                                SymbolRemapper *Remapper,
469                                StringRef OutputFilename,
470                                ProfileFormat OutputFormat,
471                                StringRef ProfileSymbolListFile,
472                                bool CompressAllSections, FailureMode FailMode) {
473   using namespace sampleprof;
474   StringMap<FunctionSamples> ProfileMap;
475   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
476   LLVMContext Context;
477   sampleprof::ProfileSymbolList WriterList;
478   for (const auto &Input : Inputs) {
479     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
480     if (std::error_code EC = ReaderOrErr.getError()) {
481       warnOrExitGivenError(FailMode, EC, Input.Filename);
482       continue;
483     }
484 
485     // We need to keep the readers around until after all the files are
486     // read so that we do not lose the function names stored in each
487     // reader's memory. The function names are needed to write out the
488     // merged profile map.
489     Readers.push_back(std::move(ReaderOrErr.get()));
490     const auto Reader = Readers.back().get();
491     if (std::error_code EC = Reader->read()) {
492       warnOrExitGivenError(FailMode, EC, Input.Filename);
493       Readers.pop_back();
494       continue;
495     }
496 
497     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
498     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
499                                               E = Profiles.end();
500          I != E; ++I) {
501       sampleprof_error Result = sampleprof_error::success;
502       FunctionSamples Remapped =
503           Remapper ? remapSamples(I->second, *Remapper, Result)
504                    : FunctionSamples();
505       FunctionSamples &Samples = Remapper ? Remapped : I->second;
506       StringRef FName = Samples.getName();
507       MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight));
508       if (Result != sampleprof_error::success) {
509         std::error_code EC = make_error_code(Result);
510         handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
511       }
512     }
513 
514     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
515         Reader->getProfileSymbolList();
516     if (ReaderList)
517       WriterList.merge(*ReaderList);
518   }
519   auto WriterOrErr =
520       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
521   if (std::error_code EC = WriterOrErr.getError())
522     exitWithErrorCode(EC, OutputFilename);
523 
524   auto Writer = std::move(WriterOrErr.get());
525   // WriterList will have StringRef refering to string in Buffer.
526   // Make sure Buffer lives as long as WriterList.
527   auto Buffer = getInputFileBuf(ProfileSymbolListFile);
528   handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList,
529                         CompressAllSections);
530   Writer->write(ProfileMap);
531 }
532 
533 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
534   StringRef WeightStr, FileName;
535   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
536 
537   uint64_t Weight;
538   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
539     exitWithError("Input weight must be a positive integer.");
540 
541   return {std::string(FileName), Weight};
542 }
543 
544 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
545   StringRef Filename = WF.Filename;
546   uint64_t Weight = WF.Weight;
547 
548   // If it's STDIN just pass it on.
549   if (Filename == "-") {
550     WNI.push_back({std::string(Filename), Weight});
551     return;
552   }
553 
554   llvm::sys::fs::file_status Status;
555   llvm::sys::fs::status(Filename, Status);
556   if (!llvm::sys::fs::exists(Status))
557     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
558                       Filename);
559   // If it's a source file, collect it.
560   if (llvm::sys::fs::is_regular_file(Status)) {
561     WNI.push_back({std::string(Filename), Weight});
562     return;
563   }
564 
565   if (llvm::sys::fs::is_directory(Status)) {
566     std::error_code EC;
567     for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
568          F != E && !EC; F.increment(EC)) {
569       if (llvm::sys::fs::is_regular_file(F->path())) {
570         addWeightedInput(WNI, {F->path(), Weight});
571       }
572     }
573     if (EC)
574       exitWithErrorCode(EC, Filename);
575   }
576 }
577 
578 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
579                                     WeightedFileVector &WFV) {
580   if (!Buffer)
581     return;
582 
583   SmallVector<StringRef, 8> Entries;
584   StringRef Data = Buffer->getBuffer();
585   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
586   for (const StringRef &FileWeightEntry : Entries) {
587     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
588     // Skip comments.
589     if (SanitizedEntry.startswith("#"))
590       continue;
591     // If there's no comma, it's an unweighted profile.
592     else if (SanitizedEntry.find(',') == StringRef::npos)
593       addWeightedInput(WFV, {std::string(SanitizedEntry), 1});
594     else
595       addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
596   }
597 }
598 
599 static int merge_main(int argc, const char *argv[]) {
600   cl::list<std::string> InputFilenames(cl::Positional,
601                                        cl::desc("<filename...>"));
602   cl::list<std::string> WeightedInputFilenames("weighted-input",
603                                                cl::desc("<weight>,<filename>"));
604   cl::opt<std::string> InputFilenamesFile(
605       "input-files", cl::init(""),
606       cl::desc("Path to file containing newline-separated "
607                "[<weight>,]<filename> entries"));
608   cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
609                                 cl::aliasopt(InputFilenamesFile));
610   cl::opt<bool> DumpInputFileList(
611       "dump-input-file-list", cl::init(false), cl::Hidden,
612       cl::desc("Dump the list of input files and their weights, then exit"));
613   cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
614                                      cl::desc("Symbol remapping file"));
615   cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
616                            cl::aliasopt(RemappingFile));
617   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
618                                       cl::init("-"), cl::Required,
619                                       cl::desc("Output file"));
620   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
621                             cl::aliasopt(OutputFilename));
622   cl::opt<ProfileKinds> ProfileKind(
623       cl::desc("Profile kind:"), cl::init(instr),
624       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
625                  clEnumVal(sample, "Sample profile")));
626   cl::opt<ProfileFormat> OutputFormat(
627       cl::desc("Format of output profile"), cl::init(PF_Binary),
628       cl::values(
629           clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
630           clEnumValN(PF_Compact_Binary, "compbinary",
631                      "Compact binary encoding"),
632           clEnumValN(PF_Ext_Binary, "extbinary", "Extensible binary encoding"),
633           clEnumValN(PF_Text, "text", "Text encoding"),
634           clEnumValN(PF_GCC, "gcc",
635                      "GCC encoding (only meaningful for -sample)")));
636   cl::opt<FailureMode> FailureMode(
637       "failure-mode", cl::init(failIfAnyAreInvalid), cl::desc("Failure mode:"),
638       cl::values(clEnumValN(failIfAnyAreInvalid, "any",
639                             "Fail if any profile is invalid."),
640                  clEnumValN(failIfAllAreInvalid, "all",
641                             "Fail only if all profiles are invalid.")));
642   cl::opt<bool> OutputSparse("sparse", cl::init(false),
643       cl::desc("Generate a sparse profile (only meaningful for -instr)"));
644   cl::opt<unsigned> NumThreads(
645       "num-threads", cl::init(0),
646       cl::desc("Number of merge threads to use (default: autodetect)"));
647   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
648                         cl::aliasopt(NumThreads));
649   cl::opt<std::string> ProfileSymbolListFile(
650       "prof-sym-list", cl::init(""),
651       cl::desc("Path to file containing the list of function symbols "
652                "used to populate profile symbol list"));
653   cl::opt<bool> CompressAllSections(
654       "compress-all-sections", cl::init(false), cl::Hidden,
655       cl::desc("Compress all sections when writing the profile (only "
656                "meaningful for -extbinary)"));
657 
658   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
659 
660   WeightedFileVector WeightedInputs;
661   for (StringRef Filename : InputFilenames)
662     addWeightedInput(WeightedInputs, {std::string(Filename), 1});
663   for (StringRef WeightedFilename : WeightedInputFilenames)
664     addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
665 
666   // Make sure that the file buffer stays alive for the duration of the
667   // weighted input vector's lifetime.
668   auto Buffer = getInputFileBuf(InputFilenamesFile);
669   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
670 
671   if (WeightedInputs.empty())
672     exitWithError("No input files specified. See " +
673                   sys::path::filename(argv[0]) + " -help");
674 
675   if (DumpInputFileList) {
676     for (auto &WF : WeightedInputs)
677       outs() << WF.Weight << "," << WF.Filename << "\n";
678     return 0;
679   }
680 
681   std::unique_ptr<SymbolRemapper> Remapper;
682   if (!RemappingFile.empty())
683     Remapper = SymbolRemapper::create(RemappingFile);
684 
685   if (ProfileKind == instr)
686     mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
687                       OutputFormat, OutputSparse, NumThreads, FailureMode);
688   else
689     mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
690                        OutputFormat, ProfileSymbolListFile, CompressAllSections,
691                        FailureMode);
692 
693   return 0;
694 }
695 
696 /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
697 static void overlapInstrProfile(const std::string &BaseFilename,
698                                 const std::string &TestFilename,
699                                 const OverlapFuncFilters &FuncFilter,
700                                 raw_fd_ostream &OS, bool IsCS) {
701   std::mutex ErrorLock;
702   SmallSet<instrprof_error, 4> WriterErrorCodes;
703   WriterContext Context(false, ErrorLock, WriterErrorCodes);
704   WeightedFile WeightedInput{BaseFilename, 1};
705   OverlapStats Overlap;
706   Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS);
707   if (E)
708     exitWithError(std::move(E), "Error in getting profile count sums");
709   if (Overlap.Base.CountSum < 1.0f) {
710     OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
711     exit(0);
712   }
713   if (Overlap.Test.CountSum < 1.0f) {
714     OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
715     exit(0);
716   }
717   loadInput(WeightedInput, nullptr, &Context);
718   overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
719                IsCS);
720   Overlap.dump(OS);
721 }
722 
723 static int overlap_main(int argc, const char *argv[]) {
724   cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
725                                     cl::desc("<base profile file>"));
726   cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
727                                     cl::desc("<test profile file>"));
728   cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
729                               cl::desc("Output file"));
730   cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
731   cl::opt<bool> IsCS("cs", cl::init(false),
732                      cl::desc("For context sensitive counts"));
733   cl::opt<unsigned long long> ValueCutoff(
734       "value-cutoff", cl::init(-1),
735       cl::desc(
736           "Function level overlap information for every function in test "
737           "profile with max count value greater then the parameter value"));
738   cl::opt<std::string> FuncNameFilter(
739       "function",
740       cl::desc("Function level overlap information for matching functions"));
741   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
742 
743   std::error_code EC;
744   raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_Text);
745   if (EC)
746     exitWithErrorCode(EC, Output);
747 
748   overlapInstrProfile(BaseFilename, TestFilename,
749                       OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
750                       IsCS);
751 
752   return 0;
753 }
754 
755 typedef struct ValueSitesStats {
756   ValueSitesStats()
757       : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
758         TotalNumValues(0) {}
759   uint64_t TotalNumValueSites;
760   uint64_t TotalNumValueSitesWithValueProfile;
761   uint64_t TotalNumValues;
762   std::vector<unsigned> ValueSitesHistogram;
763 } ValueSitesStats;
764 
765 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
766                                   ValueSitesStats &Stats, raw_fd_ostream &OS,
767                                   InstrProfSymtab *Symtab) {
768   uint32_t NS = Func.getNumValueSites(VK);
769   Stats.TotalNumValueSites += NS;
770   for (size_t I = 0; I < NS; ++I) {
771     uint32_t NV = Func.getNumValueDataForSite(VK, I);
772     std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
773     Stats.TotalNumValues += NV;
774     if (NV) {
775       Stats.TotalNumValueSitesWithValueProfile++;
776       if (NV > Stats.ValueSitesHistogram.size())
777         Stats.ValueSitesHistogram.resize(NV, 0);
778       Stats.ValueSitesHistogram[NV - 1]++;
779     }
780 
781     uint64_t SiteSum = 0;
782     for (uint32_t V = 0; V < NV; V++)
783       SiteSum += VD[V].Count;
784     if (SiteSum == 0)
785       SiteSum = 1;
786 
787     for (uint32_t V = 0; V < NV; V++) {
788       OS << "\t[ " << format("%2u", I) << ", ";
789       if (Symtab == nullptr)
790         OS << format("%4" PRIu64, VD[V].Value);
791       else
792         OS << Symtab->getFuncName(VD[V].Value);
793       OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
794          << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
795     }
796   }
797 }
798 
799 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
800                                 ValueSitesStats &Stats) {
801   OS << "  Total number of sites: " << Stats.TotalNumValueSites << "\n";
802   OS << "  Total number of sites with values: "
803      << Stats.TotalNumValueSitesWithValueProfile << "\n";
804   OS << "  Total number of profiled values: " << Stats.TotalNumValues << "\n";
805 
806   OS << "  Value sites histogram:\n\tNumTargets, SiteCount\n";
807   for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
808     if (Stats.ValueSitesHistogram[I] > 0)
809       OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
810   }
811 }
812 
813 static int showInstrProfile(const std::string &Filename, bool ShowCounts,
814                             uint32_t TopN, bool ShowIndirectCallTargets,
815                             bool ShowMemOPSizes, bool ShowDetailedSummary,
816                             std::vector<uint32_t> DetailedSummaryCutoffs,
817                             bool ShowAllFunctions, bool ShowCS,
818                             uint64_t ValueCutoff, bool OnlyListBelow,
819                             const std::string &ShowFunction, bool TextFormat,
820                             raw_fd_ostream &OS) {
821   auto ReaderOrErr = InstrProfReader::create(Filename);
822   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
823   if (ShowDetailedSummary && Cutoffs.empty()) {
824     Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
825   }
826   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
827   if (Error E = ReaderOrErr.takeError())
828     exitWithError(std::move(E), Filename);
829 
830   auto Reader = std::move(ReaderOrErr.get());
831   bool IsIRInstr = Reader->isIRLevelProfile();
832   size_t ShownFunctions = 0;
833   size_t BelowCutoffFunctions = 0;
834   int NumVPKind = IPVK_Last - IPVK_First + 1;
835   std::vector<ValueSitesStats> VPStats(NumVPKind);
836 
837   auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
838                    const std::pair<std::string, uint64_t> &v2) {
839     return v1.second > v2.second;
840   };
841 
842   std::priority_queue<std::pair<std::string, uint64_t>,
843                       std::vector<std::pair<std::string, uint64_t>>,
844                       decltype(MinCmp)>
845       HottestFuncs(MinCmp);
846 
847   if (!TextFormat && OnlyListBelow) {
848     OS << "The list of functions with the maximum counter less than "
849        << ValueCutoff << ":\n";
850   }
851 
852   // Add marker so that IR-level instrumentation round-trips properly.
853   if (TextFormat && IsIRInstr)
854     OS << ":ir\n";
855 
856   for (const auto &Func : *Reader) {
857     if (Reader->isIRLevelProfile()) {
858       bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
859       if (FuncIsCS != ShowCS)
860         continue;
861     }
862     bool Show =
863         ShowAllFunctions || (!ShowFunction.empty() &&
864                              Func.Name.find(ShowFunction) != Func.Name.npos);
865 
866     bool doTextFormatDump = (Show && TextFormat);
867 
868     if (doTextFormatDump) {
869       InstrProfSymtab &Symtab = Reader->getSymtab();
870       InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
871                                          OS);
872       continue;
873     }
874 
875     assert(Func.Counts.size() > 0 && "function missing entry counter");
876     Builder.addRecord(Func);
877 
878     uint64_t FuncMax = 0;
879     uint64_t FuncSum = 0;
880     for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
881       FuncMax = std::max(FuncMax, Func.Counts[I]);
882       FuncSum += Func.Counts[I];
883     }
884 
885     if (FuncMax < ValueCutoff) {
886       ++BelowCutoffFunctions;
887       if (OnlyListBelow) {
888         OS << "  " << Func.Name << ": (Max = " << FuncMax
889            << " Sum = " << FuncSum << ")\n";
890       }
891       continue;
892     } else if (OnlyListBelow)
893       continue;
894 
895     if (TopN) {
896       if (HottestFuncs.size() == TopN) {
897         if (HottestFuncs.top().second < FuncMax) {
898           HottestFuncs.pop();
899           HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
900         }
901       } else
902         HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
903     }
904 
905     if (Show) {
906       if (!ShownFunctions)
907         OS << "Counters:\n";
908 
909       ++ShownFunctions;
910 
911       OS << "  " << Func.Name << ":\n"
912          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
913          << "    Counters: " << Func.Counts.size() << "\n";
914       if (!IsIRInstr)
915         OS << "    Function count: " << Func.Counts[0] << "\n";
916 
917       if (ShowIndirectCallTargets)
918         OS << "    Indirect Call Site Count: "
919            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
920 
921       uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
922       if (ShowMemOPSizes && NumMemOPCalls > 0)
923         OS << "    Number of Memory Intrinsics Calls: " << NumMemOPCalls
924            << "\n";
925 
926       if (ShowCounts) {
927         OS << "    Block counts: [";
928         size_t Start = (IsIRInstr ? 0 : 1);
929         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
930           OS << (I == Start ? "" : ", ") << Func.Counts[I];
931         }
932         OS << "]\n";
933       }
934 
935       if (ShowIndirectCallTargets) {
936         OS << "    Indirect Target Results:\n";
937         traverseAllValueSites(Func, IPVK_IndirectCallTarget,
938                               VPStats[IPVK_IndirectCallTarget], OS,
939                               &(Reader->getSymtab()));
940       }
941 
942       if (ShowMemOPSizes && NumMemOPCalls > 0) {
943         OS << "    Memory Intrinsic Size Results:\n";
944         traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
945                               nullptr);
946       }
947     }
948   }
949   if (Reader->hasError())
950     exitWithError(Reader->getError(), Filename);
951 
952   if (TextFormat)
953     return 0;
954   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
955   OS << "Instrumentation level: "
956      << (Reader->isIRLevelProfile() ? "IR" : "Front-end") << "\n";
957   if (ShowAllFunctions || !ShowFunction.empty())
958     OS << "Functions shown: " << ShownFunctions << "\n";
959   OS << "Total functions: " << PS->getNumFunctions() << "\n";
960   if (ValueCutoff > 0) {
961     OS << "Number of functions with maximum count (< " << ValueCutoff
962        << "): " << BelowCutoffFunctions << "\n";
963     OS << "Number of functions with maximum count (>= " << ValueCutoff
964        << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
965   }
966   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
967   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
968 
969   if (TopN) {
970     std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
971     while (!HottestFuncs.empty()) {
972       SortedHottestFuncs.emplace_back(HottestFuncs.top());
973       HottestFuncs.pop();
974     }
975     OS << "Top " << TopN
976        << " functions with the largest internal block counts: \n";
977     for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
978       OS << "  " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
979   }
980 
981   if (ShownFunctions && ShowIndirectCallTargets) {
982     OS << "Statistics for indirect call sites profile:\n";
983     showValueSitesStats(OS, IPVK_IndirectCallTarget,
984                         VPStats[IPVK_IndirectCallTarget]);
985   }
986 
987   if (ShownFunctions && ShowMemOPSizes) {
988     OS << "Statistics for memory intrinsic calls sizes profile:\n";
989     showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
990   }
991 
992   if (ShowDetailedSummary) {
993     OS << "Detailed summary:\n";
994     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
995     OS << "Total count: " << PS->getTotalCount() << "\n";
996     for (auto Entry : PS->getDetailedSummary()) {
997       OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
998          << " account for "
999          << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
1000          << " percentage of the total counts.\n";
1001     }
1002   }
1003   return 0;
1004 }
1005 
1006 static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
1007                             raw_fd_ostream &OS) {
1008   if (!Reader->dumpSectionInfo(OS)) {
1009     WithColor::warning() << "-show-sec-info-only is only supported for "
1010                          << "sample profile in extbinary format and is "
1011                          << "ignored for other formats.\n";
1012     return;
1013   }
1014 }
1015 
1016 static int showSampleProfile(const std::string &Filename, bool ShowCounts,
1017                              bool ShowAllFunctions,
1018                              const std::string &ShowFunction,
1019                              bool ShowProfileSymbolList,
1020                              bool ShowSectionInfoOnly, raw_fd_ostream &OS) {
1021   using namespace sampleprof;
1022   LLVMContext Context;
1023   auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
1024   if (std::error_code EC = ReaderOrErr.getError())
1025     exitWithErrorCode(EC, Filename);
1026 
1027   auto Reader = std::move(ReaderOrErr.get());
1028 
1029   if (ShowSectionInfoOnly) {
1030     showSectionInfo(Reader.get(), OS);
1031     return 0;
1032   }
1033 
1034   if (std::error_code EC = Reader->read())
1035     exitWithErrorCode(EC, Filename);
1036 
1037   if (ShowAllFunctions || ShowFunction.empty())
1038     Reader->dump(OS);
1039   else
1040     Reader->dumpFunctionProfile(ShowFunction, OS);
1041 
1042   if (ShowProfileSymbolList) {
1043     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
1044         Reader->getProfileSymbolList();
1045     ReaderList->dump(OS);
1046   }
1047 
1048   return 0;
1049 }
1050 
1051 static int show_main(int argc, const char *argv[]) {
1052   cl::opt<std::string> Filename(cl::Positional, cl::Required,
1053                                 cl::desc("<profdata-file>"));
1054 
1055   cl::opt<bool> ShowCounts("counts", cl::init(false),
1056                            cl::desc("Show counter values for shown functions"));
1057   cl::opt<bool> TextFormat(
1058       "text", cl::init(false),
1059       cl::desc("Show instr profile data in text dump format"));
1060   cl::opt<bool> ShowIndirectCallTargets(
1061       "ic-targets", cl::init(false),
1062       cl::desc("Show indirect call site target values for shown functions"));
1063   cl::opt<bool> ShowMemOPSizes(
1064       "memop-sizes", cl::init(false),
1065       cl::desc("Show the profiled sizes of the memory intrinsic calls "
1066                "for shown functions"));
1067   cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
1068                                     cl::desc("Show detailed profile summary"));
1069   cl::list<uint32_t> DetailedSummaryCutoffs(
1070       cl::CommaSeparated, "detailed-summary-cutoffs",
1071       cl::desc(
1072           "Cutoff percentages (times 10000) for generating detailed summary"),
1073       cl::value_desc("800000,901000,999999"));
1074   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
1075                                  cl::desc("Details for every function"));
1076   cl::opt<bool> ShowCS("showcs", cl::init(false),
1077                        cl::desc("Show context sensitive counts"));
1078   cl::opt<std::string> ShowFunction("function",
1079                                     cl::desc("Details for matching functions"));
1080 
1081   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
1082                                       cl::init("-"), cl::desc("Output file"));
1083   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
1084                             cl::aliasopt(OutputFilename));
1085   cl::opt<ProfileKinds> ProfileKind(
1086       cl::desc("Profile kind:"), cl::init(instr),
1087       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
1088                  clEnumVal(sample, "Sample profile")));
1089   cl::opt<uint32_t> TopNFunctions(
1090       "topn", cl::init(0),
1091       cl::desc("Show the list of functions with the largest internal counts"));
1092   cl::opt<uint32_t> ValueCutoff(
1093       "value-cutoff", cl::init(0),
1094       cl::desc("Set the count value cutoff. Functions with the maximum count "
1095                "less than this value will not be printed out. (Default is 0)"));
1096   cl::opt<bool> OnlyListBelow(
1097       "list-below-cutoff", cl::init(false),
1098       cl::desc("Only output names of functions whose max count values are "
1099                "below the cutoff value"));
1100   cl::opt<bool> ShowProfileSymbolList(
1101       "show-prof-sym-list", cl::init(false),
1102       cl::desc("Show profile symbol list if it exists in the profile. "));
1103   cl::opt<bool> ShowSectionInfoOnly(
1104       "show-sec-info-only", cl::init(false),
1105       cl::desc("Show the information of each section in the sample profile. "
1106                "The flag is only usable when the sample profile is in "
1107                "extbinary format"));
1108 
1109   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
1110 
1111   if (OutputFilename.empty())
1112     OutputFilename = "-";
1113 
1114   if (!Filename.compare(OutputFilename)) {
1115     errs() << sys::path::filename(argv[0])
1116            << ": Input file name cannot be the same as the output file name!\n";
1117     return 1;
1118   }
1119 
1120   std::error_code EC;
1121   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_Text);
1122   if (EC)
1123     exitWithErrorCode(EC, OutputFilename);
1124 
1125   if (ShowAllFunctions && !ShowFunction.empty())
1126     WithColor::warning() << "-function argument ignored: showing all functions\n";
1127 
1128   if (ProfileKind == instr)
1129     return showInstrProfile(Filename, ShowCounts, TopNFunctions,
1130                             ShowIndirectCallTargets, ShowMemOPSizes,
1131                             ShowDetailedSummary, DetailedSummaryCutoffs,
1132                             ShowAllFunctions, ShowCS, ValueCutoff,
1133                             OnlyListBelow, ShowFunction, TextFormat, OS);
1134   else
1135     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
1136                              ShowFunction, ShowProfileSymbolList,
1137                              ShowSectionInfoOnly, OS);
1138 }
1139 
1140 int main(int argc, const char *argv[]) {
1141   InitLLVM X(argc, argv);
1142 
1143   StringRef ProgName(sys::path::filename(argv[0]));
1144   if (argc > 1) {
1145     int (*func)(int, const char *[]) = nullptr;
1146 
1147     if (strcmp(argv[1], "merge") == 0)
1148       func = merge_main;
1149     else if (strcmp(argv[1], "show") == 0)
1150       func = show_main;
1151     else if (strcmp(argv[1], "overlap") == 0)
1152       func = overlap_main;
1153 
1154     if (func) {
1155       std::string Invocation(ProgName.str() + " " + argv[1]);
1156       argv[1] = Invocation.c_str();
1157       return func(argc - 1, argv + 1);
1158     }
1159 
1160     if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
1161         strcmp(argv[1], "--help") == 0) {
1162 
1163       errs() << "OVERVIEW: LLVM profile data tools\n\n"
1164              << "USAGE: " << ProgName << " <command> [args...]\n"
1165              << "USAGE: " << ProgName << " <command> -help\n\n"
1166              << "See each individual command --help for more details.\n"
1167              << "Available commands: merge, show, overlap\n";
1168       return 0;
1169     }
1170   }
1171 
1172   if (argc < 2)
1173     errs() << ProgName << ": No command specified!\n";
1174   else
1175     errs() << ProgName << ": Unknown command!\n";
1176 
1177   errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
1178   return 1;
1179 }
1180