blob: 926dd1576e605fda4550afe60b38493fe315e506 [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,
40 PF_GCC,
Wei Mid9be2c72018-06-12 05:53:49 +000041 PF_Binary
Wei Mia0c08572018-06-11 22:40:43 +000042};
Xinliang David Li6f7c19a2015-11-23 20:47:38 +000043
Jonas Devliegheree46b7562018-04-18 14:42:33 +000044static void warn(Twine Message, std::string Whence = "",
Vedant Kumar188efda2017-11-17 21:18:32 +000045 std::string Hint = "") {
Jonas Devliegheree46b7562018-04-18 14:42:33 +000046 WithColor::warning();
Justin Bognerf8d79192014-03-21 17:24:48 +000047 if (!Whence.empty())
48 errs() << Whence << ": ";
49 errs() << Message << "\n";
Nathan Slingerland4f823662015-11-13 03:47:58 +000050 if (!Hint.empty())
Jonas Devliegheree46b7562018-04-18 14:42:33 +000051 WithColor::note() << Hint << "\n";
Vedant Kumar188efda2017-11-17 21:18:32 +000052}
53
54static void exitWithError(Twine Message, std::string Whence = "",
55 std::string Hint = "") {
Jonas Devliegheree46b7562018-04-18 14:42:33 +000056 WithColor::error();
57 if (!Whence.empty())
58 errs() << Whence << ": ";
59 errs() << Message << "\n";
60 if (!Hint.empty())
61 WithColor::note() << Hint << "\n";
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000062 ::exit(1);
63}
64
Vedant Kumar9152fd12016-05-19 03:54:45 +000065static void exitWithError(Error E, StringRef Whence = "") {
66 if (E.isA<InstrProfError>()) {
67 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
68 instrprof_error instrError = IPE.get();
69 StringRef Hint = "";
70 if (instrError == instrprof_error::unrecognized_format) {
71 // Hint for common error of forgetting -sample for sample profiles.
72 Hint = "Perhaps you forgot to use the -sample option?";
73 }
74 exitWithError(IPE.message(), Whence, Hint);
75 });
Nathan Slingerland4f823662015-11-13 03:47:58 +000076 }
Vedant Kumar9152fd12016-05-19 03:54:45 +000077
78 exitWithError(toString(std::move(E)), Whence);
79}
80
81static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
82 exitWithError(EC.message(), Whence);
Nathan Slingerland4f823662015-11-13 03:47:58 +000083}
84
Duncan P. N. Exon Smith02b6fa92015-06-16 00:43:04 +000085namespace {
Diego Novillod3babdb2015-12-14 20:37:15 +000086enum ProfileKinds { instr, sample };
Duncan P. N. Exon Smith02b6fa92015-06-16 00:43:04 +000087}
Justin Bogner618bcea2014-03-19 02:20:46 +000088
Vedant Kumar9152fd12016-05-19 03:54:45 +000089static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000090 StringRef WhenceFunction = "",
Diego Novillod3babdb2015-12-14 20:37:15 +000091 bool ShowHint = true) {
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000092 if (!WhenceFile.empty())
93 errs() << WhenceFile << ": ";
94 if (!WhenceFunction.empty())
95 errs() << WhenceFunction << ": ";
Vedant Kumar9152fd12016-05-19 03:54:45 +000096
97 auto IPE = instrprof_error::success;
98 E = handleErrors(std::move(E),
99 [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
100 IPE = E->get();
101 return Error(std::move(E));
102 });
103 errs() << toString(std::move(E)) << "\n";
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000104
105 if (ShowHint) {
106 StringRef Hint = "";
Vedant Kumar9152fd12016-05-19 03:54:45 +0000107 if (IPE != instrprof_error::success) {
108 switch (IPE) {
Nathan Slingerland11c938d12015-11-17 23:37:09 +0000109 case instrprof_error::hash_mismatch:
110 case instrprof_error::count_mismatch:
111 case instrprof_error::value_site_count_mismatch:
Diego Novillod3babdb2015-12-14 20:37:15 +0000112 Hint = "Make sure that all profile data to be merged is generated "
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000113 "from the same binary.";
Nathan Slingerland11c938d12015-11-17 23:37:09 +0000114 break;
Nathan Slingerlandb2d95f02015-11-18 00:52:45 +0000115 default:
116 break;
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000117 }
118 }
119
120 if (!Hint.empty())
121 errs() << Hint << "\n";
122 }
123}
124
Richard Smith3164fcf2018-09-13 20:22:02 +0000125namespace {
126/// A remapper from original symbol names to new symbol names based on a file
127/// containing a list of mappings from old name to new name.
128class SymbolRemapper {
129 std::unique_ptr<MemoryBuffer> File;
130 DenseMap<StringRef, StringRef> RemappingTable;
131
132public:
133 /// Build a SymbolRemapper from a file containing a list of old/new symbols.
134 static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
135 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
136 if (!BufOrError)
137 exitWithErrorCode(BufOrError.getError(), InputFile);
138
139 auto Remapper = llvm::make_unique<SymbolRemapper>();
140 Remapper->File = std::move(BufOrError.get());
141
142 for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
143 !LineIt.is_at_eof(); ++LineIt) {
144 std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
145 if (Parts.first.empty() || Parts.second.empty() ||
146 Parts.second.count(' ')) {
147 exitWithError("unexpected line in remapping file",
148 (InputFile + ":" + Twine(LineIt.line_number())).str(),
149 "expected 'old_symbol new_symbol'");
150 }
151 Remapper->RemappingTable.insert(Parts);
152 }
153 return Remapper;
154 }
155
156 /// Attempt to map the given old symbol into a new symbol.
157 ///
158 /// \return The new symbol, or \p Name if no such symbol was found.
159 StringRef operator()(StringRef Name) {
160 StringRef New = RemappingTable.lookup(Name);
161 return New.empty() ? Name : New;
162 }
163};
164}
165
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000166struct WeightedFile {
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000167 std::string Filename;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000168 uint64_t Weight;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000169};
170typedef SmallVector<WeightedFile, 5> WeightedFileVector;
171
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000172/// Keep track of merged data and reported errors.
173struct WriterContext {
174 std::mutex Lock;
175 InstrProfWriter Writer;
176 Error Err;
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000177 std::string ErrWhence;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000178 std::mutex &ErrLock;
179 SmallSet<instrprof_error, 4> &WriterErrorCodes;
180
181 WriterContext(bool IsSparse, std::mutex &ErrLock,
182 SmallSet<instrprof_error, 4> &WriterErrorCodes)
183 : Lock(), Writer(IsSparse), Err(Error::success()), ErrWhence(""),
184 ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {}
185};
186
Vedant Kumar188efda2017-11-17 21:18:32 +0000187/// Determine whether an error is fatal for profile merging.
188static bool isFatalError(instrprof_error IPE) {
189 switch (IPE) {
190 default:
191 return true;
192 case instrprof_error::success:
193 case instrprof_error::eof:
194 case instrprof_error::unknown_function:
195 case instrprof_error::hash_mismatch:
196 case instrprof_error::count_mismatch:
197 case instrprof_error::counter_overflow:
198 case instrprof_error::value_site_count_mismatch:
199 return false;
200 }
201}
202
Rong Xu998b97f2019-04-30 21:19:12 +0000203/// Computer the overlap b/w profile BaseFilename and TestFileName,
204/// and store the program level result to Overlap.
205static void overlapInput(const std::string &BaseFilename,
206 const std::string &TestFilename, WriterContext *WC,
207 OverlapStats &Overlap,
208 const OverlapFuncFilters &FuncFilter,
209 raw_fd_ostream &OS, bool IsCS) {
210 auto ReaderOrErr = InstrProfReader::create(TestFilename);
211 if (Error E = ReaderOrErr.takeError()) {
212 // Skip the empty profiles by returning sliently.
213 instrprof_error IPE = InstrProfError::take(std::move(E));
214 if (IPE != instrprof_error::empty_raw_profile)
215 WC->Err = make_error<InstrProfError>(IPE);
216 return;
217 }
218
219 auto Reader = std::move(ReaderOrErr.get());
220 for (auto &I : *Reader) {
221 OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
222 FuncOverlap.setFuncInfo(I.Name, I.Hash);
223
224 WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
225 FuncOverlap.dump(OS);
226 }
227}
228
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000229/// Load an input into a writer context.
Richard Smith3164fcf2018-09-13 20:22:02 +0000230static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
231 WriterContext *WC) {
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000232 std::unique_lock<std::mutex> CtxGuard{WC->Lock};
233
234 // If there's a pending hard error, don't do more work.
235 if (WC->Err)
236 return;
237
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000238 // Copy the filename, because llvm::ThreadPool copied the input "const
239 // WeightedFile &" by value, making a reference to the filename within it
240 // invalid outside of this packaged task.
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000241 WC->ErrWhence = Input.Filename;
242
243 auto ReaderOrErr = InstrProfReader::create(Input.Filename);
Rong Xu2c684cf2016-10-19 22:51:17 +0000244 if (Error E = ReaderOrErr.takeError()) {
245 // Skip the empty profiles by returning sliently.
246 instrprof_error IPE = InstrProfError::take(std::move(E));
247 if (IPE != instrprof_error::empty_raw_profile)
248 WC->Err = make_error<InstrProfError>(IPE);
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000249 return;
Rong Xu2c684cf2016-10-19 22:51:17 +0000250 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000251
252 auto Reader = std::move(ReaderOrErr.get());
253 bool IsIRProfile = Reader->isIRLevelProfile();
Rong Xua6ff69f2019-02-28 19:55:07 +0000254 bool HasCSIRProfile = Reader->hasCSIRLevelProfile();
255 if (WC->Writer.setIsIRLevelProfile(IsIRProfile, HasCSIRProfile)) {
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000256 WC->Err = make_error<StringError>(
257 "Merge IR generated profile with Clang generated profile.",
258 std::error_code());
259 return;
260 }
261
262 for (auto &I : *Reader) {
Richard Smith3164fcf2018-09-13 20:22:02 +0000263 if (Remapper)
264 I.Name = (*Remapper)(I.Name);
Rong Xufe90d862016-10-19 23:31:59 +0000265 const StringRef FuncName = I.Name;
David Blaikie98cce002017-07-10 03:04:59 +0000266 bool Reported = false;
267 WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
268 if (Reported) {
269 consumeError(std::move(E));
270 return;
271 }
272 Reported = true;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000273 // Only show hint the first time an error occurs.
274 instrprof_error IPE = InstrProfError::take(std::move(E));
275 std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
276 bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
277 handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
Rong Xufe90d862016-10-19 23:31:59 +0000278 FuncName, firstTime);
David Blaikie98cce002017-07-10 03:04:59 +0000279 });
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000280 }
Vedant Kumar188efda2017-11-17 21:18:32 +0000281 if (Reader->hasError()) {
282 if (Error E = Reader->getError()) {
283 instrprof_error IPE = InstrProfError::take(std::move(E));
284 if (isFatalError(IPE))
285 WC->Err = make_error<InstrProfError>(IPE);
286 }
287 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000288}
289
290/// Merge the \p Src writer context into \p Dst.
291static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000292 // If we've already seen a hard error, continuing with the merge would
293 // clobber it.
294 if (Dst->Err || Src->Err)
295 return;
296
David Blaikie98cce002017-07-10 03:04:59 +0000297 bool Reported = false;
298 Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
299 if (Reported) {
300 consumeError(std::move(E));
301 return;
302 }
303 Reported = true;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000304 Dst->Err = std::move(E);
David Blaikie98cce002017-07-10 03:04:59 +0000305 });
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000306}
307
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000308static void mergeInstrProfile(const WeightedFileVector &Inputs,
Richard Smith3164fcf2018-09-13 20:22:02 +0000309 SymbolRemapper *Remapper,
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000310 StringRef OutputFilename,
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000311 ProfileFormat OutputFormat, bool OutputSparse,
312 unsigned NumThreads) {
Justin Bognerb7aa2632014-04-18 21:48:40 +0000313 if (OutputFilename.compare("-") == 0)
314 exitWithError("Cannot write indexed profdata format to stdout.");
Justin Bognerec49f982014-03-12 22:00:57 +0000315
Wei Mid9be2c72018-06-12 05:53:49 +0000316 if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
Wei Mia0c08572018-06-11 22:40:43 +0000317 OutputFormat != PF_Text)
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000318 exitWithError("Unknown format is specified.");
319
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000320 std::mutex ErrorLock;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000321 SmallSet<instrprof_error, 4> WriterErrorCodes;
Justin Bognerf8d79192014-03-21 17:24:48 +0000322
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000323 // If NumThreads is not specified, auto-detect a good default.
324 if (NumThreads == 0)
Rafael Espindola8c0ff952017-10-04 20:27:01 +0000325 NumThreads =
326 std::min(hardware_concurrency(), unsigned((Inputs.size() + 1) / 2));
Rong Xu33c76c02016-02-10 17:18:30 +0000327
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000328 // Initialize the writer contexts.
329 SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
330 for (unsigned I = 0; I < NumThreads; ++I)
331 Contexts.emplace_back(llvm::make_unique<WriterContext>(
332 OutputSparse, ErrorLock, WriterErrorCodes));
333
334 if (NumThreads == 1) {
335 for (const auto &Input : Inputs)
Richard Smith3164fcf2018-09-13 20:22:02 +0000336 loadInput(Input, Remapper, Contexts[0].get());
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000337 } else {
338 ThreadPool Pool(NumThreads);
339
340 // Load the inputs in parallel (N/NumThreads serial steps).
341 unsigned Ctx = 0;
342 for (const auto &Input : Inputs) {
Richard Smith3164fcf2018-09-13 20:22:02 +0000343 Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get());
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000344 Ctx = (Ctx + 1) % NumThreads;
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000345 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000346 Pool.wait();
347
348 // Merge the writer contexts together (~ lg(NumThreads) serial steps).
349 unsigned Mid = Contexts.size() / 2;
350 unsigned End = Contexts.size();
351 assert(Mid > 0 && "Expected more than one context");
352 do {
353 for (unsigned I = 0; I < Mid; ++I)
354 Pool.async(mergeWriterContexts, Contexts[I].get(),
355 Contexts[I + Mid].get());
356 Pool.wait();
357 if (End & 1) {
358 Pool.async(mergeWriterContexts, Contexts[0].get(),
359 Contexts[End - 1].get());
360 Pool.wait();
361 }
362 End = Mid;
363 Mid /= 2;
364 } while (Mid > 0);
Justin Bognerbfee8d42014-03-12 20:14:17 +0000365 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000366
367 // Handle deferred hard errors encountered during merging.
Vedant Kumar188efda2017-11-17 21:18:32 +0000368 for (std::unique_ptr<WriterContext> &WC : Contexts) {
369 if (!WC->Err)
370 continue;
371 if (!WC->Err.isA<InstrProfError>())
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000372 exitWithError(std::move(WC->Err), WC->ErrWhence);
373
Vedant Kumar188efda2017-11-17 21:18:32 +0000374 instrprof_error IPE = InstrProfError::take(std::move(WC->Err));
375 if (isFatalError(IPE))
376 exitWithError(make_error<InstrProfError>(IPE), WC->ErrWhence);
377 else
Jonas Devliegheree46b7562018-04-18 14:42:33 +0000378 warn(toString(make_error<InstrProfError>(IPE)),
Vedant Kumar188efda2017-11-17 21:18:32 +0000379 WC->ErrWhence);
380 }
381
Rong Xuf0d3dce2019-07-08 21:03:12 +0000382 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000383 raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::OF_None);
Rong Xuf0d3dce2019-07-08 21:03:12 +0000384 if (EC)
385 exitWithErrorCode(EC, OutputFilename);
386
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000387 InstrProfWriter &Writer = Contexts[0]->Writer;
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000388 if (OutputFormat == PF_Text) {
389 if (Error E = Writer.writeText(Output))
390 exitWithError(std::move(E));
391 } else {
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000392 Writer.write(Output);
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000393 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000394}
395
Richard Smith3164fcf2018-09-13 20:22:02 +0000396/// Make a copy of the given function samples with all symbol names remapped
397/// by the provided symbol remapper.
398static sampleprof::FunctionSamples
399remapSamples(const sampleprof::FunctionSamples &Samples,
400 SymbolRemapper &Remapper, sampleprof_error &Error) {
401 sampleprof::FunctionSamples Result;
402 Result.setName(Remapper(Samples.getName()));
403 Result.addTotalSamples(Samples.getTotalSamples());
404 Result.addHeadSamples(Samples.getHeadSamples());
405 for (const auto &BodySample : Samples.getBodySamples()) {
406 Result.addBodySamples(BodySample.first.LineOffset,
407 BodySample.first.Discriminator,
408 BodySample.second.getSamples());
409 for (const auto &Target : BodySample.second.getCallTargets()) {
410 Result.addCalledTargetSamples(BodySample.first.LineOffset,
411 BodySample.first.Discriminator,
412 Remapper(Target.first()), Target.second);
413 }
414 }
415 for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
416 sampleprof::FunctionSamplesMap &Target =
417 Result.functionSamplesAt(CallsiteSamples.first);
418 for (const auto &Callsite : CallsiteSamples.second) {
419 sampleprof::FunctionSamples Remapped =
420 remapSamples(Callsite.second, Remapper, Error);
421 MergeResult(Error, Target[Remapped.getName()].merge(Remapped));
422 }
423 }
424 return Result;
425}
426
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000427static sampleprof::SampleProfileFormat FormatMap[] = {
Wei Mia0c08572018-06-11 22:40:43 +0000428 sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Compact_Binary,
Wei Mid9be2c72018-06-12 05:53:49 +0000429 sampleprof::SPF_GCC, sampleprof::SPF_Binary};
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000430
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000431static void mergeSampleProfile(const WeightedFileVector &Inputs,
Richard Smith3164fcf2018-09-13 20:22:02 +0000432 SymbolRemapper *Remapper,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000433 StringRef OutputFilename,
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000434 ProfileFormat OutputFormat) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000435 using namespace sampleprof;
Diego Novillod5336ae2014-11-01 00:56:55 +0000436 StringMap<FunctionSamples> ProfileMap;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000437 SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
Mehdi Amini03b42e42016-04-14 21:59:01 +0000438 LLVMContext Context;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000439 for (const auto &Input : Inputs) {
Mehdi Amini03b42e42016-04-14 21:59:01 +0000440 auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
Diego Novillofcd55602014-11-03 00:51:45 +0000441 if (std::error_code EC = ReaderOrErr.getError())
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000442 exitWithErrorCode(EC, Input.Filename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000443
Diego Novilloaae1ed82015-10-08 19:40:37 +0000444 // We need to keep the readers around until after all the files are
445 // read so that we do not lose the function names stored in each
446 // reader's memory. The function names are needed to write out the
447 // merged profile map.
448 Readers.push_back(std::move(ReaderOrErr.get()));
449 const auto Reader = Readers.back().get();
Diego Novillod5336ae2014-11-01 00:56:55 +0000450 if (std::error_code EC = Reader->read())
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000451 exitWithErrorCode(EC, Input.Filename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000452
453 StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
454 for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
455 E = Profiles.end();
456 I != E; ++I) {
Richard Smith3164fcf2018-09-13 20:22:02 +0000457 sampleprof_error Result = sampleprof_error::success;
458 FunctionSamples Remapped =
459 Remapper ? remapSamples(I->second, *Remapper, Result)
460 : FunctionSamples();
461 FunctionSamples &Samples = Remapper ? Remapped : I->second;
462 StringRef FName = Samples.getName();
463 MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight));
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000464 if (Result != sampleprof_error::success) {
465 std::error_code EC = make_error_code(Result);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000466 handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000467 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000468 }
469 }
Rong Xuf0d3dce2019-07-08 21:03:12 +0000470 auto WriterOrErr =
471 SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
472 if (std::error_code EC = WriterOrErr.getError())
473 exitWithErrorCode(EC, OutputFilename);
474
475 auto Writer = std::move(WriterOrErr.get());
Diego Novillod5336ae2014-11-01 00:56:55 +0000476 Writer->write(ProfileMap);
477}
478
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000479static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
Vedant Kumar8d0e8612016-06-06 23:43:56 +0000480 StringRef WeightStr, FileName;
481 std::tie(WeightStr, FileName) = WeightedFilename.split(',');
Diego Novillod5336ae2014-11-01 00:56:55 +0000482
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000483 uint64_t Weight;
484 if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
485 exitWithError("Input weight must be a positive integer.");
486
Benjamin Kramer929e7db2016-07-21 14:29:11 +0000487 return {FileName, Weight};
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000488}
489
Vedant Kumarcef43602016-06-07 22:47:31 +0000490static std::unique_ptr<MemoryBuffer>
491getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) {
492 if (InputFilenamesFile == "")
493 return {};
494
495 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile);
496 if (!BufOrError)
497 exitWithErrorCode(BufOrError.getError(), InputFilenamesFile);
498
499 return std::move(*BufOrError);
500}
501
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000502static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
503 StringRef Filename = WF.Filename;
504 uint64_t Weight = WF.Weight;
Benjamin Kramera81f4722016-07-22 12:39:55 +0000505
506 // If it's STDIN just pass it on.
507 if (Filename == "-") {
508 WNI.push_back({Filename, Weight});
509 return;
510 }
511
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000512 llvm::sys::fs::file_status Status;
513 llvm::sys::fs::status(Filename, Status);
514 if (!llvm::sys::fs::exists(Status))
515 exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
516 Filename);
517 // If it's a source file, collect it.
518 if (llvm::sys::fs::is_regular_file(Status)) {
Benjamin Kramer929e7db2016-07-21 14:29:11 +0000519 WNI.push_back({Filename, Weight});
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000520 return;
521 }
522
523 if (llvm::sys::fs::is_directory(Status)) {
524 std::error_code EC;
525 for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
526 F != E && !EC; F.increment(EC)) {
527 if (llvm::sys::fs::is_regular_file(F->path())) {
528 addWeightedInput(WNI, {F->path(), Weight});
529 }
530 }
531 if (EC)
532 exitWithErrorCode(EC, Filename);
533 }
534}
535
Vedant Kumarcef43602016-06-07 22:47:31 +0000536static void parseInputFilenamesFile(MemoryBuffer *Buffer,
537 WeightedFileVector &WFV) {
538 if (!Buffer)
539 return;
540
541 SmallVector<StringRef, 8> Entries;
542 StringRef Data = Buffer->getBuffer();
543 Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
544 for (const StringRef &FileWeightEntry : Entries) {
545 StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
546 // Skip comments.
547 if (SanitizedEntry.startswith("#"))
548 continue;
549 // If there's no comma, it's an unweighted profile.
550 else if (SanitizedEntry.find(',') == StringRef::npos)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000551 addWeightedInput(WFV, {SanitizedEntry, 1});
Vedant Kumarcef43602016-06-07 22:47:31 +0000552 else
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000553 addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
Vedant Kumarcef43602016-06-07 22:47:31 +0000554 }
555}
556
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000557static int merge_main(int argc, const char *argv[]) {
558 cl::list<std::string> InputFilenames(cl::Positional,
559 cl::desc("<filename...>"));
560 cl::list<std::string> WeightedInputFilenames("weighted-input",
561 cl::desc("<weight>,<filename>"));
Vedant Kumarcef43602016-06-07 22:47:31 +0000562 cl::opt<std::string> InputFilenamesFile(
563 "input-files", cl::init(""),
564 cl::desc("Path to file containing newline-separated "
565 "[<weight>,]<filename> entries"));
566 cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
567 cl::aliasopt(InputFilenamesFile));
568 cl::opt<bool> DumpInputFileList(
569 "dump-input-file-list", cl::init(false), cl::Hidden,
570 cl::desc("Dump the list of input files and their weights, then exit"));
Richard Smith3164fcf2018-09-13 20:22:02 +0000571 cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
572 cl::desc("Symbol remapping file"));
573 cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
574 cl::aliasopt(RemappingFile));
Diego Novillod5336ae2014-11-01 00:56:55 +0000575 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
576 cl::init("-"), cl::Required,
577 cl::desc("Output file"));
578 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
579 cl::aliasopt(OutputFilename));
580 cl::opt<ProfileKinds> ProfileKind(
581 cl::desc("Profile kind:"), cl::init(instr),
582 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000583 clEnumVal(sample, "Sample profile")));
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000584 cl::opt<ProfileFormat> OutputFormat(
Wei Mid9be2c72018-06-12 05:53:49 +0000585 cl::desc("Format of output profile"), cl::init(PF_Binary),
586 cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
587 clEnumValN(PF_Compact_Binary, "compbinary",
588 "Compact binary encoding"),
589 clEnumValN(PF_Text, "text", "Text encoding"),
590 clEnumValN(PF_GCC, "gcc",
591 "GCC encoding (only meaningful for -sample)")));
Vedant Kumar00dab222016-01-29 22:54:45 +0000592 cl::opt<bool> OutputSparse("sparse", cl::init(false),
593 cl::desc("Generate a sparse profile (only meaningful for -instr)"));
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000594 cl::opt<unsigned> NumThreads(
595 "num-threads", cl::init(0),
596 cl::desc("Number of merge threads to use (default: autodetect)"));
597 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
598 cl::aliasopt(NumThreads));
Vedant Kumar00dab222016-01-29 22:54:45 +0000599
Diego Novillod5336ae2014-11-01 00:56:55 +0000600 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
601
Vedant Kumarcef43602016-06-07 22:47:31 +0000602 WeightedFileVector WeightedInputs;
603 for (StringRef Filename : InputFilenames)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000604 addWeightedInput(WeightedInputs, {Filename, 1});
Vedant Kumarcef43602016-06-07 22:47:31 +0000605 for (StringRef WeightedFilename : WeightedInputFilenames)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000606 addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
Vedant Kumarcef43602016-06-07 22:47:31 +0000607
608 // Make sure that the file buffer stays alive for the duration of the
609 // weighted input vector's lifetime.
610 auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile);
611 parseInputFilenamesFile(Buffer.get(), WeightedInputs);
612
613 if (WeightedInputs.empty())
Chandler Carruth0c30f892016-06-04 03:08:01 +0000614 exitWithError("No input files specified. See " +
615 sys::path::filename(argv[0]) + " -help");
616
Vedant Kumarcef43602016-06-07 22:47:31 +0000617 if (DumpInputFileList) {
618 for (auto &WF : WeightedInputs)
619 outs() << WF.Weight << "," << WF.Filename << "\n";
620 return 0;
621 }
Vedant Kumarf771a052016-06-04 00:36:28 +0000622
Richard Smith3164fcf2018-09-13 20:22:02 +0000623 std::unique_ptr<SymbolRemapper> Remapper;
624 if (!RemappingFile.empty())
625 Remapper = SymbolRemapper::create(RemappingFile);
626
Diego Novillod5336ae2014-11-01 00:56:55 +0000627 if (ProfileKind == instr)
Richard Smith3164fcf2018-09-13 20:22:02 +0000628 mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
629 OutputFormat, OutputSparse, NumThreads);
Diego Novillod5336ae2014-11-01 00:56:55 +0000630 else
Richard Smith3164fcf2018-09-13 20:22:02 +0000631 mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
632 OutputFormat);
Justin Bognerbfee8d42014-03-12 20:14:17 +0000633
Justin Bognerec49f982014-03-12 22:00:57 +0000634 return 0;
Justin Bognerbfee8d42014-03-12 20:14:17 +0000635}
Justin Bogner618bcea2014-03-19 02:20:46 +0000636
Rong Xu998b97f2019-04-30 21:19:12 +0000637/// Computer the overlap b/w profile BaseFilename and profile TestFilename.
638static void overlapInstrProfile(const std::string &BaseFilename,
639 const std::string &TestFilename,
640 const OverlapFuncFilters &FuncFilter,
641 raw_fd_ostream &OS, bool IsCS) {
642 std::mutex ErrorLock;
643 SmallSet<instrprof_error, 4> WriterErrorCodes;
644 WriterContext Context(false, ErrorLock, WriterErrorCodes);
645 WeightedFile WeightedInput{BaseFilename, 1};
646 OverlapStats Overlap;
647 Error E = Overlap.accumuateCounts(BaseFilename, TestFilename, IsCS);
648 if (E)
649 exitWithError(std::move(E), "Error in getting profile count sums");
650 if (Overlap.Base.CountSum < 1.0f) {
651 OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
652 exit(0);
653 }
654 if (Overlap.Test.CountSum < 1.0f) {
655 OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
656 exit(0);
657 }
658 loadInput(WeightedInput, nullptr, &Context);
659 overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
660 IsCS);
661 Overlap.dump(OS);
662}
663
664static int overlap_main(int argc, const char *argv[]) {
665 cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
666 cl::desc("<base profile file>"));
667 cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
668 cl::desc("<test profile file>"));
669 cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
670 cl::desc("Output file"));
671 cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
672 cl::opt<bool> IsCS("cs", cl::init(false),
673 cl::desc("For context sensitive counts"));
674 cl::opt<unsigned long long> ValueCutoff(
675 "value-cutoff", cl::init(-1),
676 cl::desc(
677 "Function level overlap information for every function in test "
678 "profile with max count value greater then the parameter value"));
679 cl::opt<std::string> FuncNameFilter(
680 "function",
681 cl::desc("Function level overlap information for matching functions"));
682 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
683
684 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000685 raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_Text);
Rong Xu998b97f2019-04-30 21:19:12 +0000686 if (EC)
687 exitWithErrorCode(EC, Output);
688
689 overlapInstrProfile(BaseFilename, TestFilename,
690 OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
691 IsCS);
692
693 return 0;
694}
695
Rong Xu0cf1f562017-03-09 19:03:57 +0000696typedef struct ValueSitesStats {
697 ValueSitesStats()
698 : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
699 TotalNumValues(0) {}
700 uint64_t TotalNumValueSites;
701 uint64_t TotalNumValueSitesWithValueProfile;
702 uint64_t TotalNumValues;
703 std::vector<unsigned> ValueSitesHistogram;
704} ValueSitesStats;
705
706static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
707 ValueSitesStats &Stats, raw_fd_ostream &OS,
Rong Xu60faea12017-03-16 21:15:48 +0000708 InstrProfSymtab *Symtab) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000709 uint32_t NS = Func.getNumValueSites(VK);
710 Stats.TotalNumValueSites += NS;
711 for (size_t I = 0; I < NS; ++I) {
712 uint32_t NV = Func.getNumValueDataForSite(VK, I);
713 std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
714 Stats.TotalNumValues += NV;
715 if (NV) {
716 Stats.TotalNumValueSitesWithValueProfile++;
717 if (NV > Stats.ValueSitesHistogram.size())
718 Stats.ValueSitesHistogram.resize(NV, 0);
719 Stats.ValueSitesHistogram[NV - 1]++;
720 }
Rong Xu52aa2242019-01-08 22:41:48 +0000721
722 uint64_t SiteSum = 0;
723 for (uint32_t V = 0; V < NV; V++)
724 SiteSum += VD[V].Count;
725 if (SiteSum == 0)
726 SiteSum = 1;
727
Rong Xu0cf1f562017-03-09 19:03:57 +0000728 for (uint32_t V = 0; V < NV; V++) {
Rong Xu52aa2242019-01-08 22:41:48 +0000729 OS << "\t[ " << format("%2u", I) << ", ";
Rong Xu60faea12017-03-16 21:15:48 +0000730 if (Symtab == nullptr)
Petar Jovanovic40a7f632019-02-05 18:09:28 +0000731 OS << format("%4" PRIu64, VD[V].Value);
Rong Xu60faea12017-03-16 21:15:48 +0000732 else
733 OS << Symtab->getFuncName(VD[V].Value);
Rong Xu52aa2242019-01-08 22:41:48 +0000734 OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
735 << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
Rong Xu0cf1f562017-03-09 19:03:57 +0000736 }
737 }
738}
739
740static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
741 ValueSitesStats &Stats) {
742 OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n";
743 OS << " Total number of sites with values: "
744 << Stats.TotalNumValueSitesWithValueProfile << "\n";
745 OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n";
746
747 OS << " Value sites histogram:\n\tNumTargets, SiteCount\n";
748 for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
749 if (Stats.ValueSitesHistogram[I] > 0)
750 OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
751 }
752}
753
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000754static int showInstrProfile(const std::string &Filename, bool ShowCounts,
Xinliang David Li801b5312017-07-11 20:30:43 +0000755 uint32_t TopN, bool ShowIndirectCallTargets,
756 bool ShowMemOPSizes, bool ShowDetailedSummary,
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000757 std::vector<uint32_t> DetailedSummaryCutoffs,
Rong Xua6ff69f2019-02-28 19:55:07 +0000758 bool ShowAllFunctions, bool ShowCS,
759 uint64_t ValueCutoff, bool OnlyListBelow,
760 const std::string &ShowFunction, bool TextFormat,
761 raw_fd_ostream &OS) {
Diego Novillofcd55602014-11-03 00:51:45 +0000762 auto ReaderOrErr = InstrProfReader::create(Filename);
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000763 std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
764 if (ShowDetailedSummary && Cutoffs.empty()) {
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000765 Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
766 }
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000767 InstrProfSummaryBuilder Builder(std::move(Cutoffs));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000768 if (Error E = ReaderOrErr.takeError())
769 exitWithError(std::move(E), Filename);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000770
Diego Novillofcd55602014-11-03 00:51:45 +0000771 auto Reader = std::move(ReaderOrErr.get());
Rong Xu33c76c02016-02-10 17:18:30 +0000772 bool IsIRInstr = Reader->isIRLevelProfile();
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000773 size_t ShownFunctions = 0;
Rong Xu52aa2242019-01-08 22:41:48 +0000774 size_t BelowCutoffFunctions = 0;
Rong Xu0cf1f562017-03-09 19:03:57 +0000775 int NumVPKind = IPVK_Last - IPVK_First + 1;
776 std::vector<ValueSitesStats> VPStats(NumVPKind);
Xinliang David Li801b5312017-07-11 20:30:43 +0000777
778 auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
779 const std::pair<std::string, uint64_t> &v2) {
780 return v1.second > v2.second;
781 };
782
783 std::priority_queue<std::pair<std::string, uint64_t>,
784 std::vector<std::pair<std::string, uint64_t>>,
785 decltype(MinCmp)>
786 HottestFuncs(MinCmp);
787
Rong Xu52aa2242019-01-08 22:41:48 +0000788 if (!TextFormat && OnlyListBelow) {
789 OS << "The list of functions with the maximum counter less than "
790 << ValueCutoff << ":\n";
791 }
792
Richard Smithc6ba9ca2018-08-24 01:34:45 +0000793 // Add marker so that IR-level instrumentation round-trips properly.
794 if (TextFormat && IsIRInstr)
795 OS << ":ir\n";
796
Justin Bogner9af28ef2014-03-21 17:29:44 +0000797 for (const auto &Func : *Reader) {
Rong Xua6ff69f2019-02-28 19:55:07 +0000798 if (Reader->isIRLevelProfile()) {
799 bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
800 if (FuncIsCS != ShowCS)
801 continue;
802 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000803 bool Show =
804 ShowAllFunctions || (!ShowFunction.empty() &&
805 Func.Name.find(ShowFunction) != Func.Name.npos);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000806
Richard Smithc6ba9ca2018-08-24 01:34:45 +0000807 bool doTextFormatDump = (Show && TextFormat);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000808
809 if (doTextFormatDump) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000810 InstrProfSymtab &Symtab = Reader->getSymtab();
David Blaikiecf9d52c2017-07-06 19:00:12 +0000811 InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
812 OS);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000813 continue;
814 }
815
Justin Bognerb59d7c72014-04-25 02:45:33 +0000816 assert(Func.Counts.size() > 0 && "function missing entry counter");
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000817 Builder.addRecord(Func);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000818
Rong Xu52aa2242019-01-08 22:41:48 +0000819 uint64_t FuncMax = 0;
820 uint64_t FuncSum = 0;
821 for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
822 FuncMax = std::max(FuncMax, Func.Counts[I]);
823 FuncSum += Func.Counts[I];
824 }
Rong Xu7162e162019-01-08 22:37:12 +0000825
Rong Xu52aa2242019-01-08 22:41:48 +0000826 if (FuncMax < ValueCutoff) {
827 ++BelowCutoffFunctions;
828 if (OnlyListBelow) {
829 OS << " " << Func.Name << ": (Max = " << FuncMax
830 << " Sum = " << FuncSum << ")\n";
831 }
832 continue;
833 } else if (OnlyListBelow)
834 continue;
835
836 if (TopN) {
Xinliang David Li801b5312017-07-11 20:30:43 +0000837 if (HottestFuncs.size() == TopN) {
838 if (HottestFuncs.top().second < FuncMax) {
839 HottestFuncs.pop();
840 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
841 }
842 } else
843 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
844 }
845
Justin Bogner9af28ef2014-03-21 17:29:44 +0000846 if (Show) {
847 if (!ShownFunctions)
848 OS << "Counters:\n";
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000849
Justin Bogner9af28ef2014-03-21 17:29:44 +0000850 ++ShownFunctions;
851
852 OS << " " << Func.Name << ":\n"
Justin Bogner423380f2014-03-23 20:43:50 +0000853 << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
Rong Xu33c76c02016-02-10 17:18:30 +0000854 << " Counters: " << Func.Counts.size() << "\n";
855 if (!IsIRInstr)
856 OS << " Function count: " << Func.Counts[0] << "\n";
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000857
Justin Bogner9e9a0572015-09-29 22:13:58 +0000858 if (ShowIndirectCallTargets)
Xinliang David Li2004f002015-11-02 05:08:23 +0000859 OS << " Indirect Call Site Count: "
860 << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
Justin Bogner9af28ef2014-03-21 17:29:44 +0000861
Rong Xu60faea12017-03-16 21:15:48 +0000862 uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
863 if (ShowMemOPSizes && NumMemOPCalls > 0)
864 OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls
865 << "\n";
866
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000867 if (ShowCounts) {
868 OS << " Block counts: [";
Rong Xu33c76c02016-02-10 17:18:30 +0000869 size_t Start = (IsIRInstr ? 0 : 1);
870 for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
871 OS << (I == Start ? "" : ", ") << Func.Counts[I];
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000872 }
873 OS << "]\n";
874 }
Justin Bogner9e9a0572015-09-29 22:13:58 +0000875
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000876 if (ShowIndirectCallTargets) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000877 OS << " Indirect Target Results:\n";
878 traverseAllValueSites(Func, IPVK_IndirectCallTarget,
879 VPStats[IPVK_IndirectCallTarget], OS,
Rong Xu60faea12017-03-16 21:15:48 +0000880 &(Reader->getSymtab()));
881 }
882
883 if (ShowMemOPSizes && NumMemOPCalls > 0) {
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000884 OS << " Memory Intrinsic Size Results:\n";
Rong Xu60faea12017-03-16 21:15:48 +0000885 traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
886 nullptr);
Justin Bogner9e9a0572015-09-29 22:13:58 +0000887 }
888 }
Justin Bogner9af28ef2014-03-21 17:29:44 +0000889 }
Justin Bognerdb1225d2014-03-23 20:55:53 +0000890 if (Reader->hasError())
Vedant Kumar9152fd12016-05-19 03:54:45 +0000891 exitWithError(Reader->getError(), Filename);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000892
Richard Smithc6ba9ca2018-08-24 01:34:45 +0000893 if (TextFormat)
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000894 return 0;
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000895 std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
Adam Nemet1142b2d2017-11-14 16:59:18 +0000896 OS << "Instrumentation level: "
897 << (Reader->isIRLevelProfile() ? "IR" : "Front-end") << "\n";
Justin Bogner9af28ef2014-03-21 17:29:44 +0000898 if (ShowAllFunctions || !ShowFunction.empty())
899 OS << "Functions shown: " << ShownFunctions << "\n";
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000900 OS << "Total functions: " << PS->getNumFunctions() << "\n";
Rong Xu52aa2242019-01-08 22:41:48 +0000901 if (ValueCutoff > 0) {
902 OS << "Number of functions with maximum count (< " << ValueCutoff
903 << "): " << BelowCutoffFunctions << "\n";
904 OS << "Number of functions with maximum count (>= " << ValueCutoff
905 << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
906 }
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000907 OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000908 OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
Rong Xu60faea12017-03-16 21:15:48 +0000909
Xinliang David Li801b5312017-07-11 20:30:43 +0000910 if (TopN) {
911 std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
912 while (!HottestFuncs.empty()) {
913 SortedHottestFuncs.emplace_back(HottestFuncs.top());
914 HottestFuncs.pop();
915 }
916 OS << "Top " << TopN
917 << " functions with the largest internal block counts: \n";
918 for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
919 OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
920 }
921
Xinliang David Li872362c2016-05-23 16:36:11 +0000922 if (ShownFunctions && ShowIndirectCallTargets) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000923 OS << "Statistics for indirect call sites profile:\n";
924 showValueSitesStats(OS, IPVK_IndirectCallTarget,
925 VPStats[IPVK_IndirectCallTarget]);
Xinliang David Li872362c2016-05-23 16:36:11 +0000926 }
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000927
Rong Xu60faea12017-03-16 21:15:48 +0000928 if (ShownFunctions && ShowMemOPSizes) {
929 OS << "Statistics for memory intrinsic calls sizes profile:\n";
930 showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
931 }
932
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000933 if (ShowDetailedSummary) {
934 OS << "Detailed summary:\n";
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000935 OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000936 OS << "Total count: " << PS->getTotalCount() << "\n";
937 for (auto Entry : PS->getDetailedSummary()) {
Easwaran Raman43095702016-02-17 18:18:47 +0000938 OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000939 << " account for "
940 << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
941 << " percentage of the total counts.\n";
942 }
943 }
Justin Bogner9af28ef2014-03-21 17:29:44 +0000944 return 0;
945}
946
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000947static int showSampleProfile(const std::string &Filename, bool ShowCounts,
948 bool ShowAllFunctions,
949 const std::string &ShowFunction,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000950 raw_fd_ostream &OS) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000951 using namespace sampleprof;
Mehdi Amini03b42e42016-04-14 21:59:01 +0000952 LLVMContext Context;
953 auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
Diego Novillofcd55602014-11-03 00:51:45 +0000954 if (std::error_code EC = ReaderOrErr.getError())
Nathan Slingerland4f823662015-11-13 03:47:58 +0000955 exitWithErrorCode(EC, Filename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000956
Diego Novillofcd55602014-11-03 00:51:45 +0000957 auto Reader = std::move(ReaderOrErr.get());
Diego Novilloc6d032a2015-09-17 00:17:21 +0000958 if (std::error_code EC = Reader->read())
Nathan Slingerland4f823662015-11-13 03:47:58 +0000959 exitWithErrorCode(EC, Filename);
Diego Novilloc6d032a2015-09-17 00:17:21 +0000960
Diego Novillod5336ae2014-11-01 00:56:55 +0000961 if (ShowAllFunctions || ShowFunction.empty())
962 Reader->dump(OS);
963 else
964 Reader->dumpFunctionProfile(ShowFunction, OS);
965
966 return 0;
967}
968
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000969static int show_main(int argc, const char *argv[]) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000970 cl::opt<std::string> Filename(cl::Positional, cl::Required,
971 cl::desc("<profdata-file>"));
972
973 cl::opt<bool> ShowCounts("counts", cl::init(false),
974 cl::desc("Show counter values for shown functions"));
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000975 cl::opt<bool> TextFormat(
976 "text", cl::init(false),
977 cl::desc("Show instr profile data in text dump format"));
Justin Bogner9e9a0572015-09-29 22:13:58 +0000978 cl::opt<bool> ShowIndirectCallTargets(
979 "ic-targets", cl::init(false),
980 cl::desc("Show indirect call site target values for shown functions"));
Rong Xu60faea12017-03-16 21:15:48 +0000981 cl::opt<bool> ShowMemOPSizes(
982 "memop-sizes", cl::init(false),
983 cl::desc("Show the profiled sizes of the memory intrinsic calls "
984 "for shown functions"));
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000985 cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
986 cl::desc("Show detailed profile summary"));
987 cl::list<uint32_t> DetailedSummaryCutoffs(
988 cl::CommaSeparated, "detailed-summary-cutoffs",
989 cl::desc(
990 "Cutoff percentages (times 10000) for generating detailed summary"),
991 cl::value_desc("800000,901000,999999"));
Diego Novillod5336ae2014-11-01 00:56:55 +0000992 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
993 cl::desc("Details for every function"));
Rong Xua6ff69f2019-02-28 19:55:07 +0000994 cl::opt<bool> ShowCS("showcs", cl::init(false),
995 cl::desc("Show context sensitive counts"));
Diego Novillod5336ae2014-11-01 00:56:55 +0000996 cl::opt<std::string> ShowFunction("function",
997 cl::desc("Details for matching functions"));
998
999 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
1000 cl::init("-"), cl::desc("Output file"));
1001 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
1002 cl::aliasopt(OutputFilename));
1003 cl::opt<ProfileKinds> ProfileKind(
1004 cl::desc("Profile kind:"), cl::init(instr),
1005 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +00001006 clEnumVal(sample, "Sample profile")));
Xinliang David Li801b5312017-07-11 20:30:43 +00001007 cl::opt<uint32_t> TopNFunctions(
1008 "topn", cl::init(0),
1009 cl::desc("Show the list of functions with the largest internal counts"));
Rong Xu52aa2242019-01-08 22:41:48 +00001010 cl::opt<uint32_t> ValueCutoff(
1011 "value-cutoff", cl::init(0),
1012 cl::desc("Set the count value cutoff. Functions with the maximum count "
1013 "less than this value will not be printed out. (Default is 0)"));
1014 cl::opt<bool> OnlyListBelow(
1015 "list-below-cutoff", cl::init(false),
1016 cl::desc("Only output names of functions whose max count values are "
1017 "below the cutoff value"));
Diego Novillod5336ae2014-11-01 00:56:55 +00001018 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
1019
1020 if (OutputFilename.empty())
1021 OutputFilename = "-";
1022
Rong Xuf0d3dce2019-07-08 21:03:12 +00001023 if (!Filename.compare(OutputFilename)) {
1024 errs() << sys::path::filename(argv[0])
1025 << ": Input file name cannot be the same as the output file name!\n";
1026 return 1;
1027 }
1028
Diego Novillod5336ae2014-11-01 00:56:55 +00001029 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00001030 raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_Text);
Diego Novillod5336ae2014-11-01 00:56:55 +00001031 if (EC)
Xinliang David Li6f7c19a2015-11-23 20:47:38 +00001032 exitWithErrorCode(EC, OutputFilename);
Diego Novillod5336ae2014-11-01 00:56:55 +00001033
1034 if (ShowAllFunctions && !ShowFunction.empty())
Jonas Devliegheree46b7562018-04-18 14:42:33 +00001035 WithColor::warning() << "-function argument ignored: showing all functions\n";
Diego Novillod5336ae2014-11-01 00:56:55 +00001036
1037 if (ProfileKind == instr)
Xinliang David Li801b5312017-07-11 20:30:43 +00001038 return showInstrProfile(Filename, ShowCounts, TopNFunctions,
1039 ShowIndirectCallTargets, ShowMemOPSizes,
1040 ShowDetailedSummary, DetailedSummaryCutoffs,
Rong Xua6ff69f2019-02-28 19:55:07 +00001041 ShowAllFunctions, ShowCS, ValueCutoff,
1042 OnlyListBelow, ShowFunction, TextFormat, OS);
Diego Novillod5336ae2014-11-01 00:56:55 +00001043 else
1044 return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
1045 ShowFunction, OS);
1046}
1047
Justin Bogner618bcea2014-03-19 02:20:46 +00001048int main(int argc, const char *argv[]) {
Rui Ueyama197194b2018-04-13 18:26:06 +00001049 InitLLVM X(argc, argv);
Justin Bogner618bcea2014-03-19 02:20:46 +00001050
1051 StringRef ProgName(sys::path::filename(argv[0]));
1052 if (argc > 1) {
Craig Toppere6cb63e2014-04-25 04:24:47 +00001053 int (*func)(int, const char *[]) = nullptr;
Justin Bogner618bcea2014-03-19 02:20:46 +00001054
1055 if (strcmp(argv[1], "merge") == 0)
1056 func = merge_main;
Justin Bogner9af28ef2014-03-21 17:29:44 +00001057 else if (strcmp(argv[1], "show") == 0)
1058 func = show_main;
Rong Xu998b97f2019-04-30 21:19:12 +00001059 else if (strcmp(argv[1], "overlap") == 0)
1060 func = overlap_main;
Justin Bogner618bcea2014-03-19 02:20:46 +00001061
1062 if (func) {
1063 std::string Invocation(ProgName.str() + " " + argv[1]);
1064 argv[1] = Invocation.c_str();
1065 return func(argc - 1, argv + 1);
1066 }
1067
Diego Novillod3babdb2015-12-14 20:37:15 +00001068 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
Justin Bogner618bcea2014-03-19 02:20:46 +00001069 strcmp(argv[1], "--help") == 0) {
1070
1071 errs() << "OVERVIEW: LLVM profile data tools\n\n"
1072 << "USAGE: " << ProgName << " <command> [args...]\n"
1073 << "USAGE: " << ProgName << " <command> -help\n\n"
Justin Bogner253eb172016-08-03 23:10:51 +00001074 << "See each individual command --help for more details.\n"
Rong Xu998b97f2019-04-30 21:19:12 +00001075 << "Available commands: merge, show, overlap\n";
Justin Bogner618bcea2014-03-19 02:20:46 +00001076 return 0;
1077 }
1078 }
1079
1080 if (argc < 2)
1081 errs() << ProgName << ": No command specified!\n";
1082 else
1083 errs() << ProgName << ": Unknown command!\n";
1084
Rong Xu998b97f2019-04-30 21:19:12 +00001085 errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
Justin Bogner618bcea2014-03-19 02:20:46 +00001086 return 1;
1087}