blob: 1470442c38b6181a952f832f5b9f5b174e1dcdbc [file] [log] [blame]
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +00001//===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +00006//
7//===----------------------------------------------------------------------===//
8//
9// llvm-profdata merges .profdata files.
10//
11//===----------------------------------------------------------------------===//
12
Nathan Slingerlandc21a44d2015-11-18 17:10:24 +000013#include "llvm/ADT/SmallSet.h"
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +000014#include "llvm/ADT/SmallVector.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000015#include "llvm/ADT/StringRef.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000016#include "llvm/IR/LLVMContext.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000017#include "llvm/ProfileData/InstrProfReader.h"
Justin Bognerb9bd7f82014-03-21 17:46:22 +000018#include "llvm/ProfileData/InstrProfWriter.h"
Easwaran Ramand68aae22016-02-04 23:34:31 +000019#include "llvm/ProfileData/ProfileCommon.h"
Diego Novillod5336ae2014-11-01 00:56:55 +000020#include "llvm/ProfileData/SampleProfReader.h"
21#include "llvm/ProfileData/SampleProfWriter.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000022#include "llvm/Support/CommandLine.h"
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +000023#include "llvm/Support/Errc.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000024#include "llvm/Support/FileSystem.h"
Justin Bogner423380f2014-03-23 20:43:50 +000025#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000026#include "llvm/Support/InitLLVM.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000027#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000028#include "llvm/Support/Path.h"
Vedant Kumare3a0bf52016-07-19 01:17:20 +000029#include "llvm/Support/ThreadPool.h"
Fangrui Songef598752019-02-21 07:42:31 +000030#include "llvm/Support/WithColor.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000031#include "llvm/Support/raw_ostream.h"
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +000032#include <algorithm>
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000033
34using namespace llvm;
35
Wei Mia0c08572018-06-11 22:40:43 +000036enum ProfileFormat {
37 PF_None = 0,
38 PF_Text,
39 PF_Compact_Binary,
Wei Mibe907322019-08-23 19:05:30 +000040 PF_Ext_Binary,
Wei Mia0c08572018-06-11 22:40:43 +000041 PF_GCC,
Wei Mid9be2c72018-06-12 05:53:49 +000042 PF_Binary
Wei Mia0c08572018-06-11 22:40:43 +000043};
Xinliang David Li6f7c19a2015-11-23 20:47:38 +000044
Jonas Devliegheree46b7562018-04-18 14:42:33 +000045static void warn(Twine Message, std::string Whence = "",
Vedant Kumar188efda2017-11-17 21:18:32 +000046 std::string Hint = "") {
Jonas Devliegheree46b7562018-04-18 14:42:33 +000047 WithColor::warning();
Justin Bognerf8d79192014-03-21 17:24:48 +000048 if (!Whence.empty())
49 errs() << Whence << ": ";
50 errs() << Message << "\n";
Nathan Slingerland4f823662015-11-13 03:47:58 +000051 if (!Hint.empty())
Jonas Devliegheree46b7562018-04-18 14:42:33 +000052 WithColor::note() << Hint << "\n";
Vedant Kumar188efda2017-11-17 21:18:32 +000053}
54
55static void exitWithError(Twine Message, std::string Whence = "",
56 std::string Hint = "") {
Jonas Devliegheree46b7562018-04-18 14:42:33 +000057 WithColor::error();
58 if (!Whence.empty())
59 errs() << Whence << ": ";
60 errs() << Message << "\n";
61 if (!Hint.empty())
62 WithColor::note() << Hint << "\n";
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000063 ::exit(1);
64}
65
Vedant Kumar9152fd12016-05-19 03:54:45 +000066static void exitWithError(Error E, StringRef Whence = "") {
67 if (E.isA<InstrProfError>()) {
68 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
69 instrprof_error instrError = IPE.get();
70 StringRef Hint = "";
71 if (instrError == instrprof_error::unrecognized_format) {
72 // Hint for common error of forgetting -sample for sample profiles.
73 Hint = "Perhaps you forgot to use the -sample option?";
74 }
75 exitWithError(IPE.message(), Whence, Hint);
76 });
Nathan Slingerland4f823662015-11-13 03:47:58 +000077 }
Vedant Kumar9152fd12016-05-19 03:54:45 +000078
79 exitWithError(toString(std::move(E)), Whence);
80}
81
82static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
83 exitWithError(EC.message(), Whence);
Nathan Slingerland4f823662015-11-13 03:47:58 +000084}
85
Duncan P. N. Exon Smith02b6fa92015-06-16 00:43:04 +000086namespace {
Diego Novillod3babdb2015-12-14 20:37:15 +000087enum ProfileKinds { instr, sample };
Vedant Kumar0fcfe892019-09-03 22:23:16 +000088enum FailureMode { failIfAnyAreInvalid, failIfAllAreInvalid };
89}
90
91static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
92 StringRef Whence = "") {
93 if (FailMode == failIfAnyAreInvalid)
94 exitWithErrorCode(EC, Whence);
95 else
96 warn(EC.message(), Whence);
Duncan P. N. Exon Smith02b6fa92015-06-16 00:43:04 +000097}
Justin Bogner618bcea2014-03-19 02:20:46 +000098
Vedant Kumar9152fd12016-05-19 03:54:45 +000099static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000100 StringRef WhenceFunction = "",
Diego Novillod3babdb2015-12-14 20:37:15 +0000101 bool ShowHint = true) {
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000102 if (!WhenceFile.empty())
103 errs() << WhenceFile << ": ";
104 if (!WhenceFunction.empty())
105 errs() << WhenceFunction << ": ";
Vedant Kumar9152fd12016-05-19 03:54:45 +0000106
107 auto IPE = instrprof_error::success;
108 E = handleErrors(std::move(E),
109 [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
110 IPE = E->get();
111 return Error(std::move(E));
112 });
113 errs() << toString(std::move(E)) << "\n";
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000114
115 if (ShowHint) {
116 StringRef Hint = "";
Vedant Kumar9152fd12016-05-19 03:54:45 +0000117 if (IPE != instrprof_error::success) {
118 switch (IPE) {
Nathan Slingerland11c938d12015-11-17 23:37:09 +0000119 case instrprof_error::hash_mismatch:
120 case instrprof_error::count_mismatch:
121 case instrprof_error::value_site_count_mismatch:
Diego Novillod3babdb2015-12-14 20:37:15 +0000122 Hint = "Make sure that all profile data to be merged is generated "
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000123 "from the same binary.";
Nathan Slingerland11c938d12015-11-17 23:37:09 +0000124 break;
Nathan Slingerlandb2d95f02015-11-18 00:52:45 +0000125 default:
126 break;
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000127 }
128 }
129
130 if (!Hint.empty())
131 errs() << Hint << "\n";
132 }
133}
134
Richard Smith3164fcf2018-09-13 20:22:02 +0000135namespace {
136/// A remapper from original symbol names to new symbol names based on a file
137/// containing a list of mappings from old name to new name.
138class SymbolRemapper {
139 std::unique_ptr<MemoryBuffer> File;
140 DenseMap<StringRef, StringRef> RemappingTable;
141
142public:
143 /// Build a SymbolRemapper from a file containing a list of old/new symbols.
144 static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
145 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
146 if (!BufOrError)
147 exitWithErrorCode(BufOrError.getError(), InputFile);
148
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000149 auto Remapper = std::make_unique<SymbolRemapper>();
Richard Smith3164fcf2018-09-13 20:22:02 +0000150 Remapper->File = std::move(BufOrError.get());
151
152 for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
153 !LineIt.is_at_eof(); ++LineIt) {
154 std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
155 if (Parts.first.empty() || Parts.second.empty() ||
156 Parts.second.count(' ')) {
157 exitWithError("unexpected line in remapping file",
158 (InputFile + ":" + Twine(LineIt.line_number())).str(),
159 "expected 'old_symbol new_symbol'");
160 }
161 Remapper->RemappingTable.insert(Parts);
162 }
163 return Remapper;
164 }
165
166 /// Attempt to map the given old symbol into a new symbol.
167 ///
168 /// \return The new symbol, or \p Name if no such symbol was found.
169 StringRef operator()(StringRef Name) {
170 StringRef New = RemappingTable.lookup(Name);
171 return New.empty() ? Name : New;
172 }
173};
174}
175
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000176struct WeightedFile {
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000177 std::string Filename;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000178 uint64_t Weight;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000179};
180typedef SmallVector<WeightedFile, 5> WeightedFileVector;
181
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000182/// Keep track of merged data and reported errors.
183struct WriterContext {
184 std::mutex Lock;
185 InstrProfWriter Writer;
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000186 std::vector<std::pair<Error, std::string>> Errors;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000187 std::mutex &ErrLock;
188 SmallSet<instrprof_error, 4> &WriterErrorCodes;
189
190 WriterContext(bool IsSparse, std::mutex &ErrLock,
191 SmallSet<instrprof_error, 4> &WriterErrorCodes)
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000192 : Lock(), Writer(IsSparse), Errors(), ErrLock(ErrLock),
193 WriterErrorCodes(WriterErrorCodes) {}
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000194};
195
Rong Xu998b97f2019-04-30 21:19:12 +0000196/// Computer the overlap b/w profile BaseFilename and TestFileName,
197/// and store the program level result to Overlap.
198static void overlapInput(const std::string &BaseFilename,
199 const std::string &TestFilename, WriterContext *WC,
200 OverlapStats &Overlap,
201 const OverlapFuncFilters &FuncFilter,
202 raw_fd_ostream &OS, bool IsCS) {
203 auto ReaderOrErr = InstrProfReader::create(TestFilename);
204 if (Error E = ReaderOrErr.takeError()) {
205 // Skip the empty profiles by returning sliently.
206 instrprof_error IPE = InstrProfError::take(std::move(E));
207 if (IPE != instrprof_error::empty_raw_profile)
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000208 WC->Errors.emplace_back(make_error<InstrProfError>(IPE), TestFilename);
Rong Xu998b97f2019-04-30 21:19:12 +0000209 return;
210 }
211
212 auto Reader = std::move(ReaderOrErr.get());
213 for (auto &I : *Reader) {
214 OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
215 FuncOverlap.setFuncInfo(I.Name, I.Hash);
216
217 WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
218 FuncOverlap.dump(OS);
219 }
220}
221
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000222/// Load an input into a writer context.
Richard Smith3164fcf2018-09-13 20:22:02 +0000223static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
224 WriterContext *WC) {
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000225 std::unique_lock<std::mutex> CtxGuard{WC->Lock};
226
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000227 // Copy the filename, because llvm::ThreadPool copied the input "const
228 // WeightedFile &" by value, making a reference to the filename within it
229 // invalid outside of this packaged task.
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000230 std::string Filename = Input.Filename;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000231
232 auto ReaderOrErr = InstrProfReader::create(Input.Filename);
Rong Xu2c684cf2016-10-19 22:51:17 +0000233 if (Error E = ReaderOrErr.takeError()) {
234 // Skip the empty profiles by returning sliently.
235 instrprof_error IPE = InstrProfError::take(std::move(E));
236 if (IPE != instrprof_error::empty_raw_profile)
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000237 WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename);
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000238 return;
Rong Xu2c684cf2016-10-19 22:51:17 +0000239 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000240
241 auto Reader = std::move(ReaderOrErr.get());
242 bool IsIRProfile = Reader->isIRLevelProfile();
Rong Xua6ff69f2019-02-28 19:55:07 +0000243 bool HasCSIRProfile = Reader->hasCSIRLevelProfile();
244 if (WC->Writer.setIsIRLevelProfile(IsIRProfile, HasCSIRProfile)) {
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000245 WC->Errors.emplace_back(
246 make_error<StringError>(
247 "Merge IR generated profile with Clang generated profile.",
248 std::error_code()),
249 Filename);
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000250 return;
251 }
252
253 for (auto &I : *Reader) {
Richard Smith3164fcf2018-09-13 20:22:02 +0000254 if (Remapper)
255 I.Name = (*Remapper)(I.Name);
Rong Xufe90d862016-10-19 23:31:59 +0000256 const StringRef FuncName = I.Name;
David Blaikie98cce002017-07-10 03:04:59 +0000257 bool Reported = false;
258 WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
259 if (Reported) {
260 consumeError(std::move(E));
261 return;
262 }
263 Reported = true;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000264 // Only show hint the first time an error occurs.
265 instrprof_error IPE = InstrProfError::take(std::move(E));
266 std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
267 bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
268 handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
Rong Xufe90d862016-10-19 23:31:59 +0000269 FuncName, firstTime);
David Blaikie98cce002017-07-10 03:04:59 +0000270 });
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000271 }
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000272 if (Reader->hasError())
273 if (Error E = Reader->getError())
274 WC->Errors.emplace_back(std::move(E), Filename);
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000275}
276
277/// Merge the \p Src writer context into \p Dst.
278static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000279 for (auto &ErrorPair : Src->Errors)
280 Dst->Errors.push_back(std::move(ErrorPair));
281 Src->Errors.clear();
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000282
David Blaikie98cce002017-07-10 03:04:59 +0000283 Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000284 instrprof_error IPE = InstrProfError::take(std::move(E));
285 std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
286 bool firstTime = Dst->WriterErrorCodes.insert(IPE).second;
287 if (firstTime)
288 warn(toString(make_error<InstrProfError>(IPE)));
David Blaikie98cce002017-07-10 03:04:59 +0000289 });
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000290}
291
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000292static void mergeInstrProfile(const WeightedFileVector &Inputs,
Richard Smith3164fcf2018-09-13 20:22:02 +0000293 SymbolRemapper *Remapper,
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000294 StringRef OutputFilename,
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000295 ProfileFormat OutputFormat, bool OutputSparse,
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000296 unsigned NumThreads, FailureMode FailMode) {
Justin Bognerb7aa2632014-04-18 21:48:40 +0000297 if (OutputFilename.compare("-") == 0)
298 exitWithError("Cannot write indexed profdata format to stdout.");
Justin Bognerec49f982014-03-12 22:00:57 +0000299
Wei Mid9be2c72018-06-12 05:53:49 +0000300 if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
Wei Mibe907322019-08-23 19:05:30 +0000301 OutputFormat != PF_Ext_Binary && OutputFormat != PF_Text)
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000302 exitWithError("Unknown format is specified.");
303
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000304 std::mutex ErrorLock;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000305 SmallSet<instrprof_error, 4> WriterErrorCodes;
Justin Bognerf8d79192014-03-21 17:24:48 +0000306
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000307 // If NumThreads is not specified, auto-detect a good default.
308 if (NumThreads == 0)
Rafael Espindola8c0ff952017-10-04 20:27:01 +0000309 NumThreads =
310 std::min(hardware_concurrency(), unsigned((Inputs.size() + 1) / 2));
Rong Xu33c76c02016-02-10 17:18:30 +0000311
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000312 // Initialize the writer contexts.
313 SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
314 for (unsigned I = 0; I < NumThreads; ++I)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000315 Contexts.emplace_back(std::make_unique<WriterContext>(
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000316 OutputSparse, ErrorLock, WriterErrorCodes));
317
318 if (NumThreads == 1) {
319 for (const auto &Input : Inputs)
Richard Smith3164fcf2018-09-13 20:22:02 +0000320 loadInput(Input, Remapper, Contexts[0].get());
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000321 } else {
322 ThreadPool Pool(NumThreads);
323
324 // Load the inputs in parallel (N/NumThreads serial steps).
325 unsigned Ctx = 0;
326 for (const auto &Input : Inputs) {
Richard Smith3164fcf2018-09-13 20:22:02 +0000327 Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get());
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000328 Ctx = (Ctx + 1) % NumThreads;
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000329 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000330 Pool.wait();
331
332 // Merge the writer contexts together (~ lg(NumThreads) serial steps).
333 unsigned Mid = Contexts.size() / 2;
334 unsigned End = Contexts.size();
335 assert(Mid > 0 && "Expected more than one context");
336 do {
337 for (unsigned I = 0; I < Mid; ++I)
338 Pool.async(mergeWriterContexts, Contexts[I].get(),
339 Contexts[I + Mid].get());
340 Pool.wait();
341 if (End & 1) {
342 Pool.async(mergeWriterContexts, Contexts[0].get(),
343 Contexts[End - 1].get());
344 Pool.wait();
345 }
346 End = Mid;
347 Mid /= 2;
348 } while (Mid > 0);
Justin Bognerbfee8d42014-03-12 20:14:17 +0000349 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000350
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000351 // Handle deferred errors encountered during merging. If the number of errors
352 // is equal to the number of inputs the merge failed.
353 unsigned NumErrors = 0;
Vedant Kumar188efda2017-11-17 21:18:32 +0000354 for (std::unique_ptr<WriterContext> &WC : Contexts) {
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000355 for (auto &ErrorPair : WC->Errors) {
356 ++NumErrors;
357 warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
358 }
Vedant Kumar188efda2017-11-17 21:18:32 +0000359 }
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000360 if (NumErrors == Inputs.size() ||
361 (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
362 exitWithError("No profiles could be merged.");
Vedant Kumar188efda2017-11-17 21:18:32 +0000363
Rong Xuf0d3dce2019-07-08 21:03:12 +0000364 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000365 raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::OF_None);
Rong Xuf0d3dce2019-07-08 21:03:12 +0000366 if (EC)
367 exitWithErrorCode(EC, OutputFilename);
368
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000369 InstrProfWriter &Writer = Contexts[0]->Writer;
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000370 if (OutputFormat == PF_Text) {
371 if (Error E = Writer.writeText(Output))
372 exitWithError(std::move(E));
373 } else {
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000374 Writer.write(Output);
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000375 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000376}
377
Richard Smith3164fcf2018-09-13 20:22:02 +0000378/// Make a copy of the given function samples with all symbol names remapped
379/// by the provided symbol remapper.
380static sampleprof::FunctionSamples
381remapSamples(const sampleprof::FunctionSamples &Samples,
382 SymbolRemapper &Remapper, sampleprof_error &Error) {
383 sampleprof::FunctionSamples Result;
384 Result.setName(Remapper(Samples.getName()));
385 Result.addTotalSamples(Samples.getTotalSamples());
386 Result.addHeadSamples(Samples.getHeadSamples());
387 for (const auto &BodySample : Samples.getBodySamples()) {
388 Result.addBodySamples(BodySample.first.LineOffset,
389 BodySample.first.Discriminator,
390 BodySample.second.getSamples());
391 for (const auto &Target : BodySample.second.getCallTargets()) {
392 Result.addCalledTargetSamples(BodySample.first.LineOffset,
393 BodySample.first.Discriminator,
394 Remapper(Target.first()), Target.second);
395 }
396 }
397 for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
398 sampleprof::FunctionSamplesMap &Target =
399 Result.functionSamplesAt(CallsiteSamples.first);
400 for (const auto &Callsite : CallsiteSamples.second) {
401 sampleprof::FunctionSamples Remapped =
402 remapSamples(Callsite.second, Remapper, Error);
403 MergeResult(Error, Target[Remapped.getName()].merge(Remapped));
404 }
405 }
406 return Result;
407}
408
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000409static sampleprof::SampleProfileFormat FormatMap[] = {
Wei Mibe907322019-08-23 19:05:30 +0000410 sampleprof::SPF_None,
411 sampleprof::SPF_Text,
412 sampleprof::SPF_Compact_Binary,
413 sampleprof::SPF_Ext_Binary,
414 sampleprof::SPF_GCC,
415 sampleprof::SPF_Binary};
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000416
Wei Mi798e59b2019-08-31 02:27:26 +0000417static std::unique_ptr<MemoryBuffer>
418getInputFileBuf(const StringRef &InputFile) {
419 if (InputFile == "")
420 return {};
421
422 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
423 if (!BufOrError)
424 exitWithErrorCode(BufOrError.getError(), InputFile);
425
426 return std::move(*BufOrError);
427}
428
429static void populateProfileSymbolList(MemoryBuffer *Buffer,
430 sampleprof::ProfileSymbolList &PSL) {
431 if (!Buffer)
432 return;
433
434 SmallVector<StringRef, 32> SymbolVec;
435 StringRef Data = Buffer->getBuffer();
436 Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
437
438 for (StringRef symbol : SymbolVec)
439 PSL.add(symbol);
440}
441
Wei Mib5237902019-10-07 16:12:37 +0000442static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer,
443 ProfileFormat OutputFormat,
444 MemoryBuffer *Buffer,
445 sampleprof::ProfileSymbolList &WriterList,
446 bool CompressAllSections) {
447 populateProfileSymbolList(Buffer, WriterList);
448 if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
449 warn("Profile Symbol list is not empty but the output format is not "
450 "ExtBinary format. The list will be lost in the output. ");
451
452 Writer.setProfileSymbolList(&WriterList);
453
454 if (CompressAllSections) {
455 if (OutputFormat != PF_Ext_Binary) {
456 warn("-compress-all-section is ignored. Specify -extbinary to enable it");
457 } else {
458 auto ExtBinaryWriter =
459 static_cast<sampleprof::SampleProfileWriterExtBinary *>(&Writer);
460 ExtBinaryWriter->setToCompressAllSections();
461 }
462 }
463}
464
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000465static void mergeSampleProfile(const WeightedFileVector &Inputs,
466 SymbolRemapper *Remapper,
467 StringRef OutputFilename,
468 ProfileFormat OutputFormat,
469 StringRef ProfileSymbolListFile,
Wei Mib5237902019-10-07 16:12:37 +0000470 bool CompressAllSections, FailureMode FailMode) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000471 using namespace sampleprof;
Diego Novillod5336ae2014-11-01 00:56:55 +0000472 StringMap<FunctionSamples> ProfileMap;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000473 SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
Mehdi Amini03b42e42016-04-14 21:59:01 +0000474 LLVMContext Context;
Wei Mi798e59b2019-08-31 02:27:26 +0000475 sampleprof::ProfileSymbolList WriterList;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000476 for (const auto &Input : Inputs) {
Mehdi Amini03b42e42016-04-14 21:59:01 +0000477 auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000478 if (std::error_code EC = ReaderOrErr.getError()) {
479 warnOrExitGivenError(FailMode, EC, Input.Filename);
480 continue;
481 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000482
Diego Novilloaae1ed82015-10-08 19:40:37 +0000483 // We need to keep the readers around until after all the files are
484 // read so that we do not lose the function names stored in each
485 // reader's memory. The function names are needed to write out the
486 // merged profile map.
487 Readers.push_back(std::move(ReaderOrErr.get()));
488 const auto Reader = Readers.back().get();
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000489 if (std::error_code EC = Reader->read()) {
490 warnOrExitGivenError(FailMode, EC, Input.Filename);
491 Readers.pop_back();
492 continue;
493 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000494
495 StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
496 for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
497 E = Profiles.end();
498 I != E; ++I) {
Richard Smith3164fcf2018-09-13 20:22:02 +0000499 sampleprof_error Result = sampleprof_error::success;
500 FunctionSamples Remapped =
501 Remapper ? remapSamples(I->second, *Remapper, Result)
502 : FunctionSamples();
503 FunctionSamples &Samples = Remapper ? Remapped : I->second;
504 StringRef FName = Samples.getName();
505 MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight));
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000506 if (Result != sampleprof_error::success) {
507 std::error_code EC = make_error_code(Result);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000508 handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000509 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000510 }
Wei Mi798e59b2019-08-31 02:27:26 +0000511
512 std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
513 Reader->getProfileSymbolList();
514 if (ReaderList)
515 WriterList.merge(*ReaderList);
Diego Novillod5336ae2014-11-01 00:56:55 +0000516 }
Rong Xuf0d3dce2019-07-08 21:03:12 +0000517 auto WriterOrErr =
518 SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
519 if (std::error_code EC = WriterOrErr.getError())
520 exitWithErrorCode(EC, OutputFilename);
521
Wei Mib5237902019-10-07 16:12:37 +0000522 auto Writer = std::move(WriterOrErr.get());
Wei Mi798e59b2019-08-31 02:27:26 +0000523 // WriterList will have StringRef refering to string in Buffer.
524 // Make sure Buffer lives as long as WriterList.
525 auto Buffer = getInputFileBuf(ProfileSymbolListFile);
Wei Mib5237902019-10-07 16:12:37 +0000526 handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList,
527 CompressAllSections);
Diego Novillod5336ae2014-11-01 00:56:55 +0000528 Writer->write(ProfileMap);
529}
530
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000531static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
Vedant Kumar8d0e8612016-06-06 23:43:56 +0000532 StringRef WeightStr, FileName;
533 std::tie(WeightStr, FileName) = WeightedFilename.split(',');
Diego Novillod5336ae2014-11-01 00:56:55 +0000534
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000535 uint64_t Weight;
536 if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
537 exitWithError("Input weight must be a positive integer.");
538
Benjamin Kramer929e7db2016-07-21 14:29:11 +0000539 return {FileName, Weight};
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000540}
541
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000542static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
543 StringRef Filename = WF.Filename;
544 uint64_t Weight = WF.Weight;
Benjamin Kramera81f4722016-07-22 12:39:55 +0000545
546 // If it's STDIN just pass it on.
547 if (Filename == "-") {
548 WNI.push_back({Filename, Weight});
549 return;
550 }
551
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000552 llvm::sys::fs::file_status Status;
553 llvm::sys::fs::status(Filename, Status);
554 if (!llvm::sys::fs::exists(Status))
555 exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
556 Filename);
557 // If it's a source file, collect it.
558 if (llvm::sys::fs::is_regular_file(Status)) {
Benjamin Kramer929e7db2016-07-21 14:29:11 +0000559 WNI.push_back({Filename, Weight});
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000560 return;
561 }
562
563 if (llvm::sys::fs::is_directory(Status)) {
564 std::error_code EC;
565 for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
566 F != E && !EC; F.increment(EC)) {
567 if (llvm::sys::fs::is_regular_file(F->path())) {
568 addWeightedInput(WNI, {F->path(), Weight});
569 }
570 }
571 if (EC)
572 exitWithErrorCode(EC, Filename);
573 }
574}
575
Vedant Kumarcef43602016-06-07 22:47:31 +0000576static void parseInputFilenamesFile(MemoryBuffer *Buffer,
577 WeightedFileVector &WFV) {
578 if (!Buffer)
579 return;
580
581 SmallVector<StringRef, 8> Entries;
582 StringRef Data = Buffer->getBuffer();
583 Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
584 for (const StringRef &FileWeightEntry : Entries) {
585 StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
586 // Skip comments.
587 if (SanitizedEntry.startswith("#"))
588 continue;
589 // If there's no comma, it's an unweighted profile.
590 else if (SanitizedEntry.find(',') == StringRef::npos)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000591 addWeightedInput(WFV, {SanitizedEntry, 1});
Vedant Kumarcef43602016-06-07 22:47:31 +0000592 else
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000593 addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
Vedant Kumarcef43602016-06-07 22:47:31 +0000594 }
595}
596
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000597static int merge_main(int argc, const char *argv[]) {
598 cl::list<std::string> InputFilenames(cl::Positional,
599 cl::desc("<filename...>"));
600 cl::list<std::string> WeightedInputFilenames("weighted-input",
601 cl::desc("<weight>,<filename>"));
Vedant Kumarcef43602016-06-07 22:47:31 +0000602 cl::opt<std::string> InputFilenamesFile(
603 "input-files", cl::init(""),
604 cl::desc("Path to file containing newline-separated "
605 "[<weight>,]<filename> entries"));
606 cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
607 cl::aliasopt(InputFilenamesFile));
608 cl::opt<bool> DumpInputFileList(
609 "dump-input-file-list", cl::init(false), cl::Hidden,
610 cl::desc("Dump the list of input files and their weights, then exit"));
Richard Smith3164fcf2018-09-13 20:22:02 +0000611 cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
612 cl::desc("Symbol remapping file"));
613 cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
614 cl::aliasopt(RemappingFile));
Diego Novillod5336ae2014-11-01 00:56:55 +0000615 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
616 cl::init("-"), cl::Required,
617 cl::desc("Output file"));
618 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
619 cl::aliasopt(OutputFilename));
620 cl::opt<ProfileKinds> ProfileKind(
621 cl::desc("Profile kind:"), cl::init(instr),
622 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000623 clEnumVal(sample, "Sample profile")));
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000624 cl::opt<ProfileFormat> OutputFormat(
Wei Mid9be2c72018-06-12 05:53:49 +0000625 cl::desc("Format of output profile"), cl::init(PF_Binary),
Wei Mibe907322019-08-23 19:05:30 +0000626 cl::values(
627 clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
628 clEnumValN(PF_Compact_Binary, "compbinary",
629 "Compact binary encoding"),
630 clEnumValN(PF_Ext_Binary, "extbinary", "Extensible binary encoding"),
631 clEnumValN(PF_Text, "text", "Text encoding"),
632 clEnumValN(PF_GCC, "gcc",
633 "GCC encoding (only meaningful for -sample)")));
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000634 cl::opt<FailureMode> FailureMode(
635 "failure-mode", cl::init(failIfAnyAreInvalid), cl::desc("Failure mode:"),
636 cl::values(clEnumValN(failIfAnyAreInvalid, "any",
637 "Fail if any profile is invalid."),
638 clEnumValN(failIfAllAreInvalid, "all",
639 "Fail only if all profiles are invalid.")));
Vedant Kumar00dab222016-01-29 22:54:45 +0000640 cl::opt<bool> OutputSparse("sparse", cl::init(false),
641 cl::desc("Generate a sparse profile (only meaningful for -instr)"));
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000642 cl::opt<unsigned> NumThreads(
643 "num-threads", cl::init(0),
644 cl::desc("Number of merge threads to use (default: autodetect)"));
645 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
646 cl::aliasopt(NumThreads));
Wei Mi798e59b2019-08-31 02:27:26 +0000647 cl::opt<std::string> ProfileSymbolListFile(
648 "prof-sym-list", cl::init(""),
649 cl::desc("Path to file containing the list of function symbols "
650 "used to populate profile symbol list"));
Wei Mib5237902019-10-07 16:12:37 +0000651 cl::opt<bool> CompressAllSections(
652 "compress-all-sections", cl::init(false), cl::Hidden,
653 cl::desc("Compress all sections when writing the profile (only "
654 "meaningful for -extbinary)"));
Vedant Kumar00dab222016-01-29 22:54:45 +0000655
Diego Novillod5336ae2014-11-01 00:56:55 +0000656 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
657
Vedant Kumarcef43602016-06-07 22:47:31 +0000658 WeightedFileVector WeightedInputs;
659 for (StringRef Filename : InputFilenames)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000660 addWeightedInput(WeightedInputs, {Filename, 1});
Vedant Kumarcef43602016-06-07 22:47:31 +0000661 for (StringRef WeightedFilename : WeightedInputFilenames)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000662 addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
Vedant Kumarcef43602016-06-07 22:47:31 +0000663
664 // Make sure that the file buffer stays alive for the duration of the
665 // weighted input vector's lifetime.
Wei Mi798e59b2019-08-31 02:27:26 +0000666 auto Buffer = getInputFileBuf(InputFilenamesFile);
Vedant Kumarcef43602016-06-07 22:47:31 +0000667 parseInputFilenamesFile(Buffer.get(), WeightedInputs);
668
669 if (WeightedInputs.empty())
Chandler Carruth0c30f892016-06-04 03:08:01 +0000670 exitWithError("No input files specified. See " +
671 sys::path::filename(argv[0]) + " -help");
672
Vedant Kumarcef43602016-06-07 22:47:31 +0000673 if (DumpInputFileList) {
674 for (auto &WF : WeightedInputs)
675 outs() << WF.Weight << "," << WF.Filename << "\n";
676 return 0;
677 }
Vedant Kumarf771a052016-06-04 00:36:28 +0000678
Richard Smith3164fcf2018-09-13 20:22:02 +0000679 std::unique_ptr<SymbolRemapper> Remapper;
680 if (!RemappingFile.empty())
681 Remapper = SymbolRemapper::create(RemappingFile);
682
Diego Novillod5336ae2014-11-01 00:56:55 +0000683 if (ProfileKind == instr)
Richard Smith3164fcf2018-09-13 20:22:02 +0000684 mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
Vedant Kumar0fcfe892019-09-03 22:23:16 +0000685 OutputFormat, OutputSparse, NumThreads, FailureMode);
Diego Novillod5336ae2014-11-01 00:56:55 +0000686 else
Richard Smith3164fcf2018-09-13 20:22:02 +0000687 mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
Wei Mib5237902019-10-07 16:12:37 +0000688 OutputFormat, ProfileSymbolListFile, CompressAllSections,
689 FailureMode);
Justin Bognerbfee8d42014-03-12 20:14:17 +0000690
Justin Bognerec49f982014-03-12 22:00:57 +0000691 return 0;
Justin Bognerbfee8d42014-03-12 20:14:17 +0000692}
Justin Bogner618bcea2014-03-19 02:20:46 +0000693
Rong Xu998b97f2019-04-30 21:19:12 +0000694/// Computer the overlap b/w profile BaseFilename and profile TestFilename.
695static void overlapInstrProfile(const std::string &BaseFilename,
696 const std::string &TestFilename,
697 const OverlapFuncFilters &FuncFilter,
698 raw_fd_ostream &OS, bool IsCS) {
699 std::mutex ErrorLock;
700 SmallSet<instrprof_error, 4> WriterErrorCodes;
701 WriterContext Context(false, ErrorLock, WriterErrorCodes);
702 WeightedFile WeightedInput{BaseFilename, 1};
703 OverlapStats Overlap;
Rong Xue0fa2682019-10-01 18:06:50 +0000704 Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS);
Rong Xu998b97f2019-04-30 21:19:12 +0000705 if (E)
706 exitWithError(std::move(E), "Error in getting profile count sums");
707 if (Overlap.Base.CountSum < 1.0f) {
708 OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
709 exit(0);
710 }
711 if (Overlap.Test.CountSum < 1.0f) {
712 OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
713 exit(0);
714 }
715 loadInput(WeightedInput, nullptr, &Context);
716 overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
717 IsCS);
718 Overlap.dump(OS);
719}
720
721static int overlap_main(int argc, const char *argv[]) {
722 cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
723 cl::desc("<base profile file>"));
724 cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
725 cl::desc("<test profile file>"));
726 cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
727 cl::desc("Output file"));
728 cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
729 cl::opt<bool> IsCS("cs", cl::init(false),
730 cl::desc("For context sensitive counts"));
731 cl::opt<unsigned long long> ValueCutoff(
732 "value-cutoff", cl::init(-1),
733 cl::desc(
734 "Function level overlap information for every function in test "
735 "profile with max count value greater then the parameter value"));
736 cl::opt<std::string> FuncNameFilter(
737 "function",
738 cl::desc("Function level overlap information for matching functions"));
739 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
740
741 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000742 raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_Text);
Rong Xu998b97f2019-04-30 21:19:12 +0000743 if (EC)
744 exitWithErrorCode(EC, Output);
745
746 overlapInstrProfile(BaseFilename, TestFilename,
747 OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
748 IsCS);
749
750 return 0;
751}
752
Rong Xu0cf1f562017-03-09 19:03:57 +0000753typedef struct ValueSitesStats {
754 ValueSitesStats()
755 : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
756 TotalNumValues(0) {}
757 uint64_t TotalNumValueSites;
758 uint64_t TotalNumValueSitesWithValueProfile;
759 uint64_t TotalNumValues;
760 std::vector<unsigned> ValueSitesHistogram;
761} ValueSitesStats;
762
763static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
764 ValueSitesStats &Stats, raw_fd_ostream &OS,
Rong Xu60faea12017-03-16 21:15:48 +0000765 InstrProfSymtab *Symtab) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000766 uint32_t NS = Func.getNumValueSites(VK);
767 Stats.TotalNumValueSites += NS;
768 for (size_t I = 0; I < NS; ++I) {
769 uint32_t NV = Func.getNumValueDataForSite(VK, I);
770 std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
771 Stats.TotalNumValues += NV;
772 if (NV) {
773 Stats.TotalNumValueSitesWithValueProfile++;
774 if (NV > Stats.ValueSitesHistogram.size())
775 Stats.ValueSitesHistogram.resize(NV, 0);
776 Stats.ValueSitesHistogram[NV - 1]++;
777 }
Rong Xu52aa2242019-01-08 22:41:48 +0000778
779 uint64_t SiteSum = 0;
780 for (uint32_t V = 0; V < NV; V++)
781 SiteSum += VD[V].Count;
782 if (SiteSum == 0)
783 SiteSum = 1;
784
Rong Xu0cf1f562017-03-09 19:03:57 +0000785 for (uint32_t V = 0; V < NV; V++) {
Rong Xu52aa2242019-01-08 22:41:48 +0000786 OS << "\t[ " << format("%2u", I) << ", ";
Rong Xu60faea12017-03-16 21:15:48 +0000787 if (Symtab == nullptr)
Petar Jovanovic40a7f632019-02-05 18:09:28 +0000788 OS << format("%4" PRIu64, VD[V].Value);
Rong Xu60faea12017-03-16 21:15:48 +0000789 else
790 OS << Symtab->getFuncName(VD[V].Value);
Rong Xu52aa2242019-01-08 22:41:48 +0000791 OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
792 << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
Rong Xu0cf1f562017-03-09 19:03:57 +0000793 }
794 }
795}
796
797static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
798 ValueSitesStats &Stats) {
799 OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n";
800 OS << " Total number of sites with values: "
801 << Stats.TotalNumValueSitesWithValueProfile << "\n";
802 OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n";
803
804 OS << " Value sites histogram:\n\tNumTargets, SiteCount\n";
805 for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
806 if (Stats.ValueSitesHistogram[I] > 0)
807 OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
808 }
809}
810
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000811static int showInstrProfile(const std::string &Filename, bool ShowCounts,
Xinliang David Li801b5312017-07-11 20:30:43 +0000812 uint32_t TopN, bool ShowIndirectCallTargets,
813 bool ShowMemOPSizes, bool ShowDetailedSummary,
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000814 std::vector<uint32_t> DetailedSummaryCutoffs,
Rong Xua6ff69f2019-02-28 19:55:07 +0000815 bool ShowAllFunctions, bool ShowCS,
816 uint64_t ValueCutoff, bool OnlyListBelow,
817 const std::string &ShowFunction, bool TextFormat,
818 raw_fd_ostream &OS) {
Diego Novillofcd55602014-11-03 00:51:45 +0000819 auto ReaderOrErr = InstrProfReader::create(Filename);
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000820 std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
821 if (ShowDetailedSummary && Cutoffs.empty()) {
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000822 Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
823 }
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000824 InstrProfSummaryBuilder Builder(std::move(Cutoffs));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000825 if (Error E = ReaderOrErr.takeError())
826 exitWithError(std::move(E), Filename);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000827
Diego Novillofcd55602014-11-03 00:51:45 +0000828 auto Reader = std::move(ReaderOrErr.get());
Rong Xu33c76c02016-02-10 17:18:30 +0000829 bool IsIRInstr = Reader->isIRLevelProfile();
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000830 size_t ShownFunctions = 0;
Rong Xu52aa2242019-01-08 22:41:48 +0000831 size_t BelowCutoffFunctions = 0;
Rong Xu0cf1f562017-03-09 19:03:57 +0000832 int NumVPKind = IPVK_Last - IPVK_First + 1;
833 std::vector<ValueSitesStats> VPStats(NumVPKind);
Xinliang David Li801b5312017-07-11 20:30:43 +0000834
835 auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
836 const std::pair<std::string, uint64_t> &v2) {
837 return v1.second > v2.second;
838 };
839
840 std::priority_queue<std::pair<std::string, uint64_t>,
841 std::vector<std::pair<std::string, uint64_t>>,
842 decltype(MinCmp)>
843 HottestFuncs(MinCmp);
844
Rong Xu52aa2242019-01-08 22:41:48 +0000845 if (!TextFormat && OnlyListBelow) {
846 OS << "The list of functions with the maximum counter less than "
847 << ValueCutoff << ":\n";
848 }
849
Richard Smithc6ba9ca2018-08-24 01:34:45 +0000850 // Add marker so that IR-level instrumentation round-trips properly.
851 if (TextFormat && IsIRInstr)
852 OS << ":ir\n";
853
Justin Bogner9af28ef2014-03-21 17:29:44 +0000854 for (const auto &Func : *Reader) {
Rong Xua6ff69f2019-02-28 19:55:07 +0000855 if (Reader->isIRLevelProfile()) {
856 bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
857 if (FuncIsCS != ShowCS)
858 continue;
859 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000860 bool Show =
861 ShowAllFunctions || (!ShowFunction.empty() &&
862 Func.Name.find(ShowFunction) != Func.Name.npos);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000863
Richard Smithc6ba9ca2018-08-24 01:34:45 +0000864 bool doTextFormatDump = (Show && TextFormat);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000865
866 if (doTextFormatDump) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000867 InstrProfSymtab &Symtab = Reader->getSymtab();
David Blaikiecf9d52c2017-07-06 19:00:12 +0000868 InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
869 OS);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000870 continue;
871 }
872
Justin Bognerb59d7c72014-04-25 02:45:33 +0000873 assert(Func.Counts.size() > 0 && "function missing entry counter");
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000874 Builder.addRecord(Func);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000875
Rong Xu52aa2242019-01-08 22:41:48 +0000876 uint64_t FuncMax = 0;
877 uint64_t FuncSum = 0;
878 for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
879 FuncMax = std::max(FuncMax, Func.Counts[I]);
880 FuncSum += Func.Counts[I];
881 }
Rong Xu7162e162019-01-08 22:37:12 +0000882
Rong Xu52aa2242019-01-08 22:41:48 +0000883 if (FuncMax < ValueCutoff) {
884 ++BelowCutoffFunctions;
885 if (OnlyListBelow) {
886 OS << " " << Func.Name << ": (Max = " << FuncMax
887 << " Sum = " << FuncSum << ")\n";
888 }
889 continue;
890 } else if (OnlyListBelow)
891 continue;
892
893 if (TopN) {
Xinliang David Li801b5312017-07-11 20:30:43 +0000894 if (HottestFuncs.size() == TopN) {
895 if (HottestFuncs.top().second < FuncMax) {
896 HottestFuncs.pop();
897 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
898 }
899 } else
900 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
901 }
902
Justin Bogner9af28ef2014-03-21 17:29:44 +0000903 if (Show) {
904 if (!ShownFunctions)
905 OS << "Counters:\n";
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000906
Justin Bogner9af28ef2014-03-21 17:29:44 +0000907 ++ShownFunctions;
908
909 OS << " " << Func.Name << ":\n"
Justin Bogner423380f2014-03-23 20:43:50 +0000910 << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
Rong Xu33c76c02016-02-10 17:18:30 +0000911 << " Counters: " << Func.Counts.size() << "\n";
912 if (!IsIRInstr)
913 OS << " Function count: " << Func.Counts[0] << "\n";
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000914
Justin Bogner9e9a0572015-09-29 22:13:58 +0000915 if (ShowIndirectCallTargets)
Xinliang David Li2004f002015-11-02 05:08:23 +0000916 OS << " Indirect Call Site Count: "
917 << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
Justin Bogner9af28ef2014-03-21 17:29:44 +0000918
Rong Xu60faea12017-03-16 21:15:48 +0000919 uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
920 if (ShowMemOPSizes && NumMemOPCalls > 0)
921 OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls
922 << "\n";
923
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000924 if (ShowCounts) {
925 OS << " Block counts: [";
Rong Xu33c76c02016-02-10 17:18:30 +0000926 size_t Start = (IsIRInstr ? 0 : 1);
927 for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
928 OS << (I == Start ? "" : ", ") << Func.Counts[I];
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000929 }
930 OS << "]\n";
931 }
Justin Bogner9e9a0572015-09-29 22:13:58 +0000932
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000933 if (ShowIndirectCallTargets) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000934 OS << " Indirect Target Results:\n";
935 traverseAllValueSites(Func, IPVK_IndirectCallTarget,
936 VPStats[IPVK_IndirectCallTarget], OS,
Rong Xu60faea12017-03-16 21:15:48 +0000937 &(Reader->getSymtab()));
938 }
939
940 if (ShowMemOPSizes && NumMemOPCalls > 0) {
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000941 OS << " Memory Intrinsic Size Results:\n";
Rong Xu60faea12017-03-16 21:15:48 +0000942 traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
943 nullptr);
Justin Bogner9e9a0572015-09-29 22:13:58 +0000944 }
945 }
Justin Bogner9af28ef2014-03-21 17:29:44 +0000946 }
Justin Bognerdb1225d2014-03-23 20:55:53 +0000947 if (Reader->hasError())
Vedant Kumar9152fd12016-05-19 03:54:45 +0000948 exitWithError(Reader->getError(), Filename);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000949
Richard Smithc6ba9ca2018-08-24 01:34:45 +0000950 if (TextFormat)
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000951 return 0;
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000952 std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
Adam Nemet1142b2d2017-11-14 16:59:18 +0000953 OS << "Instrumentation level: "
954 << (Reader->isIRLevelProfile() ? "IR" : "Front-end") << "\n";
Justin Bogner9af28ef2014-03-21 17:29:44 +0000955 if (ShowAllFunctions || !ShowFunction.empty())
956 OS << "Functions shown: " << ShownFunctions << "\n";
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000957 OS << "Total functions: " << PS->getNumFunctions() << "\n";
Rong Xu52aa2242019-01-08 22:41:48 +0000958 if (ValueCutoff > 0) {
959 OS << "Number of functions with maximum count (< " << ValueCutoff
960 << "): " << BelowCutoffFunctions << "\n";
961 OS << "Number of functions with maximum count (>= " << ValueCutoff
962 << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
963 }
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000964 OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000965 OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
Rong Xu60faea12017-03-16 21:15:48 +0000966
Xinliang David Li801b5312017-07-11 20:30:43 +0000967 if (TopN) {
968 std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
969 while (!HottestFuncs.empty()) {
970 SortedHottestFuncs.emplace_back(HottestFuncs.top());
971 HottestFuncs.pop();
972 }
973 OS << "Top " << TopN
974 << " functions with the largest internal block counts: \n";
975 for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
976 OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
977 }
978
Xinliang David Li872362c2016-05-23 16:36:11 +0000979 if (ShownFunctions && ShowIndirectCallTargets) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000980 OS << "Statistics for indirect call sites profile:\n";
981 showValueSitesStats(OS, IPVK_IndirectCallTarget,
982 VPStats[IPVK_IndirectCallTarget]);
Xinliang David Li872362c2016-05-23 16:36:11 +0000983 }
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000984
Rong Xu60faea12017-03-16 21:15:48 +0000985 if (ShownFunctions && ShowMemOPSizes) {
986 OS << "Statistics for memory intrinsic calls sizes profile:\n";
987 showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
988 }
989
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000990 if (ShowDetailedSummary) {
991 OS << "Detailed summary:\n";
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000992 OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000993 OS << "Total count: " << PS->getTotalCount() << "\n";
994 for (auto Entry : PS->getDetailedSummary()) {
Easwaran Raman43095702016-02-17 18:18:47 +0000995 OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000996 << " account for "
997 << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
998 << " percentage of the total counts.\n";
999 }
1000 }
Justin Bogner9af28ef2014-03-21 17:29:44 +00001001 return 0;
1002}
1003
Wei Mieee532c2019-09-21 17:23:55 +00001004static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
1005 raw_fd_ostream &OS) {
1006 if (!Reader->dumpSectionInfo(OS)) {
1007 WithColor::warning() << "-show-sec-info-only is only supported for "
1008 << "sample profile in extbinary format and is "
1009 << "ignored for other formats.\n";
1010 return;
1011 }
1012}
1013
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00001014static int showSampleProfile(const std::string &Filename, bool ShowCounts,
1015 bool ShowAllFunctions,
1016 const std::string &ShowFunction,
Wei Mieee532c2019-09-21 17:23:55 +00001017 bool ShowProfileSymbolList,
1018 bool ShowSectionInfoOnly, raw_fd_ostream &OS) {
Diego Novillod5336ae2014-11-01 00:56:55 +00001019 using namespace sampleprof;
Mehdi Amini03b42e42016-04-14 21:59:01 +00001020 LLVMContext Context;
1021 auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
Diego Novillofcd55602014-11-03 00:51:45 +00001022 if (std::error_code EC = ReaderOrErr.getError())
Nathan Slingerland4f823662015-11-13 03:47:58 +00001023 exitWithErrorCode(EC, Filename);
Diego Novillod5336ae2014-11-01 00:56:55 +00001024
Diego Novillofcd55602014-11-03 00:51:45 +00001025 auto Reader = std::move(ReaderOrErr.get());
Wei Mieee532c2019-09-21 17:23:55 +00001026
1027 if (ShowSectionInfoOnly) {
1028 showSectionInfo(Reader.get(), OS);
1029 return 0;
1030 }
1031
Diego Novilloc6d032a2015-09-17 00:17:21 +00001032 if (std::error_code EC = Reader->read())
Nathan Slingerland4f823662015-11-13 03:47:58 +00001033 exitWithErrorCode(EC, Filename);
Diego Novilloc6d032a2015-09-17 00:17:21 +00001034
Diego Novillod5336ae2014-11-01 00:56:55 +00001035 if (ShowAllFunctions || ShowFunction.empty())
1036 Reader->dump(OS);
1037 else
1038 Reader->dumpFunctionProfile(ShowFunction, OS);
1039
Wei Mi798e59b2019-08-31 02:27:26 +00001040 if (ShowProfileSymbolList) {
1041 std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
1042 Reader->getProfileSymbolList();
1043 ReaderList->dump(OS);
1044 }
1045
Diego Novillod5336ae2014-11-01 00:56:55 +00001046 return 0;
1047}
1048
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001049static int show_main(int argc, const char *argv[]) {
Diego Novillod5336ae2014-11-01 00:56:55 +00001050 cl::opt<std::string> Filename(cl::Positional, cl::Required,
1051 cl::desc("<profdata-file>"));
1052
1053 cl::opt<bool> ShowCounts("counts", cl::init(false),
1054 cl::desc("Show counter values for shown functions"));
Xinliang David Li6f7c19a2015-11-23 20:47:38 +00001055 cl::opt<bool> TextFormat(
1056 "text", cl::init(false),
1057 cl::desc("Show instr profile data in text dump format"));
Justin Bogner9e9a0572015-09-29 22:13:58 +00001058 cl::opt<bool> ShowIndirectCallTargets(
1059 "ic-targets", cl::init(false),
1060 cl::desc("Show indirect call site target values for shown functions"));
Rong Xu60faea12017-03-16 21:15:48 +00001061 cl::opt<bool> ShowMemOPSizes(
1062 "memop-sizes", cl::init(false),
1063 cl::desc("Show the profiled sizes of the memory intrinsic calls "
1064 "for shown functions"));
Easwaran Raman183ebbe2016-01-13 21:44:36 +00001065 cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
1066 cl::desc("Show detailed profile summary"));
1067 cl::list<uint32_t> DetailedSummaryCutoffs(
1068 cl::CommaSeparated, "detailed-summary-cutoffs",
1069 cl::desc(
1070 "Cutoff percentages (times 10000) for generating detailed summary"),
1071 cl::value_desc("800000,901000,999999"));
Diego Novillod5336ae2014-11-01 00:56:55 +00001072 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
1073 cl::desc("Details for every function"));
Rong Xua6ff69f2019-02-28 19:55:07 +00001074 cl::opt<bool> ShowCS("showcs", cl::init(false),
1075 cl::desc("Show context sensitive counts"));
Diego Novillod5336ae2014-11-01 00:56:55 +00001076 cl::opt<std::string> ShowFunction("function",
1077 cl::desc("Details for matching functions"));
1078
1079 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
1080 cl::init("-"), cl::desc("Output file"));
1081 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
1082 cl::aliasopt(OutputFilename));
1083 cl::opt<ProfileKinds> ProfileKind(
1084 cl::desc("Profile kind:"), cl::init(instr),
1085 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +00001086 clEnumVal(sample, "Sample profile")));
Xinliang David Li801b5312017-07-11 20:30:43 +00001087 cl::opt<uint32_t> TopNFunctions(
1088 "topn", cl::init(0),
1089 cl::desc("Show the list of functions with the largest internal counts"));
Rong Xu52aa2242019-01-08 22:41:48 +00001090 cl::opt<uint32_t> ValueCutoff(
1091 "value-cutoff", cl::init(0),
1092 cl::desc("Set the count value cutoff. Functions with the maximum count "
1093 "less than this value will not be printed out. (Default is 0)"));
1094 cl::opt<bool> OnlyListBelow(
1095 "list-below-cutoff", cl::init(false),
1096 cl::desc("Only output names of functions whose max count values are "
1097 "below the cutoff value"));
Wei Mi798e59b2019-08-31 02:27:26 +00001098 cl::opt<bool> ShowProfileSymbolList(
1099 "show-prof-sym-list", cl::init(false),
1100 cl::desc("Show profile symbol list if it exists in the profile. "));
Wei Mieee532c2019-09-21 17:23:55 +00001101 cl::opt<bool> ShowSectionInfoOnly(
1102 "show-sec-info-only", cl::init(false),
1103 cl::desc("Show the information of each section in the sample profile. "
1104 "The flag is only usable when the sample profile is in "
1105 "extbinary format"));
Wei Mi798e59b2019-08-31 02:27:26 +00001106
Diego Novillod5336ae2014-11-01 00:56:55 +00001107 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
1108
1109 if (OutputFilename.empty())
1110 OutputFilename = "-";
1111
Rong Xuf0d3dce2019-07-08 21:03:12 +00001112 if (!Filename.compare(OutputFilename)) {
1113 errs() << sys::path::filename(argv[0])
1114 << ": Input file name cannot be the same as the output file name!\n";
1115 return 1;
1116 }
1117
Diego Novillod5336ae2014-11-01 00:56:55 +00001118 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00001119 raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_Text);
Diego Novillod5336ae2014-11-01 00:56:55 +00001120 if (EC)
Xinliang David Li6f7c19a2015-11-23 20:47:38 +00001121 exitWithErrorCode(EC, OutputFilename);
Diego Novillod5336ae2014-11-01 00:56:55 +00001122
1123 if (ShowAllFunctions && !ShowFunction.empty())
Jonas Devliegheree46b7562018-04-18 14:42:33 +00001124 WithColor::warning() << "-function argument ignored: showing all functions\n";
Diego Novillod5336ae2014-11-01 00:56:55 +00001125
1126 if (ProfileKind == instr)
Xinliang David Li801b5312017-07-11 20:30:43 +00001127 return showInstrProfile(Filename, ShowCounts, TopNFunctions,
1128 ShowIndirectCallTargets, ShowMemOPSizes,
1129 ShowDetailedSummary, DetailedSummaryCutoffs,
Rong Xua6ff69f2019-02-28 19:55:07 +00001130 ShowAllFunctions, ShowCS, ValueCutoff,
1131 OnlyListBelow, ShowFunction, TextFormat, OS);
Diego Novillod5336ae2014-11-01 00:56:55 +00001132 else
1133 return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
Wei Mieee532c2019-09-21 17:23:55 +00001134 ShowFunction, ShowProfileSymbolList,
1135 ShowSectionInfoOnly, OS);
Diego Novillod5336ae2014-11-01 00:56:55 +00001136}
1137
Justin Bogner618bcea2014-03-19 02:20:46 +00001138int main(int argc, const char *argv[]) {
Rui Ueyama197194b2018-04-13 18:26:06 +00001139 InitLLVM X(argc, argv);
Justin Bogner618bcea2014-03-19 02:20:46 +00001140
1141 StringRef ProgName(sys::path::filename(argv[0]));
1142 if (argc > 1) {
Craig Toppere6cb63e2014-04-25 04:24:47 +00001143 int (*func)(int, const char *[]) = nullptr;
Justin Bogner618bcea2014-03-19 02:20:46 +00001144
1145 if (strcmp(argv[1], "merge") == 0)
1146 func = merge_main;
Justin Bogner9af28ef2014-03-21 17:29:44 +00001147 else if (strcmp(argv[1], "show") == 0)
1148 func = show_main;
Rong Xu998b97f2019-04-30 21:19:12 +00001149 else if (strcmp(argv[1], "overlap") == 0)
1150 func = overlap_main;
Justin Bogner618bcea2014-03-19 02:20:46 +00001151
1152 if (func) {
1153 std::string Invocation(ProgName.str() + " " + argv[1]);
1154 argv[1] = Invocation.c_str();
1155 return func(argc - 1, argv + 1);
1156 }
1157
Diego Novillod3babdb2015-12-14 20:37:15 +00001158 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
Justin Bogner618bcea2014-03-19 02:20:46 +00001159 strcmp(argv[1], "--help") == 0) {
1160
1161 errs() << "OVERVIEW: LLVM profile data tools\n\n"
1162 << "USAGE: " << ProgName << " <command> [args...]\n"
1163 << "USAGE: " << ProgName << " <command> -help\n\n"
Justin Bogner253eb172016-08-03 23:10:51 +00001164 << "See each individual command --help for more details.\n"
Rong Xu998b97f2019-04-30 21:19:12 +00001165 << "Available commands: merge, show, overlap\n";
Justin Bogner618bcea2014-03-19 02:20:46 +00001166 return 0;
1167 }
1168 }
1169
1170 if (argc < 2)
1171 errs() << ProgName << ": No command specified!\n";
1172 else
1173 errs() << ProgName << ": Unknown command!\n";
1174
Rong Xu998b97f2019-04-30 21:19:12 +00001175 errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
Justin Bogner618bcea2014-03-19 02:20:46 +00001176 return 1;
1177}