blob: cb043837134a83709655967a47e61707e0c3ca6c [file] [log] [blame]
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +00001//===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// llvm-profdata merges .profdata files.
11//
12//===----------------------------------------------------------------------===//
13
Nathan Slingerlandc21a44d2015-11-18 17:10:24 +000014#include "llvm/ADT/SmallSet.h"
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +000015#include "llvm/ADT/SmallVector.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000016#include "llvm/ADT/StringRef.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000017#include "llvm/IR/LLVMContext.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000018#include "llvm/ProfileData/InstrProfReader.h"
Justin Bognerb9bd7f82014-03-21 17:46:22 +000019#include "llvm/ProfileData/InstrProfWriter.h"
Easwaran Ramand68aae22016-02-04 23:34:31 +000020#include "llvm/ProfileData/ProfileCommon.h"
Diego Novillod5336ae2014-11-01 00:56:55 +000021#include "llvm/ProfileData/SampleProfReader.h"
22#include "llvm/ProfileData/SampleProfWriter.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000023#include "llvm/Support/CommandLine.h"
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +000024#include "llvm/Support/Errc.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000025#include "llvm/Support/FileSystem.h"
Justin Bogner423380f2014-03-23 20:43:50 +000026#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000027#include "llvm/Support/InitLLVM.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000029#include "llvm/Support/Path.h"
Jonas Devliegheree46b7562018-04-18 14:42:33 +000030#include "llvm/Support/WithColor.h"
Vedant Kumare3a0bf52016-07-19 01:17:20 +000031#include "llvm/Support/ThreadPool.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000032#include "llvm/Support/raw_ostream.h"
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +000033#include <algorithm>
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000034
35using namespace llvm;
36
Xinliang David Li6f7c19a2015-11-23 20:47:38 +000037enum ProfileFormat { PF_None = 0, PF_Text, PF_Binary, PF_GCC };
38
Jonas Devliegheree46b7562018-04-18 14:42:33 +000039static void warn(Twine Message, std::string Whence = "",
Vedant Kumar188efda2017-11-17 21:18:32 +000040 std::string Hint = "") {
Jonas Devliegheree46b7562018-04-18 14:42:33 +000041 WithColor::warning();
Justin Bognerf8d79192014-03-21 17:24:48 +000042 if (!Whence.empty())
43 errs() << Whence << ": ";
44 errs() << Message << "\n";
Nathan Slingerland4f823662015-11-13 03:47:58 +000045 if (!Hint.empty())
Jonas Devliegheree46b7562018-04-18 14:42:33 +000046 WithColor::note() << Hint << "\n";
Vedant Kumar188efda2017-11-17 21:18:32 +000047}
48
49static void exitWithError(Twine Message, std::string Whence = "",
50 std::string Hint = "") {
Jonas Devliegheree46b7562018-04-18 14:42:33 +000051 WithColor::error();
52 if (!Whence.empty())
53 errs() << Whence << ": ";
54 errs() << Message << "\n";
55 if (!Hint.empty())
56 WithColor::note() << Hint << "\n";
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000057 ::exit(1);
58}
59
Vedant Kumar9152fd12016-05-19 03:54:45 +000060static void exitWithError(Error E, StringRef Whence = "") {
61 if (E.isA<InstrProfError>()) {
62 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
63 instrprof_error instrError = IPE.get();
64 StringRef Hint = "";
65 if (instrError == instrprof_error::unrecognized_format) {
66 // Hint for common error of forgetting -sample for sample profiles.
67 Hint = "Perhaps you forgot to use the -sample option?";
68 }
69 exitWithError(IPE.message(), Whence, Hint);
70 });
Nathan Slingerland4f823662015-11-13 03:47:58 +000071 }
Vedant Kumar9152fd12016-05-19 03:54:45 +000072
73 exitWithError(toString(std::move(E)), Whence);
74}
75
76static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
77 exitWithError(EC.message(), Whence);
Nathan Slingerland4f823662015-11-13 03:47:58 +000078}
79
Duncan P. N. Exon Smith02b6fa92015-06-16 00:43:04 +000080namespace {
Diego Novillod3babdb2015-12-14 20:37:15 +000081enum ProfileKinds { instr, sample };
Duncan P. N. Exon Smith02b6fa92015-06-16 00:43:04 +000082}
Justin Bogner618bcea2014-03-19 02:20:46 +000083
Vedant Kumar9152fd12016-05-19 03:54:45 +000084static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000085 StringRef WhenceFunction = "",
Diego Novillod3babdb2015-12-14 20:37:15 +000086 bool ShowHint = true) {
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000087 if (!WhenceFile.empty())
88 errs() << WhenceFile << ": ";
89 if (!WhenceFunction.empty())
90 errs() << WhenceFunction << ": ";
Vedant Kumar9152fd12016-05-19 03:54:45 +000091
92 auto IPE = instrprof_error::success;
93 E = handleErrors(std::move(E),
94 [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
95 IPE = E->get();
96 return Error(std::move(E));
97 });
98 errs() << toString(std::move(E)) << "\n";
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000099
100 if (ShowHint) {
101 StringRef Hint = "";
Vedant Kumar9152fd12016-05-19 03:54:45 +0000102 if (IPE != instrprof_error::success) {
103 switch (IPE) {
Nathan Slingerland11c938d12015-11-17 23:37:09 +0000104 case instrprof_error::hash_mismatch:
105 case instrprof_error::count_mismatch:
106 case instrprof_error::value_site_count_mismatch:
Diego Novillod3babdb2015-12-14 20:37:15 +0000107 Hint = "Make sure that all profile data to be merged is generated "
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000108 "from the same binary.";
Nathan Slingerland11c938d12015-11-17 23:37:09 +0000109 break;
Nathan Slingerlandb2d95f02015-11-18 00:52:45 +0000110 default:
111 break;
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000112 }
113 }
114
115 if (!Hint.empty())
116 errs() << Hint << "\n";
117 }
118}
119
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000120struct WeightedFile {
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000121 std::string Filename;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000122 uint64_t Weight;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000123};
124typedef SmallVector<WeightedFile, 5> WeightedFileVector;
125
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000126/// Keep track of merged data and reported errors.
127struct WriterContext {
128 std::mutex Lock;
129 InstrProfWriter Writer;
130 Error Err;
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000131 std::string ErrWhence;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000132 std::mutex &ErrLock;
133 SmallSet<instrprof_error, 4> &WriterErrorCodes;
134
135 WriterContext(bool IsSparse, std::mutex &ErrLock,
136 SmallSet<instrprof_error, 4> &WriterErrorCodes)
137 : Lock(), Writer(IsSparse), Err(Error::success()), ErrWhence(""),
138 ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {}
139};
140
Vedant Kumar188efda2017-11-17 21:18:32 +0000141/// Determine whether an error is fatal for profile merging.
142static bool isFatalError(instrprof_error IPE) {
143 switch (IPE) {
144 default:
145 return true;
146 case instrprof_error::success:
147 case instrprof_error::eof:
148 case instrprof_error::unknown_function:
149 case instrprof_error::hash_mismatch:
150 case instrprof_error::count_mismatch:
151 case instrprof_error::counter_overflow:
152 case instrprof_error::value_site_count_mismatch:
153 return false;
154 }
155}
156
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000157/// Load an input into a writer context.
158static void loadInput(const WeightedFile &Input, WriterContext *WC) {
159 std::unique_lock<std::mutex> CtxGuard{WC->Lock};
160
161 // If there's a pending hard error, don't do more work.
162 if (WC->Err)
163 return;
164
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000165 // Copy the filename, because llvm::ThreadPool copied the input "const
166 // WeightedFile &" by value, making a reference to the filename within it
167 // invalid outside of this packaged task.
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000168 WC->ErrWhence = Input.Filename;
169
170 auto ReaderOrErr = InstrProfReader::create(Input.Filename);
Rong Xu2c684cf2016-10-19 22:51:17 +0000171 if (Error E = ReaderOrErr.takeError()) {
172 // Skip the empty profiles by returning sliently.
173 instrprof_error IPE = InstrProfError::take(std::move(E));
174 if (IPE != instrprof_error::empty_raw_profile)
175 WC->Err = make_error<InstrProfError>(IPE);
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000176 return;
Rong Xu2c684cf2016-10-19 22:51:17 +0000177 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000178
179 auto Reader = std::move(ReaderOrErr.get());
180 bool IsIRProfile = Reader->isIRLevelProfile();
181 if (WC->Writer.setIsIRLevelProfile(IsIRProfile)) {
182 WC->Err = make_error<StringError>(
183 "Merge IR generated profile with Clang generated profile.",
184 std::error_code());
185 return;
186 }
187
188 for (auto &I : *Reader) {
Rong Xufe90d862016-10-19 23:31:59 +0000189 const StringRef FuncName = I.Name;
David Blaikie98cce002017-07-10 03:04:59 +0000190 bool Reported = false;
191 WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
192 if (Reported) {
193 consumeError(std::move(E));
194 return;
195 }
196 Reported = true;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000197 // Only show hint the first time an error occurs.
198 instrprof_error IPE = InstrProfError::take(std::move(E));
199 std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
200 bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
201 handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
Rong Xufe90d862016-10-19 23:31:59 +0000202 FuncName, firstTime);
David Blaikie98cce002017-07-10 03:04:59 +0000203 });
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000204 }
Vedant Kumar188efda2017-11-17 21:18:32 +0000205 if (Reader->hasError()) {
206 if (Error E = Reader->getError()) {
207 instrprof_error IPE = InstrProfError::take(std::move(E));
208 if (isFatalError(IPE))
209 WC->Err = make_error<InstrProfError>(IPE);
210 }
211 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000212}
213
214/// Merge the \p Src writer context into \p Dst.
215static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000216 // If we've already seen a hard error, continuing with the merge would
217 // clobber it.
218 if (Dst->Err || Src->Err)
219 return;
220
David Blaikie98cce002017-07-10 03:04:59 +0000221 bool Reported = false;
222 Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
223 if (Reported) {
224 consumeError(std::move(E));
225 return;
226 }
227 Reported = true;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000228 Dst->Err = std::move(E);
David Blaikie98cce002017-07-10 03:04:59 +0000229 });
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000230}
231
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000232static void mergeInstrProfile(const WeightedFileVector &Inputs,
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000233 StringRef OutputFilename,
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000234 ProfileFormat OutputFormat, bool OutputSparse,
235 unsigned NumThreads) {
Justin Bognerb7aa2632014-04-18 21:48:40 +0000236 if (OutputFilename.compare("-") == 0)
237 exitWithError("Cannot write indexed profdata format to stdout.");
Justin Bognerec49f982014-03-12 22:00:57 +0000238
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000239 if (OutputFormat != PF_Binary && OutputFormat != PF_Text)
240 exitWithError("Unknown format is specified.");
241
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000242 std::error_code EC;
243 raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
244 if (EC)
Nathan Slingerland4f823662015-11-13 03:47:58 +0000245 exitWithErrorCode(EC, OutputFilename);
Justin Bognerec49f982014-03-12 22:00:57 +0000246
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000247 std::mutex ErrorLock;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000248 SmallSet<instrprof_error, 4> WriterErrorCodes;
Justin Bognerf8d79192014-03-21 17:24:48 +0000249
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000250 // If NumThreads is not specified, auto-detect a good default.
251 if (NumThreads == 0)
Rafael Espindola8c0ff952017-10-04 20:27:01 +0000252 NumThreads =
253 std::min(hardware_concurrency(), unsigned((Inputs.size() + 1) / 2));
Rong Xu33c76c02016-02-10 17:18:30 +0000254
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000255 // Initialize the writer contexts.
256 SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
257 for (unsigned I = 0; I < NumThreads; ++I)
258 Contexts.emplace_back(llvm::make_unique<WriterContext>(
259 OutputSparse, ErrorLock, WriterErrorCodes));
260
261 if (NumThreads == 1) {
262 for (const auto &Input : Inputs)
263 loadInput(Input, Contexts[0].get());
264 } else {
265 ThreadPool Pool(NumThreads);
266
267 // Load the inputs in parallel (N/NumThreads serial steps).
268 unsigned Ctx = 0;
269 for (const auto &Input : Inputs) {
270 Pool.async(loadInput, Input, Contexts[Ctx].get());
271 Ctx = (Ctx + 1) % NumThreads;
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000272 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000273 Pool.wait();
274
275 // Merge the writer contexts together (~ lg(NumThreads) serial steps).
276 unsigned Mid = Contexts.size() / 2;
277 unsigned End = Contexts.size();
278 assert(Mid > 0 && "Expected more than one context");
279 do {
280 for (unsigned I = 0; I < Mid; ++I)
281 Pool.async(mergeWriterContexts, Contexts[I].get(),
282 Contexts[I + Mid].get());
283 Pool.wait();
284 if (End & 1) {
285 Pool.async(mergeWriterContexts, Contexts[0].get(),
286 Contexts[End - 1].get());
287 Pool.wait();
288 }
289 End = Mid;
290 Mid /= 2;
291 } while (Mid > 0);
Justin Bognerbfee8d42014-03-12 20:14:17 +0000292 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000293
294 // Handle deferred hard errors encountered during merging.
Vedant Kumar188efda2017-11-17 21:18:32 +0000295 for (std::unique_ptr<WriterContext> &WC : Contexts) {
296 if (!WC->Err)
297 continue;
298 if (!WC->Err.isA<InstrProfError>())
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000299 exitWithError(std::move(WC->Err), WC->ErrWhence);
300
Vedant Kumar188efda2017-11-17 21:18:32 +0000301 instrprof_error IPE = InstrProfError::take(std::move(WC->Err));
302 if (isFatalError(IPE))
303 exitWithError(make_error<InstrProfError>(IPE), WC->ErrWhence);
304 else
Jonas Devliegheree46b7562018-04-18 14:42:33 +0000305 warn(toString(make_error<InstrProfError>(IPE)),
Vedant Kumar188efda2017-11-17 21:18:32 +0000306 WC->ErrWhence);
307 }
308
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000309 InstrProfWriter &Writer = Contexts[0]->Writer;
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000310 if (OutputFormat == PF_Text) {
311 if (Error E = Writer.writeText(Output))
312 exitWithError(std::move(E));
313 } else {
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000314 Writer.write(Output);
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000315 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000316}
317
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000318static sampleprof::SampleProfileFormat FormatMap[] = {
319 sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Binary,
320 sampleprof::SPF_GCC};
321
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000322static void mergeSampleProfile(const WeightedFileVector &Inputs,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000323 StringRef OutputFilename,
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000324 ProfileFormat OutputFormat) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000325 using namespace sampleprof;
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000326 auto WriterOrErr =
327 SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
Diego Novillofcd55602014-11-03 00:51:45 +0000328 if (std::error_code EC = WriterOrErr.getError())
Nathan Slingerland4f823662015-11-13 03:47:58 +0000329 exitWithErrorCode(EC, OutputFilename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000330
Diego Novillofcd55602014-11-03 00:51:45 +0000331 auto Writer = std::move(WriterOrErr.get());
Diego Novillod5336ae2014-11-01 00:56:55 +0000332 StringMap<FunctionSamples> ProfileMap;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000333 SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
Mehdi Amini03b42e42016-04-14 21:59:01 +0000334 LLVMContext Context;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000335 for (const auto &Input : Inputs) {
Mehdi Amini03b42e42016-04-14 21:59:01 +0000336 auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
Diego Novillofcd55602014-11-03 00:51:45 +0000337 if (std::error_code EC = ReaderOrErr.getError())
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000338 exitWithErrorCode(EC, Input.Filename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000339
Diego Novilloaae1ed82015-10-08 19:40:37 +0000340 // We need to keep the readers around until after all the files are
341 // read so that we do not lose the function names stored in each
342 // reader's memory. The function names are needed to write out the
343 // merged profile map.
344 Readers.push_back(std::move(ReaderOrErr.get()));
345 const auto Reader = Readers.back().get();
Diego Novillod5336ae2014-11-01 00:56:55 +0000346 if (std::error_code EC = Reader->read())
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000347 exitWithErrorCode(EC, Input.Filename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000348
349 StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
350 for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
351 E = Profiles.end();
352 I != E; ++I) {
353 StringRef FName = I->first();
354 FunctionSamples &Samples = I->second;
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000355 sampleprof_error Result = ProfileMap[FName].merge(Samples, Input.Weight);
356 if (Result != sampleprof_error::success) {
357 std::error_code EC = make_error_code(Result);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000358 handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000359 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000360 }
361 }
362 Writer->write(ProfileMap);
363}
364
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000365static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
Vedant Kumar8d0e8612016-06-06 23:43:56 +0000366 StringRef WeightStr, FileName;
367 std::tie(WeightStr, FileName) = WeightedFilename.split(',');
Diego Novillod5336ae2014-11-01 00:56:55 +0000368
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000369 uint64_t Weight;
370 if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
371 exitWithError("Input weight must be a positive integer.");
372
Benjamin Kramer929e7db2016-07-21 14:29:11 +0000373 return {FileName, Weight};
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000374}
375
Vedant Kumarcef43602016-06-07 22:47:31 +0000376static std::unique_ptr<MemoryBuffer>
377getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) {
378 if (InputFilenamesFile == "")
379 return {};
380
381 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile);
382 if (!BufOrError)
383 exitWithErrorCode(BufOrError.getError(), InputFilenamesFile);
384
385 return std::move(*BufOrError);
386}
387
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000388static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
389 StringRef Filename = WF.Filename;
390 uint64_t Weight = WF.Weight;
Benjamin Kramera81f4722016-07-22 12:39:55 +0000391
392 // If it's STDIN just pass it on.
393 if (Filename == "-") {
394 WNI.push_back({Filename, Weight});
395 return;
396 }
397
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000398 llvm::sys::fs::file_status Status;
399 llvm::sys::fs::status(Filename, Status);
400 if (!llvm::sys::fs::exists(Status))
401 exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
402 Filename);
403 // If it's a source file, collect it.
404 if (llvm::sys::fs::is_regular_file(Status)) {
Benjamin Kramer929e7db2016-07-21 14:29:11 +0000405 WNI.push_back({Filename, Weight});
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000406 return;
407 }
408
409 if (llvm::sys::fs::is_directory(Status)) {
410 std::error_code EC;
411 for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
412 F != E && !EC; F.increment(EC)) {
413 if (llvm::sys::fs::is_regular_file(F->path())) {
414 addWeightedInput(WNI, {F->path(), Weight});
415 }
416 }
417 if (EC)
418 exitWithErrorCode(EC, Filename);
419 }
420}
421
Vedant Kumarcef43602016-06-07 22:47:31 +0000422static void parseInputFilenamesFile(MemoryBuffer *Buffer,
423 WeightedFileVector &WFV) {
424 if (!Buffer)
425 return;
426
427 SmallVector<StringRef, 8> Entries;
428 StringRef Data = Buffer->getBuffer();
429 Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
430 for (const StringRef &FileWeightEntry : Entries) {
431 StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
432 // Skip comments.
433 if (SanitizedEntry.startswith("#"))
434 continue;
435 // If there's no comma, it's an unweighted profile.
436 else if (SanitizedEntry.find(',') == StringRef::npos)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000437 addWeightedInput(WFV, {SanitizedEntry, 1});
Vedant Kumarcef43602016-06-07 22:47:31 +0000438 else
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000439 addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
Vedant Kumarcef43602016-06-07 22:47:31 +0000440 }
441}
442
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000443static int merge_main(int argc, const char *argv[]) {
444 cl::list<std::string> InputFilenames(cl::Positional,
445 cl::desc("<filename...>"));
446 cl::list<std::string> WeightedInputFilenames("weighted-input",
447 cl::desc("<weight>,<filename>"));
Vedant Kumarcef43602016-06-07 22:47:31 +0000448 cl::opt<std::string> InputFilenamesFile(
449 "input-files", cl::init(""),
450 cl::desc("Path to file containing newline-separated "
451 "[<weight>,]<filename> entries"));
452 cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
453 cl::aliasopt(InputFilenamesFile));
454 cl::opt<bool> DumpInputFileList(
455 "dump-input-file-list", cl::init(false), cl::Hidden,
456 cl::desc("Dump the list of input files and their weights, then exit"));
Diego Novillod5336ae2014-11-01 00:56:55 +0000457 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
458 cl::init("-"), cl::Required,
459 cl::desc("Output file"));
460 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
461 cl::aliasopt(OutputFilename));
462 cl::opt<ProfileKinds> ProfileKind(
463 cl::desc("Profile kind:"), cl::init(instr),
464 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000465 clEnumVal(sample, "Sample profile")));
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000466 cl::opt<ProfileFormat> OutputFormat(
467 cl::desc("Format of output profile"), cl::init(PF_Binary),
468 cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
469 clEnumValN(PF_Text, "text", "Text encoding"),
470 clEnumValN(PF_GCC, "gcc",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000471 "GCC encoding (only meaningful for -sample)")));
Vedant Kumar00dab222016-01-29 22:54:45 +0000472 cl::opt<bool> OutputSparse("sparse", cl::init(false),
473 cl::desc("Generate a sparse profile (only meaningful for -instr)"));
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000474 cl::opt<unsigned> NumThreads(
475 "num-threads", cl::init(0),
476 cl::desc("Number of merge threads to use (default: autodetect)"));
477 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
478 cl::aliasopt(NumThreads));
Vedant Kumar00dab222016-01-29 22:54:45 +0000479
Diego Novillod5336ae2014-11-01 00:56:55 +0000480 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
481
Vedant Kumarcef43602016-06-07 22:47:31 +0000482 WeightedFileVector WeightedInputs;
483 for (StringRef Filename : InputFilenames)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000484 addWeightedInput(WeightedInputs, {Filename, 1});
Vedant Kumarcef43602016-06-07 22:47:31 +0000485 for (StringRef WeightedFilename : WeightedInputFilenames)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000486 addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
Vedant Kumarcef43602016-06-07 22:47:31 +0000487
488 // Make sure that the file buffer stays alive for the duration of the
489 // weighted input vector's lifetime.
490 auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile);
491 parseInputFilenamesFile(Buffer.get(), WeightedInputs);
492
493 if (WeightedInputs.empty())
Chandler Carruth0c30f892016-06-04 03:08:01 +0000494 exitWithError("No input files specified. See " +
495 sys::path::filename(argv[0]) + " -help");
496
Vedant Kumarcef43602016-06-07 22:47:31 +0000497 if (DumpInputFileList) {
498 for (auto &WF : WeightedInputs)
499 outs() << WF.Weight << "," << WF.Filename << "\n";
500 return 0;
501 }
Vedant Kumarf771a052016-06-04 00:36:28 +0000502
Diego Novillod5336ae2014-11-01 00:56:55 +0000503 if (ProfileKind == instr)
Vedant Kumar00dab222016-01-29 22:54:45 +0000504 mergeInstrProfile(WeightedInputs, OutputFilename, OutputFormat,
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000505 OutputSparse, NumThreads);
Diego Novillod5336ae2014-11-01 00:56:55 +0000506 else
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000507 mergeSampleProfile(WeightedInputs, OutputFilename, OutputFormat);
Justin Bognerbfee8d42014-03-12 20:14:17 +0000508
Justin Bognerec49f982014-03-12 22:00:57 +0000509 return 0;
Justin Bognerbfee8d42014-03-12 20:14:17 +0000510}
Justin Bogner618bcea2014-03-19 02:20:46 +0000511
Rong Xu0cf1f562017-03-09 19:03:57 +0000512typedef struct ValueSitesStats {
513 ValueSitesStats()
514 : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
515 TotalNumValues(0) {}
516 uint64_t TotalNumValueSites;
517 uint64_t TotalNumValueSitesWithValueProfile;
518 uint64_t TotalNumValues;
519 std::vector<unsigned> ValueSitesHistogram;
520} ValueSitesStats;
521
522static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
523 ValueSitesStats &Stats, raw_fd_ostream &OS,
Rong Xu60faea12017-03-16 21:15:48 +0000524 InstrProfSymtab *Symtab) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000525 uint32_t NS = Func.getNumValueSites(VK);
526 Stats.TotalNumValueSites += NS;
527 for (size_t I = 0; I < NS; ++I) {
528 uint32_t NV = Func.getNumValueDataForSite(VK, I);
529 std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
530 Stats.TotalNumValues += NV;
531 if (NV) {
532 Stats.TotalNumValueSitesWithValueProfile++;
533 if (NV > Stats.ValueSitesHistogram.size())
534 Stats.ValueSitesHistogram.resize(NV, 0);
535 Stats.ValueSitesHistogram[NV - 1]++;
536 }
537 for (uint32_t V = 0; V < NV; V++) {
538 OS << "\t[ " << I << ", ";
Rong Xu60faea12017-03-16 21:15:48 +0000539 if (Symtab == nullptr)
540 OS << VD[V].Value;
541 else
542 OS << Symtab->getFuncName(VD[V].Value);
543 OS << ", " << VD[V].Count << " ]\n";
Rong Xu0cf1f562017-03-09 19:03:57 +0000544 }
545 }
546}
547
548static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
549 ValueSitesStats &Stats) {
550 OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n";
551 OS << " Total number of sites with values: "
552 << Stats.TotalNumValueSitesWithValueProfile << "\n";
553 OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n";
554
555 OS << " Value sites histogram:\n\tNumTargets, SiteCount\n";
556 for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
557 if (Stats.ValueSitesHistogram[I] > 0)
558 OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
559 }
560}
561
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000562static int showInstrProfile(const std::string &Filename, bool ShowCounts,
Xinliang David Li801b5312017-07-11 20:30:43 +0000563 uint32_t TopN, bool ShowIndirectCallTargets,
564 bool ShowMemOPSizes, bool ShowDetailedSummary,
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000565 std::vector<uint32_t> DetailedSummaryCutoffs,
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000566 bool ShowAllFunctions,
567 const std::string &ShowFunction, bool TextFormat,
568 raw_fd_ostream &OS) {
Diego Novillofcd55602014-11-03 00:51:45 +0000569 auto ReaderOrErr = InstrProfReader::create(Filename);
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000570 std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
571 if (ShowDetailedSummary && Cutoffs.empty()) {
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000572 Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
573 }
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000574 InstrProfSummaryBuilder Builder(std::move(Cutoffs));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000575 if (Error E = ReaderOrErr.takeError())
576 exitWithError(std::move(E), Filename);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000577
Diego Novillofcd55602014-11-03 00:51:45 +0000578 auto Reader = std::move(ReaderOrErr.get());
Rong Xu33c76c02016-02-10 17:18:30 +0000579 bool IsIRInstr = Reader->isIRLevelProfile();
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000580 size_t ShownFunctions = 0;
Rong Xu0cf1f562017-03-09 19:03:57 +0000581 int NumVPKind = IPVK_Last - IPVK_First + 1;
582 std::vector<ValueSitesStats> VPStats(NumVPKind);
Xinliang David Li801b5312017-07-11 20:30:43 +0000583
584 auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
585 const std::pair<std::string, uint64_t> &v2) {
586 return v1.second > v2.second;
587 };
588
589 std::priority_queue<std::pair<std::string, uint64_t>,
590 std::vector<std::pair<std::string, uint64_t>>,
591 decltype(MinCmp)>
592 HottestFuncs(MinCmp);
593
Justin Bogner9af28ef2014-03-21 17:29:44 +0000594 for (const auto &Func : *Reader) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000595 bool Show =
596 ShowAllFunctions || (!ShowFunction.empty() &&
597 Func.Name.find(ShowFunction) != Func.Name.npos);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000598
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000599 bool doTextFormatDump = (Show && ShowCounts && TextFormat);
600
601 if (doTextFormatDump) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000602 InstrProfSymtab &Symtab = Reader->getSymtab();
David Blaikiecf9d52c2017-07-06 19:00:12 +0000603 InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
604 OS);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000605 continue;
606 }
607
Justin Bognerb59d7c72014-04-25 02:45:33 +0000608 assert(Func.Counts.size() > 0 && "function missing entry counter");
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000609 Builder.addRecord(Func);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000610
Xinliang David Li801b5312017-07-11 20:30:43 +0000611 if (TopN) {
612 uint64_t FuncMax = 0;
613 for (size_t I = 0, E = Func.Counts.size(); I < E; ++I)
614 FuncMax = std::max(FuncMax, Func.Counts[I]);
615
616 if (HottestFuncs.size() == TopN) {
617 if (HottestFuncs.top().second < FuncMax) {
618 HottestFuncs.pop();
619 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
620 }
621 } else
622 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
623 }
624
Justin Bogner9af28ef2014-03-21 17:29:44 +0000625 if (Show) {
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000626
Justin Bogner9af28ef2014-03-21 17:29:44 +0000627 if (!ShownFunctions)
628 OS << "Counters:\n";
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000629
Justin Bogner9af28ef2014-03-21 17:29:44 +0000630 ++ShownFunctions;
631
632 OS << " " << Func.Name << ":\n"
Justin Bogner423380f2014-03-23 20:43:50 +0000633 << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
Rong Xu33c76c02016-02-10 17:18:30 +0000634 << " Counters: " << Func.Counts.size() << "\n";
635 if (!IsIRInstr)
636 OS << " Function count: " << Func.Counts[0] << "\n";
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000637
Justin Bogner9e9a0572015-09-29 22:13:58 +0000638 if (ShowIndirectCallTargets)
Xinliang David Li2004f002015-11-02 05:08:23 +0000639 OS << " Indirect Call Site Count: "
640 << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
Justin Bogner9af28ef2014-03-21 17:29:44 +0000641
Rong Xu60faea12017-03-16 21:15:48 +0000642 uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
643 if (ShowMemOPSizes && NumMemOPCalls > 0)
644 OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls
645 << "\n";
646
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000647 if (ShowCounts) {
648 OS << " Block counts: [";
Rong Xu33c76c02016-02-10 17:18:30 +0000649 size_t Start = (IsIRInstr ? 0 : 1);
650 for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
651 OS << (I == Start ? "" : ", ") << Func.Counts[I];
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000652 }
653 OS << "]\n";
654 }
Justin Bogner9e9a0572015-09-29 22:13:58 +0000655
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000656 if (ShowIndirectCallTargets) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000657 OS << " Indirect Target Results:\n";
658 traverseAllValueSites(Func, IPVK_IndirectCallTarget,
659 VPStats[IPVK_IndirectCallTarget], OS,
Rong Xu60faea12017-03-16 21:15:48 +0000660 &(Reader->getSymtab()));
661 }
662
663 if (ShowMemOPSizes && NumMemOPCalls > 0) {
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000664 OS << " Memory Intrinsic Size Results:\n";
Rong Xu60faea12017-03-16 21:15:48 +0000665 traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
666 nullptr);
Justin Bogner9e9a0572015-09-29 22:13:58 +0000667 }
668 }
Justin Bogner9af28ef2014-03-21 17:29:44 +0000669 }
Justin Bognerdb1225d2014-03-23 20:55:53 +0000670 if (Reader->hasError())
Vedant Kumar9152fd12016-05-19 03:54:45 +0000671 exitWithError(Reader->getError(), Filename);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000672
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000673 if (ShowCounts && TextFormat)
674 return 0;
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000675 std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
Adam Nemet1142b2d2017-11-14 16:59:18 +0000676 OS << "Instrumentation level: "
677 << (Reader->isIRLevelProfile() ? "IR" : "Front-end") << "\n";
Justin Bogner9af28ef2014-03-21 17:29:44 +0000678 if (ShowAllFunctions || !ShowFunction.empty())
679 OS << "Functions shown: " << ShownFunctions << "\n";
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000680 OS << "Total functions: " << PS->getNumFunctions() << "\n";
681 OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000682 OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
Rong Xu60faea12017-03-16 21:15:48 +0000683
Xinliang David Li801b5312017-07-11 20:30:43 +0000684 if (TopN) {
685 std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
686 while (!HottestFuncs.empty()) {
687 SortedHottestFuncs.emplace_back(HottestFuncs.top());
688 HottestFuncs.pop();
689 }
690 OS << "Top " << TopN
691 << " functions with the largest internal block counts: \n";
692 for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
693 OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
694 }
695
Xinliang David Li872362c2016-05-23 16:36:11 +0000696 if (ShownFunctions && ShowIndirectCallTargets) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000697 OS << "Statistics for indirect call sites profile:\n";
698 showValueSitesStats(OS, IPVK_IndirectCallTarget,
699 VPStats[IPVK_IndirectCallTarget]);
Xinliang David Li872362c2016-05-23 16:36:11 +0000700 }
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000701
Rong Xu60faea12017-03-16 21:15:48 +0000702 if (ShownFunctions && ShowMemOPSizes) {
703 OS << "Statistics for memory intrinsic calls sizes profile:\n";
704 showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
705 }
706
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000707 if (ShowDetailedSummary) {
708 OS << "Detailed summary:\n";
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000709 OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000710 OS << "Total count: " << PS->getTotalCount() << "\n";
711 for (auto Entry : PS->getDetailedSummary()) {
Easwaran Raman43095702016-02-17 18:18:47 +0000712 OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000713 << " account for "
714 << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
715 << " percentage of the total counts.\n";
716 }
717 }
Justin Bogner9af28ef2014-03-21 17:29:44 +0000718 return 0;
719}
720
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000721static int showSampleProfile(const std::string &Filename, bool ShowCounts,
722 bool ShowAllFunctions,
723 const std::string &ShowFunction,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000724 raw_fd_ostream &OS) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000725 using namespace sampleprof;
Mehdi Amini03b42e42016-04-14 21:59:01 +0000726 LLVMContext Context;
727 auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
Diego Novillofcd55602014-11-03 00:51:45 +0000728 if (std::error_code EC = ReaderOrErr.getError())
Nathan Slingerland4f823662015-11-13 03:47:58 +0000729 exitWithErrorCode(EC, Filename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000730
Diego Novillofcd55602014-11-03 00:51:45 +0000731 auto Reader = std::move(ReaderOrErr.get());
Diego Novilloc6d032a2015-09-17 00:17:21 +0000732 if (std::error_code EC = Reader->read())
Nathan Slingerland4f823662015-11-13 03:47:58 +0000733 exitWithErrorCode(EC, Filename);
Diego Novilloc6d032a2015-09-17 00:17:21 +0000734
Diego Novillod5336ae2014-11-01 00:56:55 +0000735 if (ShowAllFunctions || ShowFunction.empty())
736 Reader->dump(OS);
737 else
738 Reader->dumpFunctionProfile(ShowFunction, OS);
739
740 return 0;
741}
742
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000743static int show_main(int argc, const char *argv[]) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000744 cl::opt<std::string> Filename(cl::Positional, cl::Required,
745 cl::desc("<profdata-file>"));
746
747 cl::opt<bool> ShowCounts("counts", cl::init(false),
748 cl::desc("Show counter values for shown functions"));
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000749 cl::opt<bool> TextFormat(
750 "text", cl::init(false),
751 cl::desc("Show instr profile data in text dump format"));
Justin Bogner9e9a0572015-09-29 22:13:58 +0000752 cl::opt<bool> ShowIndirectCallTargets(
753 "ic-targets", cl::init(false),
754 cl::desc("Show indirect call site target values for shown functions"));
Rong Xu60faea12017-03-16 21:15:48 +0000755 cl::opt<bool> ShowMemOPSizes(
756 "memop-sizes", cl::init(false),
757 cl::desc("Show the profiled sizes of the memory intrinsic calls "
758 "for shown functions"));
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000759 cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
760 cl::desc("Show detailed profile summary"));
761 cl::list<uint32_t> DetailedSummaryCutoffs(
762 cl::CommaSeparated, "detailed-summary-cutoffs",
763 cl::desc(
764 "Cutoff percentages (times 10000) for generating detailed summary"),
765 cl::value_desc("800000,901000,999999"));
Diego Novillod5336ae2014-11-01 00:56:55 +0000766 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
767 cl::desc("Details for every function"));
768 cl::opt<std::string> ShowFunction("function",
769 cl::desc("Details for matching functions"));
770
771 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
772 cl::init("-"), cl::desc("Output file"));
773 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
774 cl::aliasopt(OutputFilename));
775 cl::opt<ProfileKinds> ProfileKind(
776 cl::desc("Profile kind:"), cl::init(instr),
777 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000778 clEnumVal(sample, "Sample profile")));
Xinliang David Li801b5312017-07-11 20:30:43 +0000779 cl::opt<uint32_t> TopNFunctions(
780 "topn", cl::init(0),
781 cl::desc("Show the list of functions with the largest internal counts"));
Diego Novillod5336ae2014-11-01 00:56:55 +0000782
783 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
784
785 if (OutputFilename.empty())
786 OutputFilename = "-";
787
788 std::error_code EC;
789 raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
790 if (EC)
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000791 exitWithErrorCode(EC, OutputFilename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000792
793 if (ShowAllFunctions && !ShowFunction.empty())
Jonas Devliegheree46b7562018-04-18 14:42:33 +0000794 WithColor::warning() << "-function argument ignored: showing all functions\n";
Diego Novillod5336ae2014-11-01 00:56:55 +0000795
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000796 std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs.begin(),
797 DetailedSummaryCutoffs.end());
Diego Novillod5336ae2014-11-01 00:56:55 +0000798 if (ProfileKind == instr)
Xinliang David Li801b5312017-07-11 20:30:43 +0000799 return showInstrProfile(Filename, ShowCounts, TopNFunctions,
800 ShowIndirectCallTargets, ShowMemOPSizes,
801 ShowDetailedSummary, DetailedSummaryCutoffs,
802 ShowAllFunctions, ShowFunction, TextFormat, OS);
Diego Novillod5336ae2014-11-01 00:56:55 +0000803 else
804 return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
805 ShowFunction, OS);
806}
807
Justin Bogner618bcea2014-03-19 02:20:46 +0000808int main(int argc, const char *argv[]) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000809 InitLLVM X(argc, argv);
Justin Bogner618bcea2014-03-19 02:20:46 +0000810
811 StringRef ProgName(sys::path::filename(argv[0]));
812 if (argc > 1) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000813 int (*func)(int, const char *[]) = nullptr;
Justin Bogner618bcea2014-03-19 02:20:46 +0000814
815 if (strcmp(argv[1], "merge") == 0)
816 func = merge_main;
Justin Bogner9af28ef2014-03-21 17:29:44 +0000817 else if (strcmp(argv[1], "show") == 0)
818 func = show_main;
Justin Bogner618bcea2014-03-19 02:20:46 +0000819
820 if (func) {
821 std::string Invocation(ProgName.str() + " " + argv[1]);
822 argv[1] = Invocation.c_str();
823 return func(argc - 1, argv + 1);
824 }
825
Diego Novillod3babdb2015-12-14 20:37:15 +0000826 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
Justin Bogner618bcea2014-03-19 02:20:46 +0000827 strcmp(argv[1], "--help") == 0) {
828
829 errs() << "OVERVIEW: LLVM profile data tools\n\n"
830 << "USAGE: " << ProgName << " <command> [args...]\n"
831 << "USAGE: " << ProgName << " <command> -help\n\n"
Justin Bogner253eb172016-08-03 23:10:51 +0000832 << "See each individual command --help for more details.\n"
Justin Bogner9af28ef2014-03-21 17:29:44 +0000833 << "Available commands: merge, show\n";
Justin Bogner618bcea2014-03-19 02:20:46 +0000834 return 0;
835 }
836 }
837
838 if (argc < 2)
839 errs() << ProgName << ": No command specified!\n";
840 else
841 errs() << ProgName << ": Unknown command!\n";
842
Justin Bogner9af28ef2014-03-21 17:29:44 +0000843 errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
Justin Bogner618bcea2014-03-19 02:20:46 +0000844 return 1;
845}