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