Re-apply r249644: Handle inline stacks in gcov-encoded sample profiles.
[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 using namespace llvm;
31
32 static void exitWithError(const Twine &Message, StringRef Whence = "") {
33   errs() << "error: ";
34   if (!Whence.empty())
35     errs() << Whence << ": ";
36   errs() << Message << "\n";
37   ::exit(1);
38 }
39
40 namespace {
41 enum ProfileKinds { instr, sample };
42 }
43
44 static void mergeInstrProfile(const cl::list<std::string> &Inputs,
45                               StringRef OutputFilename) {
46   if (OutputFilename.compare("-") == 0)
47     exitWithError("Cannot write indexed profdata format to stdout.");
48
49   std::error_code EC;
50   raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
51   if (EC)
52     exitWithError(EC.message(), OutputFilename);
53
54   InstrProfWriter Writer;
55   for (const auto &Filename : Inputs) {
56     auto ReaderOrErr = InstrProfReader::create(Filename);
57     if (std::error_code ec = ReaderOrErr.getError())
58       exitWithError(ec.message(), Filename);
59
60     auto Reader = std::move(ReaderOrErr.get());
61     for (auto &I : *Reader)
62       if (std::error_code EC = Writer.addRecord(std::move(I)))
63         errs() << Filename << ": " << I.Name << ": " << EC.message() << "\n";
64     if (Reader->hasError())
65       exitWithError(Reader->getError().message(), Filename);
66   }
67   Writer.write(Output);
68 }
69
70 static void mergeSampleProfile(const cl::list<std::string> &Inputs,
71                                StringRef OutputFilename,
72                                sampleprof::SampleProfileFormat OutputFormat) {
73   using namespace sampleprof;
74   auto WriterOrErr = SampleProfileWriter::create(OutputFilename, OutputFormat);
75   if (std::error_code EC = WriterOrErr.getError())
76     exitWithError(EC.message(), OutputFilename);
77
78   auto Writer = std::move(WriterOrErr.get());
79   StringMap<FunctionSamples> ProfileMap;
80   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
81   for (const auto &Filename : Inputs) {
82     auto ReaderOrErr =
83         SampleProfileReader::create(Filename, getGlobalContext());
84     if (std::error_code EC = ReaderOrErr.getError())
85       exitWithError(EC.message(), Filename);
86
87     // We need to keep the readers around until after all the files are
88     // read so that we do not lose the function names stored in each
89     // reader's memory. The function names are needed to write out the
90     // merged profile map.
91     Readers.push_back(std::move(ReaderOrErr.get()));
92     const auto Reader = Readers.back().get();
93     if (std::error_code EC = Reader->read())
94       exitWithError(EC.message(), Filename);
95
96     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
97     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
98                                               E = Profiles.end();
99          I != E; ++I) {
100       StringRef FName = I->first();
101       FunctionSamples &Samples = I->second;
102       ProfileMap[FName].merge(Samples);
103     }
104   }
105   Writer->write(ProfileMap);
106 }
107
108 static int merge_main(int argc, const char *argv[]) {
109   cl::list<std::string> Inputs(cl::Positional, cl::Required, cl::OneOrMore,
110                                cl::desc("<filenames...>"));
111
112   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
113                                       cl::init("-"), cl::Required,
114                                       cl::desc("Output file"));
115   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
116                             cl::aliasopt(OutputFilename));
117   cl::opt<ProfileKinds> ProfileKind(
118       cl::desc("Profile kind:"), cl::init(instr),
119       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
120                  clEnumVal(sample, "Sample profile"), clEnumValEnd));
121
122   cl::opt<sampleprof::SampleProfileFormat> OutputFormat(
123       cl::desc("Format of output profile (only meaningful with --sample)"),
124       cl::init(sampleprof::SPF_Binary),
125       cl::values(clEnumValN(sampleprof::SPF_Binary, "binary",
126                             "Binary encoding (default)"),
127                  clEnumValN(sampleprof::SPF_Text, "text", "Text encoding"),
128                  clEnumValN(sampleprof::SPF_GCC, "gcc", "GCC encoding"),
129                  clEnumValEnd));
130
131   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
132
133   if (ProfileKind == instr)
134     mergeInstrProfile(Inputs, OutputFilename);
135   else
136     mergeSampleProfile(Inputs, OutputFilename, OutputFormat);
137
138   return 0;
139 }
140
141 static int showInstrProfile(std::string Filename, bool ShowCounts,
142                             bool ShowIndirectCallTargets, bool ShowAllFunctions,
143                             std::string ShowFunction, raw_fd_ostream &OS) {
144   auto ReaderOrErr = InstrProfReader::create(Filename);
145   if (std::error_code EC = ReaderOrErr.getError())
146     exitWithError(EC.message(), Filename);
147
148   auto Reader = std::move(ReaderOrErr.get());
149   uint64_t MaxFunctionCount = 0, MaxBlockCount = 0;
150   size_t ShownFunctions = 0, TotalFunctions = 0;
151   for (const auto &Func : *Reader) {
152     bool Show =
153         ShowAllFunctions || (!ShowFunction.empty() &&
154                              Func.Name.find(ShowFunction) != Func.Name.npos);
155
156     ++TotalFunctions;
157     assert(Func.Counts.size() > 0 && "function missing entry counter");
158     if (Func.Counts[0] > MaxFunctionCount)
159       MaxFunctionCount = Func.Counts[0];
160
161     if (Show) {
162       if (!ShownFunctions)
163         OS << "Counters:\n";
164       ++ShownFunctions;
165
166       OS << "  " << Func.Name << ":\n"
167          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
168          << "    Counters: " << Func.Counts.size() << "\n"
169          << "    Function count: " << Func.Counts[0] << "\n";
170       if (ShowIndirectCallTargets)
171         OS << "    Indirect Call Site Count: " << Func.IndirectCallSites.size()
172            << "\n";
173     }
174
175     if (Show && ShowCounts)
176       OS << "    Block counts: [";
177     for (size_t I = 1, E = Func.Counts.size(); I < E; ++I) {
178       if (Func.Counts[I] > MaxBlockCount)
179         MaxBlockCount = Func.Counts[I];
180       if (Show && ShowCounts)
181         OS << (I == 1 ? "" : ", ") << Func.Counts[I];
182     }
183     if (Show && ShowCounts)
184       OS << "]\n";
185
186     if (Show && ShowIndirectCallTargets) {
187       OS << "    Indirect Target Results: \n";
188       for (size_t I = 0, E = Func.IndirectCallSites.size(); I < E; ++I) {
189         for (auto V : Func.IndirectCallSites[I].ValueData) {
190           OS << "\t[ " << I << ", ";
191           OS << (const char *)V.first << ", " << V.second << " ]\n";
192         }
193       }
194     }
195   }
196   if (Reader->hasError())
197     exitWithError(Reader->getError().message(), Filename);
198
199   if (ShowAllFunctions || !ShowFunction.empty())
200     OS << "Functions shown: " << ShownFunctions << "\n";
201   OS << "Total functions: " << TotalFunctions << "\n";
202   OS << "Maximum function count: " << MaxFunctionCount << "\n";
203   OS << "Maximum internal block count: " << MaxBlockCount << "\n";
204   return 0;
205 }
206
207 static int showSampleProfile(std::string Filename, bool ShowCounts,
208                              bool ShowAllFunctions, std::string ShowFunction,
209                              raw_fd_ostream &OS) {
210   using namespace sampleprof;
211   auto ReaderOrErr = SampleProfileReader::create(Filename, getGlobalContext());
212   if (std::error_code EC = ReaderOrErr.getError())
213     exitWithError(EC.message(), Filename);
214
215   auto Reader = std::move(ReaderOrErr.get());
216   if (std::error_code EC = Reader->read())
217     exitWithError(EC.message(), Filename);
218
219   if (ShowAllFunctions || ShowFunction.empty())
220     Reader->dump(OS);
221   else
222     Reader->dumpFunctionProfile(ShowFunction, OS);
223
224   return 0;
225 }
226
227 static int show_main(int argc, const char *argv[]) {
228   cl::opt<std::string> Filename(cl::Positional, cl::Required,
229                                 cl::desc("<profdata-file>"));
230
231   cl::opt<bool> ShowCounts("counts", cl::init(false),
232                            cl::desc("Show counter values for shown functions"));
233   cl::opt<bool> ShowIndirectCallTargets(
234       "ic-targets", cl::init(false),
235       cl::desc("Show indirect call site target values for shown functions"));
236   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
237                                  cl::desc("Details for every function"));
238   cl::opt<std::string> ShowFunction("function",
239                                     cl::desc("Details for matching functions"));
240
241   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
242                                       cl::init("-"), cl::desc("Output file"));
243   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
244                             cl::aliasopt(OutputFilename));
245   cl::opt<ProfileKinds> ProfileKind(
246       cl::desc("Profile kind:"), cl::init(instr),
247       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
248                  clEnumVal(sample, "Sample profile"), clEnumValEnd));
249
250   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
251
252   if (OutputFilename.empty())
253     OutputFilename = "-";
254
255   std::error_code EC;
256   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
257   if (EC)
258     exitWithError(EC.message(), OutputFilename);
259
260   if (ShowAllFunctions && !ShowFunction.empty())
261     errs() << "warning: -function argument ignored: showing all functions\n";
262
263   if (ProfileKind == instr)
264     return showInstrProfile(Filename, ShowCounts, ShowIndirectCallTargets,
265                             ShowAllFunctions, ShowFunction, OS);
266   else
267     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
268                              ShowFunction, OS);
269 }
270
271 int main(int argc, const char *argv[]) {
272   // Print a stack trace if we signal out.
273   sys::PrintStackTraceOnErrorSignal();
274   PrettyStackTraceProgram X(argc, argv);
275   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
276
277   StringRef ProgName(sys::path::filename(argv[0]));
278   if (argc > 1) {
279     int (*func)(int, const char *[]) = nullptr;
280
281     if (strcmp(argv[1], "merge") == 0)
282       func = merge_main;
283     else if (strcmp(argv[1], "show") == 0)
284       func = show_main;
285
286     if (func) {
287       std::string Invocation(ProgName.str() + " " + argv[1]);
288       argv[1] = Invocation.c_str();
289       return func(argc - 1, argv + 1);
290     }
291
292     if (strcmp(argv[1], "-h") == 0 ||
293         strcmp(argv[1], "-help") == 0 ||
294         strcmp(argv[1], "--help") == 0) {
295
296       errs() << "OVERVIEW: LLVM profile data tools\n\n"
297              << "USAGE: " << ProgName << " <command> [args...]\n"
298              << "USAGE: " << ProgName << " <command> -help\n\n"
299              << "Available commands: merge, show\n";
300       return 0;
301     }
302   }
303
304   if (argc < 2)
305     errs() << ProgName << ": No command specified!\n";
306   else
307     errs() << ProgName << ": Unknown command!\n";
308
309   errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
310   return 1;
311 }