6c340b89c65c2bc49f921ccffee9a2496d3abe9b
[oota-llvm.git] / tools / llvm-prof / llvm-prof.cpp
1 //===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===//
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 // This tools is meant for use with the various LLVM profiling instrumentation
11 // passes.  It reads in the data file produced by executing an instrumented
12 // program, and outputs a nice report.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/ProfileInfo.h"
19 #include "llvm/Analysis/ProfileInfoLoader.h"
20 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
21 #include "llvm/Bitcode/ReaderWriter.h"
22 #include "llvm/IR/InstrTypes.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/FormattedStream.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/Signals.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Support/system_error.h"
34 #include <algorithm>
35 #include <iomanip>
36 #include <map>
37 #include <set>
38
39 using namespace llvm;
40
41 namespace {
42   cl::opt<std::string>
43   BitcodeFile(cl::Positional, cl::desc("<program bitcode file>"),
44               cl::Required);
45
46   cl::opt<std::string>
47   ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
48                   cl::Optional, cl::init("llvmprof.out"));
49
50   cl::opt<bool>
51   PrintAnnotatedLLVM("annotated-llvm",
52                      cl::desc("Print LLVM code with frequency annotations"));
53   cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"),
54                             cl::aliasopt(PrintAnnotatedLLVM));
55   cl::opt<bool>
56   PrintAllCode("print-all-code",
57                cl::desc("Print annotated code for the entire program"));
58 }
59
60 // PairSecondSort - A sorting predicate to sort by the second element of a pair.
61 template<class T>
62 struct PairSecondSortReverse
63   : public std::binary_function<std::pair<T, double>,
64                                 std::pair<T, double>, bool> {
65   bool operator()(const std::pair<T, double> &LHS,
66                   const std::pair<T, double> &RHS) const {
67     return LHS.second > RHS.second;
68   }
69 };
70
71 static double ignoreMissing(double w) {
72   if (w == ProfileInfo::MissingValue) return 0;
73   return w;
74 }
75
76 namespace {
77   class ProfileAnnotator : public AssemblyAnnotationWriter {
78     ProfileInfo &PI;
79   public:
80     ProfileAnnotator(ProfileInfo &pi) : PI(pi) {}
81
82     virtual void emitFunctionAnnot(const Function *F,
83                                    formatted_raw_ostream &OS) {
84       double w = PI.getExecutionCount(F);
85       if (w != ProfileInfo::MissingValue) {
86         OS << ";;; %" << F->getName() << " called "<<(unsigned)w
87            <<" times.\n;;;\n";
88       }
89     }
90     virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
91                                           formatted_raw_ostream &OS) {
92       double w = PI.getExecutionCount(BB);
93       if (w != ProfileInfo::MissingValue) {
94         if (w != 0) {
95           OS << "\t;;; Basic block executed " << (unsigned)w << " times.\n";
96         } else {
97           OS << "\t;;; Never executed!\n";
98         }
99       }
100     }
101
102     virtual void emitBasicBlockEndAnnot(const BasicBlock *BB,
103                                         formatted_raw_ostream &OS) {
104       // Figure out how many times each successor executed.
105       std::vector<std::pair<ProfileInfo::Edge, double> > SuccCounts;
106
107       const TerminatorInst *TI = BB->getTerminator();
108       for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {
109         BasicBlock* Succ = TI->getSuccessor(s);
110         double w = ignoreMissing(PI.getEdgeWeight(std::make_pair(BB, Succ)));
111         if (w != 0)
112           SuccCounts.push_back(std::make_pair(std::make_pair(BB, Succ), w));
113       }
114       if (!SuccCounts.empty()) {
115         OS << "\t;;; Out-edge counts:";
116         for (unsigned i = 0, e = SuccCounts.size(); i != e; ++i)
117           OS << " [" << (SuccCounts[i]).second << " -> "
118              << (SuccCounts[i]).first.second->getName() << "]";
119         OS << "\n";
120       }
121     }
122   };
123 }
124
125 namespace {
126   /// ProfileInfoPrinterPass - Helper pass to dump the profile information for
127   /// a module.
128   //
129   // FIXME: This should move elsewhere.
130   class ProfileInfoPrinterPass : public ModulePass {
131     ProfileInfoLoader &PIL;
132   public:
133     static char ID; // Class identification, replacement for typeinfo.
134     explicit ProfileInfoPrinterPass(ProfileInfoLoader &_PIL)
135       : ModulePass(ID), PIL(_PIL) {}
136
137     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
138       AU.setPreservesAll();
139       AU.addRequired<ProfileInfo>();
140     }
141
142     bool runOnModule(Module &M);
143   };
144 }
145
146 char ProfileInfoPrinterPass::ID = 0;
147
148 bool ProfileInfoPrinterPass::runOnModule(Module &M) {
149   ProfileInfo &PI = getAnalysis<ProfileInfo>();
150
151   // Output a report. Eventually, there will be multiple reports selectable on
152   // the command line, for now, just keep things simple.
153
154   // Emit the most frequent function table...
155   std::vector<std::pair<Function*, double> > FunctionCounts;
156   std::vector<std::pair<BasicBlock*, double> > Counts;
157   for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
158     if (FI->isDeclaration()) continue;
159     double w = ignoreMissing(PI.getExecutionCount(FI));
160     FunctionCounts.push_back(std::make_pair(FI, w));
161     for (Function::iterator BB = FI->begin(), BBE = FI->end();
162          BB != BBE; ++BB) {
163       double w = ignoreMissing(PI.getExecutionCount(BB));
164       Counts.push_back(std::make_pair(BB, w));
165     }
166   }
167
168   // Sort by the frequency, backwards.
169   sort(FunctionCounts.begin(), FunctionCounts.end(),
170             PairSecondSortReverse<Function*>());
171
172   double TotalExecutions = 0;
173   for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
174     TotalExecutions += FunctionCounts[i].second;
175
176   outs() << "===" << std::string(73, '-') << "===\n"
177          << "LLVM profiling output for execution";
178   if (PIL.getNumExecutions() != 1) outs() << "s";
179   outs() << ":\n";
180
181   for (unsigned i = 0, e = PIL.getNumExecutions(); i != e; ++i) {
182     outs() << "  ";
183     if (e != 1) outs() << i+1 << ". ";
184     outs() << PIL.getExecution(i) << "\n";
185   }
186
187   outs() << "\n===" << std::string(73, '-') << "===\n";
188   outs() << "Function execution frequencies:\n\n";
189
190   // Print out the function frequencies...
191   outs() << " ##   Frequency\n";
192   for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
193     if (FunctionCounts[i].second == 0) {
194       outs() << "\n  NOTE: " << e-i << " function"
195         << (e-i-1 ? "s were" : " was") << " never executed!\n";
196       break;
197     }
198
199     outs() << format("%3d", i+1) << ". "
200            << format("%5.2g", FunctionCounts[i].second) << "/"
201            << format("%g", TotalExecutions) << " "
202            << FunctionCounts[i].first->getName() << "\n";
203   }
204
205   std::set<Function*> FunctionsToPrint;
206
207   TotalExecutions = 0;
208   for (unsigned i = 0, e = Counts.size(); i != e; ++i)
209     TotalExecutions += Counts[i].second;
210
211   // Sort by the frequency, backwards.
212   sort(Counts.begin(), Counts.end(),
213        PairSecondSortReverse<BasicBlock*>());
214
215   outs() << "\n===" << std::string(73, '-') << "===\n";
216   outs() << "Top 20 most frequently executed basic blocks:\n\n";
217
218   // Print out the function frequencies...
219   outs() <<" ##      %% \tFrequency\n";
220   unsigned BlocksToPrint = Counts.size();
221   if (BlocksToPrint > 20) BlocksToPrint = 20;
222   for (unsigned i = 0; i != BlocksToPrint; ++i) {
223     if (Counts[i].second == 0) break;
224     Function *F = Counts[i].first->getParent();
225     outs() << format("%3d", i+1) << ". "
226            << format("%5g", Counts[i].second/(double)TotalExecutions*100)<<"% "
227            << format("%5.0f", Counts[i].second) << "/"
228            << format("%g", TotalExecutions) << "\t"
229            << F->getName() << "() - "
230            << Counts[i].first->getName() << "\n";
231     FunctionsToPrint.insert(F);
232   }
233
234   if (PrintAnnotatedLLVM || PrintAllCode) {
235     outs() << "\n===" << std::string(73, '-') << "===\n";
236     outs() << "Annotated LLVM code for the module:\n\n";
237
238     ProfileAnnotator PA(PI);
239
240     if (FunctionsToPrint.empty() || PrintAllCode)
241       M.print(outs(), &PA);
242     else
243       // Print just a subset of the functions.
244       for (std::set<Function*>::iterator I = FunctionsToPrint.begin(),
245              E = FunctionsToPrint.end(); I != E; ++I)
246         (*I)->print(outs(), &PA);
247   }
248
249   return false;
250 }
251
252 int main(int argc, char **argv) {
253   // Print a stack trace if we signal out.
254   sys::PrintStackTraceOnErrorSignal();
255   PrettyStackTraceProgram X(argc, argv);
256
257   LLVMContext &Context = getGlobalContext();
258   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
259
260   cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");
261
262   // Read in the bitcode file...
263   std::string ErrorMessage;
264   OwningPtr<MemoryBuffer> Buffer;
265   error_code ec;
266   Module *M = 0;
267   if (!(ec = MemoryBuffer::getFileOrSTDIN(BitcodeFile, Buffer))) {
268     M = ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage);
269   } else
270     ErrorMessage = ec.message();
271   if (M == 0) {
272     errs() << argv[0] << ": " << BitcodeFile << ": "
273       << ErrorMessage << "\n";
274     return 1;
275   }
276
277   // Read the profiling information. This is redundant since we load it again
278   // using the standard profile info provider pass, but for now this gives us
279   // access to additional information not exposed via the ProfileInfo
280   // interface.
281   ProfileInfoLoader PIL(argv[0], ProfileDataFile);
282
283   // Run the printer pass.
284   PassManager PassMgr;
285   PassMgr.add(createProfileLoaderPass(ProfileDataFile));
286   PassMgr.add(new ProfileInfoPrinterPass(PIL));
287   PassMgr.run(*M);
288
289   return 0;
290 }