1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // llvm-profdata merges .profdata files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/SmallSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/ProfileData/InstrProfReader.h"
19 #include "llvm/ProfileData/InstrProfWriter.h"
20 #include "llvm/ProfileData/SampleProfReader.h"
21 #include "llvm/ProfileData/SampleProfWriter.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/Signals.h"
31 #include "llvm/Support/raw_ostream.h"
37 enum ProfileFormat { PF_None = 0, PF_Text, PF_Binary, PF_GCC };
39 static void exitWithError(const Twine &Message, StringRef Whence = "",
40 StringRef Hint = "") {
43 errs() << Whence << ": ";
44 errs() << Message << "\n";
46 errs() << Hint << "\n";
50 static void exitWithErrorCode(const std::error_code &Error,
51 StringRef Whence = "") {
52 if (Error.category() == instrprof_category()) {
53 instrprof_error instrError = static_cast<instrprof_error>(Error.value());
54 if (instrError == instrprof_error::unrecognized_format) {
55 // Hint for common error of forgetting -sample for sample profiles.
56 exitWithError(Error.message(), Whence,
57 "Perhaps you forgot to use the -sample option?");
60 exitWithError(Error.message(), Whence);
64 enum ProfileKinds { instr, sample };
67 static void handleMergeWriterError(std::error_code &Error,
68 StringRef WhenceFile = "",
69 StringRef WhenceFunction = "",
70 bool ShowHint = true) {
71 if (!WhenceFile.empty())
72 errs() << WhenceFile << ": ";
73 if (!WhenceFunction.empty())
74 errs() << WhenceFunction << ": ";
75 errs() << Error.message() << "\n";
79 if (Error.category() == instrprof_category()) {
80 instrprof_error instrError = static_cast<instrprof_error>(Error.value());
82 case instrprof_error::hash_mismatch:
83 case instrprof_error::count_mismatch:
84 case instrprof_error::value_site_count_mismatch:
85 Hint = "Make sure that all profile data to be merged is generated "
86 "from the same binary.";
94 errs() << Hint << "\n";
104 WeightedFile(StringRef F, uint64_t W) : Filename{F}, Weight{W} {}
106 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
108 static void mergeInstrProfile(const WeightedFileVector &Inputs,
109 StringRef OutputFilename,
110 ProfileFormat OutputFormat) {
111 if (OutputFilename.compare("-") == 0)
112 exitWithError("Cannot write indexed profdata format to stdout.");
114 if (OutputFormat != PF_Binary && OutputFormat != PF_Text)
115 exitWithError("Unknown format is specified.");
118 raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
120 exitWithErrorCode(EC, OutputFilename);
122 InstrProfWriter Writer;
123 SmallSet<std::error_code, 4> WriterErrorCodes;
124 for (const auto &Input : Inputs) {
125 auto ReaderOrErr = InstrProfReader::create(Input.Filename);
126 if (std::error_code ec = ReaderOrErr.getError())
127 exitWithErrorCode(ec, Input.Filename);
129 auto Reader = std::move(ReaderOrErr.get());
130 for (auto &I : *Reader) {
131 if (std::error_code EC = Writer.addRecord(std::move(I), Input.Weight)) {
132 // Only show hint the first time an error occurs.
133 bool firstTime = WriterErrorCodes.insert(EC).second;
134 handleMergeWriterError(EC, Input.Filename, I.Name, firstTime);
137 if (Reader->hasError())
138 exitWithErrorCode(Reader->getError(), Input.Filename);
140 if (OutputFormat == PF_Text)
141 Writer.writeText(Output);
143 Writer.write(Output);
146 static sampleprof::SampleProfileFormat FormatMap[] = {
147 sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Binary,
148 sampleprof::SPF_GCC};
150 static void mergeSampleProfile(const WeightedFileVector &Inputs,
151 StringRef OutputFilename,
152 ProfileFormat OutputFormat) {
153 using namespace sampleprof;
155 SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
156 if (std::error_code EC = WriterOrErr.getError())
157 exitWithErrorCode(EC, OutputFilename);
159 auto Writer = std::move(WriterOrErr.get());
160 StringMap<FunctionSamples> ProfileMap;
161 SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
162 for (const auto &Input : Inputs) {
164 SampleProfileReader::create(Input.Filename, getGlobalContext());
165 if (std::error_code EC = ReaderOrErr.getError())
166 exitWithErrorCode(EC, Input.Filename);
168 // We need to keep the readers around until after all the files are
169 // read so that we do not lose the function names stored in each
170 // reader's memory. The function names are needed to write out the
171 // merged profile map.
172 Readers.push_back(std::move(ReaderOrErr.get()));
173 const auto Reader = Readers.back().get();
174 if (std::error_code EC = Reader->read())
175 exitWithErrorCode(EC, Input.Filename);
177 StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
178 for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
181 StringRef FName = I->first();
182 FunctionSamples &Samples = I->second;
183 ProfileMap[FName].merge(Samples, Input.Weight);
186 Writer->write(ProfileMap);
189 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
190 StringRef WeightStr, FileName;
191 std::tie(WeightStr, FileName) = WeightedFilename.split(',');
194 if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
195 exitWithError("Input weight must be a positive integer.");
197 if (!sys::fs::exists(FileName))
198 exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
201 return WeightedFile(FileName, Weight);
204 static int merge_main(int argc, const char *argv[]) {
205 cl::list<std::string> InputFilenames(cl::Positional,
206 cl::desc("<filename...>"));
207 cl::list<std::string> WeightedInputFilenames("weighted-input",
208 cl::desc("<weight>,<filename>"));
209 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
210 cl::init("-"), cl::Required,
211 cl::desc("Output file"));
212 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
213 cl::aliasopt(OutputFilename));
214 cl::opt<ProfileKinds> ProfileKind(
215 cl::desc("Profile kind:"), cl::init(instr),
216 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
217 clEnumVal(sample, "Sample profile"), clEnumValEnd));
219 cl::opt<ProfileFormat> OutputFormat(
220 cl::desc("Format of output profile"), cl::init(PF_Binary),
221 cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
222 clEnumValN(PF_Text, "text", "Text encoding"),
223 clEnumValN(PF_GCC, "gcc",
224 "GCC encoding (only meaningful for -sample)"),
227 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
229 if (InputFilenames.empty() && WeightedInputFilenames.empty())
230 exitWithError("No input files specified. See " +
231 sys::path::filename(argv[0]) + " -help");
233 WeightedFileVector WeightedInputs;
234 for (StringRef Filename : InputFilenames)
235 WeightedInputs.push_back(WeightedFile(Filename, 1));
236 for (StringRef WeightedFilename : WeightedInputFilenames)
237 WeightedInputs.push_back(parseWeightedFile(WeightedFilename));
239 if (ProfileKind == instr)
240 mergeInstrProfile(WeightedInputs, OutputFilename, OutputFormat);
242 mergeSampleProfile(WeightedInputs, OutputFilename, OutputFormat);
247 static int showInstrProfile(std::string Filename, bool ShowCounts,
248 bool ShowIndirectCallTargets, bool ShowAllFunctions,
249 std::string ShowFunction, bool TextFormat,
250 raw_fd_ostream &OS) {
251 auto ReaderOrErr = InstrProfReader::create(Filename);
252 if (std::error_code EC = ReaderOrErr.getError())
253 exitWithErrorCode(EC, Filename);
255 auto Reader = std::move(ReaderOrErr.get());
256 uint64_t MaxFunctionCount = 0, MaxBlockCount = 0;
257 size_t ShownFunctions = 0, TotalFunctions = 0;
258 for (const auto &Func : *Reader) {
260 ShowAllFunctions || (!ShowFunction.empty() &&
261 Func.Name.find(ShowFunction) != Func.Name.npos);
263 bool doTextFormatDump = (Show && ShowCounts && TextFormat);
265 if (doTextFormatDump) {
266 InstrProfWriter::writeRecordInText(Func, OS);
271 assert(Func.Counts.size() > 0 && "function missing entry counter");
272 if (Func.Counts[0] > MaxFunctionCount)
273 MaxFunctionCount = Func.Counts[0];
275 for (size_t I = 1, E = Func.Counts.size(); I < E; ++I) {
276 if (Func.Counts[I] > MaxBlockCount)
277 MaxBlockCount = Func.Counts[I];
287 OS << " " << Func.Name << ":\n"
288 << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
289 << " Counters: " << Func.Counts.size() << "\n"
290 << " Function count: " << Func.Counts[0] << "\n";
292 if (ShowIndirectCallTargets)
293 OS << " Indirect Call Site Count: "
294 << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
297 OS << " Block counts: [";
298 for (size_t I = 1, E = Func.Counts.size(); I < E; ++I) {
299 OS << (I == 1 ? "" : ", ") << Func.Counts[I];
304 if (ShowIndirectCallTargets) {
305 uint32_t NS = Func.getNumValueSites(IPVK_IndirectCallTarget);
306 OS << " Indirect Target Results: \n";
307 for (size_t I = 0; I < NS; ++I) {
308 uint32_t NV = Func.getNumValueDataForSite(IPVK_IndirectCallTarget, I);
309 std::unique_ptr<InstrProfValueData[]> VD =
310 Func.getValueForSite(IPVK_IndirectCallTarget, I);
311 for (uint32_t V = 0; V < NV; V++) {
312 OS << "\t[ " << I << ", ";
313 OS << (const char *)VD[V].Value << ", " << VD[V].Count << " ]\n";
320 if (Reader->hasError())
321 exitWithErrorCode(Reader->getError(), Filename);
323 if (ShowCounts && TextFormat)
326 if (ShowAllFunctions || !ShowFunction.empty())
327 OS << "Functions shown: " << ShownFunctions << "\n";
328 OS << "Total functions: " << TotalFunctions << "\n";
329 OS << "Maximum function count: " << MaxFunctionCount << "\n";
330 OS << "Maximum internal block count: " << MaxBlockCount << "\n";
334 static int showSampleProfile(std::string Filename, bool ShowCounts,
335 bool ShowAllFunctions, std::string ShowFunction,
336 raw_fd_ostream &OS) {
337 using namespace sampleprof;
338 auto ReaderOrErr = SampleProfileReader::create(Filename, getGlobalContext());
339 if (std::error_code EC = ReaderOrErr.getError())
340 exitWithErrorCode(EC, Filename);
342 auto Reader = std::move(ReaderOrErr.get());
343 if (std::error_code EC = Reader->read())
344 exitWithErrorCode(EC, Filename);
346 if (ShowAllFunctions || ShowFunction.empty())
349 Reader->dumpFunctionProfile(ShowFunction, OS);
354 static int show_main(int argc, const char *argv[]) {
355 cl::opt<std::string> Filename(cl::Positional, cl::Required,
356 cl::desc("<profdata-file>"));
358 cl::opt<bool> ShowCounts("counts", cl::init(false),
359 cl::desc("Show counter values for shown functions"));
360 cl::opt<bool> TextFormat(
361 "text", cl::init(false),
362 cl::desc("Show instr profile data in text dump format"));
363 cl::opt<bool> ShowIndirectCallTargets(
364 "ic-targets", cl::init(false),
365 cl::desc("Show indirect call site target values for shown functions"));
366 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
367 cl::desc("Details for every function"));
368 cl::opt<std::string> ShowFunction("function",
369 cl::desc("Details for matching functions"));
371 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
372 cl::init("-"), cl::desc("Output file"));
373 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
374 cl::aliasopt(OutputFilename));
375 cl::opt<ProfileKinds> ProfileKind(
376 cl::desc("Profile kind:"), cl::init(instr),
377 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
378 clEnumVal(sample, "Sample profile"), clEnumValEnd));
380 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
382 if (OutputFilename.empty())
383 OutputFilename = "-";
386 raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
388 exitWithErrorCode(EC, OutputFilename);
390 if (ShowAllFunctions && !ShowFunction.empty())
391 errs() << "warning: -function argument ignored: showing all functions\n";
393 if (ProfileKind == instr)
394 return showInstrProfile(Filename, ShowCounts, ShowIndirectCallTargets,
395 ShowAllFunctions, ShowFunction, TextFormat, OS);
397 return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
401 int main(int argc, const char *argv[]) {
402 // Print a stack trace if we signal out.
403 sys::PrintStackTraceOnErrorSignal();
404 PrettyStackTraceProgram X(argc, argv);
405 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
407 StringRef ProgName(sys::path::filename(argv[0]));
409 int (*func)(int, const char *[]) = nullptr;
411 if (strcmp(argv[1], "merge") == 0)
413 else if (strcmp(argv[1], "show") == 0)
417 std::string Invocation(ProgName.str() + " " + argv[1]);
418 argv[1] = Invocation.c_str();
419 return func(argc - 1, argv + 1);
422 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
423 strcmp(argv[1], "--help") == 0) {
425 errs() << "OVERVIEW: LLVM profile data tools\n\n"
426 << "USAGE: " << ProgName << " <command> [args...]\n"
427 << "USAGE: " << ProgName << " <command> -help\n\n"
428 << "Available commands: merge, show\n";
434 errs() << ProgName << ": No command specified!\n";
436 errs() << ProgName << ": Unknown command!\n";
438 errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";