9ce0485fb1375de6a007ecd052c06f01e4d359c0
[oota-llvm.git] / tools / llvm-profdata / llvm-profdata.cpp
1 //===- 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
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/ProfileData/InstrProfReader.h"
17 #include "llvm/ProfileData/InstrProfWriter.h"
18 #include "llvm/ProfileData/SampleProfReader.h"
19 #include "llvm/ProfileData/SampleProfWriter.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/PrettyStackTrace.h"
27 #include "llvm/Support/Signals.h"
28 #include "llvm/Support/raw_ostream.h"
29
30 #include <set>
31
32 using namespace llvm;
33
34 static void exitWithError(const Twine &Message,
35                           StringRef Whence = "",
36                           StringRef Hint = "") {
37   errs() << "error: ";
38   if (!Whence.empty())
39     errs() << Whence << ": ";
40   errs() << Message << "\n";
41   if (!Hint.empty())
42     errs() << Hint << "\n";
43   ::exit(1);
44 }
45
46 static void exitWithErrorCode(const std::error_code &Error,
47                               StringRef Whence = "") {
48   if (Error.category() == instrprof_category()) {
49     instrprof_error instrError = static_cast<instrprof_error>(Error.value());
50     if (instrError == instrprof_error::unrecognized_format) {
51       // Hint for common error of forgetting -sample for sample profiles.
52       exitWithError(Error.message(), Whence,
53                     "Perhaps you forgot to use the -sample option?");
54     }
55   }
56   exitWithError(Error.message(), Whence);
57 }
58
59 namespace {
60     enum ProfileKinds { instr, sample };
61 }
62
63 static void handleMergeWriterError(std::error_code &Error,
64                                    StringRef WhenceFile = "",
65                                    StringRef WhenceFunction = "",
66                                    bool ShowHint = true)
67 {
68   if (!WhenceFile.empty())
69     errs() << WhenceFile << ": ";
70   if (!WhenceFunction.empty())
71     errs() << WhenceFunction << ": ";
72   errs() << Error.message() << "\n";
73
74   if (ShowHint) {
75     StringRef Hint = "";
76     if (Error.category() == instrprof_category()) {
77       instrprof_error instrError = static_cast<instrprof_error>(Error.value());
78       switch (instrError) {
79       case instrprof_error::hash_mismatch:
80       case instrprof_error::count_mismatch:
81       case instrprof_error::value_site_count_mismatch:
82         Hint = "Make sure that all profile data to be merged is generated " \
83                "from the same binary.";
84         break;
85       default:
86         break;
87       }
88     }
89
90     if (!Hint.empty())
91       errs() << Hint << "\n";
92   }
93 }
94
95 static void mergeInstrProfile(const cl::list<std::string> &Inputs,
96                               StringRef OutputFilename) {
97   if (OutputFilename.compare("-") == 0)
98     exitWithError("Cannot write indexed profdata format to stdout.");
99
100   std::error_code EC;
101   raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
102   if (EC)
103     exitWithErrorCode(EC, OutputFilename);
104
105   InstrProfWriter Writer;
106   std::set<std::error_code> WriterErrorCodes;
107   for (const auto &Filename : Inputs) {
108     auto ReaderOrErr = InstrProfReader::create(Filename);
109     if (std::error_code ec = ReaderOrErr.getError())
110       exitWithErrorCode(ec, Filename);
111
112     auto Reader = std::move(ReaderOrErr.get());
113     for (auto &I : *Reader) {
114       if (std::error_code EC = Writer.addRecord(std::move(I))) {
115         // Only show hint the first time an error occurs.
116         bool firstTime = WriterErrorCodes.insert(EC).second;
117         handleMergeWriterError(EC, Filename, I.Name, firstTime);
118       }
119     }
120     if (Reader->hasError())
121       exitWithErrorCode(Reader->getError(), Filename);
122   }
123   Writer.write(Output);
124 }
125
126 static void mergeSampleProfile(const cl::list<std::string> &Inputs,
127                                StringRef OutputFilename,
128                                sampleprof::SampleProfileFormat OutputFormat) {
129   using namespace sampleprof;
130   auto WriterOrErr = SampleProfileWriter::create(OutputFilename, OutputFormat);
131   if (std::error_code EC = WriterOrErr.getError())
132     exitWithErrorCode(EC, OutputFilename);
133
134   auto Writer = std::move(WriterOrErr.get());
135   StringMap<FunctionSamples> ProfileMap;
136   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
137   for (const auto &Filename : Inputs) {
138     auto ReaderOrErr =
139         SampleProfileReader::create(Filename, getGlobalContext());
140     if (std::error_code EC = ReaderOrErr.getError())
141       exitWithErrorCode(EC, Filename);
142
143     // We need to keep the readers around until after all the files are
144     // read so that we do not lose the function names stored in each
145     // reader's memory. The function names are needed to write out the
146     // merged profile map.
147     Readers.push_back(std::move(ReaderOrErr.get()));
148     const auto Reader = Readers.back().get();
149     if (std::error_code EC = Reader->read())
150       exitWithErrorCode(EC, Filename);
151
152     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
153     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
154                                               E = Profiles.end();
155          I != E; ++I) {
156       StringRef FName = I->first();
157       FunctionSamples &Samples = I->second;
158       ProfileMap[FName].merge(Samples);
159     }
160   }
161   Writer->write(ProfileMap);
162 }
163
164 static int merge_main(int argc, const char *argv[]) {
165   cl::list<std::string> Inputs(cl::Positional, cl::Required, cl::OneOrMore,
166                                cl::desc("<filenames...>"));
167
168   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
169                                       cl::init("-"), cl::Required,
170                                       cl::desc("Output file"));
171   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
172                             cl::aliasopt(OutputFilename));
173   cl::opt<ProfileKinds> ProfileKind(
174       cl::desc("Profile kind:"), cl::init(instr),
175       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
176                  clEnumVal(sample, "Sample profile"), clEnumValEnd));
177
178   cl::opt<sampleprof::SampleProfileFormat> OutputFormat(
179       cl::desc("Format of output profile (only meaningful with --sample)"),
180       cl::init(sampleprof::SPF_Binary),
181       cl::values(clEnumValN(sampleprof::SPF_Binary, "binary",
182                             "Binary encoding (default)"),
183                  clEnumValN(sampleprof::SPF_Text, "text", "Text encoding"),
184                  clEnumValN(sampleprof::SPF_GCC, "gcc", "GCC encoding"),
185                  clEnumValEnd));
186
187   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
188
189   if (ProfileKind == instr)
190     mergeInstrProfile(Inputs, OutputFilename);
191   else
192     mergeSampleProfile(Inputs, OutputFilename, OutputFormat);
193
194   return 0;
195 }
196
197 static int showInstrProfile(std::string Filename, bool ShowCounts,
198                             bool ShowIndirectCallTargets, bool ShowAllFunctions,
199                             std::string ShowFunction, raw_fd_ostream &OS) {
200   auto ReaderOrErr = InstrProfReader::create(Filename);
201   if (std::error_code EC = ReaderOrErr.getError())
202     exitWithErrorCode(EC, Filename);
203
204   auto Reader = std::move(ReaderOrErr.get());
205   uint64_t MaxFunctionCount = 0, MaxBlockCount = 0;
206   size_t ShownFunctions = 0, TotalFunctions = 0;
207   for (const auto &Func : *Reader) {
208     bool Show =
209         ShowAllFunctions || (!ShowFunction.empty() &&
210                              Func.Name.find(ShowFunction) != Func.Name.npos);
211
212     ++TotalFunctions;
213     assert(Func.Counts.size() > 0 && "function missing entry counter");
214     if (Func.Counts[0] > MaxFunctionCount)
215       MaxFunctionCount = Func.Counts[0];
216
217     if (Show) {
218       if (!ShownFunctions)
219         OS << "Counters:\n";
220       ++ShownFunctions;
221
222       OS << "  " << Func.Name << ":\n"
223          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
224          << "    Counters: " << Func.Counts.size() << "\n"
225          << "    Function count: " << Func.Counts[0] << "\n";
226       if (ShowIndirectCallTargets)
227         OS << "    Indirect Call Site Count: "
228            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
229     }
230
231     if (Show && ShowCounts)
232       OS << "    Block counts: [";
233     for (size_t I = 1, E = Func.Counts.size(); I < E; ++I) {
234       if (Func.Counts[I] > MaxBlockCount)
235         MaxBlockCount = Func.Counts[I];
236       if (Show && ShowCounts)
237         OS << (I == 1 ? "" : ", ") << Func.Counts[I];
238     }
239     if (Show && ShowCounts)
240       OS << "]\n";
241
242     if (Show && ShowIndirectCallTargets) {
243       uint32_t NS = Func.getNumValueSites(IPVK_IndirectCallTarget);
244       OS << "    Indirect Target Results: \n";
245       for (size_t I = 0; I < NS; ++I) {
246         uint32_t NV = Func.getNumValueDataForSite(IPVK_IndirectCallTarget, I);
247         std::unique_ptr<InstrProfValueData[]> VD =
248             Func.getValueForSite(IPVK_IndirectCallTarget, I);
249         for (uint32_t V = 0; V < NV; V++) {
250           OS << "\t[ " << I << ", ";
251           OS << (const char *)VD[V].Value << ", " << VD[V].Count << " ]\n";
252         }
253       }
254     }
255   }
256   if (Reader->hasError())
257     exitWithErrorCode(Reader->getError(), Filename);
258
259   if (ShowAllFunctions || !ShowFunction.empty())
260     OS << "Functions shown: " << ShownFunctions << "\n";
261   OS << "Total functions: " << TotalFunctions << "\n";
262   OS << "Maximum function count: " << MaxFunctionCount << "\n";
263   OS << "Maximum internal block count: " << MaxBlockCount << "\n";
264   return 0;
265 }
266
267 static int showSampleProfile(std::string Filename, bool ShowCounts,
268                              bool ShowAllFunctions, std::string ShowFunction,
269                              raw_fd_ostream &OS) {
270   using namespace sampleprof;
271   auto ReaderOrErr = SampleProfileReader::create(Filename, getGlobalContext());
272   if (std::error_code EC = ReaderOrErr.getError())
273     exitWithErrorCode(EC, Filename);
274
275   auto Reader = std::move(ReaderOrErr.get());
276   if (std::error_code EC = Reader->read())
277     exitWithErrorCode(EC, Filename);
278
279   if (ShowAllFunctions || ShowFunction.empty())
280     Reader->dump(OS);
281   else
282     Reader->dumpFunctionProfile(ShowFunction, OS);
283
284   return 0;
285 }
286
287 static int show_main(int argc, const char *argv[]) {
288   cl::opt<std::string> Filename(cl::Positional, cl::Required,
289                                 cl::desc("<profdata-file>"));
290
291   cl::opt<bool> ShowCounts("counts", cl::init(false),
292                            cl::desc("Show counter values for shown functions"));
293   cl::opt<bool> ShowIndirectCallTargets(
294       "ic-targets", cl::init(false),
295       cl::desc("Show indirect call site target values for shown functions"));
296   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
297                                  cl::desc("Details for every function"));
298   cl::opt<std::string> ShowFunction("function",
299                                     cl::desc("Details for matching functions"));
300
301   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
302                                       cl::init("-"), cl::desc("Output file"));
303   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
304                             cl::aliasopt(OutputFilename));
305   cl::opt<ProfileKinds> ProfileKind(
306       cl::desc("Profile kind:"), cl::init(instr),
307       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
308                  clEnumVal(sample, "Sample profile"), clEnumValEnd));
309
310   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
311
312   if (OutputFilename.empty())
313     OutputFilename = "-";
314
315   std::error_code EC;
316   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
317   if (EC)
318       exitWithErrorCode(EC, OutputFilename);
319
320   if (ShowAllFunctions && !ShowFunction.empty())
321     errs() << "warning: -function argument ignored: showing all functions\n";
322
323   if (ProfileKind == instr)
324     return showInstrProfile(Filename, ShowCounts, ShowIndirectCallTargets,
325                             ShowAllFunctions, ShowFunction, OS);
326   else
327     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
328                              ShowFunction, OS);
329 }
330
331 int main(int argc, const char *argv[]) {
332   // Print a stack trace if we signal out.
333   sys::PrintStackTraceOnErrorSignal();
334   PrettyStackTraceProgram X(argc, argv);
335   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
336
337   StringRef ProgName(sys::path::filename(argv[0]));
338   if (argc > 1) {
339     int (*func)(int, const char *[]) = nullptr;
340
341     if (strcmp(argv[1], "merge") == 0)
342       func = merge_main;
343     else if (strcmp(argv[1], "show") == 0)
344       func = show_main;
345
346     if (func) {
347       std::string Invocation(ProgName.str() + " " + argv[1]);
348       argv[1] = Invocation.c_str();
349       return func(argc - 1, argv + 1);
350     }
351
352     if (strcmp(argv[1], "-h") == 0 ||
353         strcmp(argv[1], "-help") == 0 ||
354         strcmp(argv[1], "--help") == 0) {
355
356       errs() << "OVERVIEW: LLVM profile data tools\n\n"
357              << "USAGE: " << ProgName << " <command> [args...]\n"
358              << "USAGE: " << ProgName << " <command> -help\n\n"
359              << "Available commands: merge, show\n";
360       return 0;
361     }
362   }
363
364   if (argc < 2)
365     errs() << ProgName << ": No command specified!\n";
366   else
367     errs() << ProgName << ": Unknown command!\n";
368
369   errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
370   return 1;
371 }