Changed std::cout to outs(), retaining formating.
[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/InstrTypes.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Assembly/AsmAnnotationWriter.h"
21 #include "llvm/Analysis/ProfileInfo.h"
22 #include "llvm/Analysis/ProfileInfoLoader.h"
23 #include "llvm/Analysis/Passes.h"
24 #include "llvm/Bitcode/ReaderWriter.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/System/Signals.h"
32 #include <algorithm>
33 #include <iostream>
34 #include <iomanip>
35 #include <map>
36 #include <set>
37
38 using namespace llvm;
39
40 namespace {
41   cl::opt<std::string>
42   BitcodeFile(cl::Positional, cl::desc("<program bitcode file>"),
43               cl::Required);
44
45   cl::opt<std::string>
46   ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
47                   cl::Optional, cl::init("llvmprof.out"));
48
49   cl::opt<bool>
50   PrintAnnotatedLLVM("annotated-llvm",
51                      cl::desc("Print LLVM code with frequency annotations"));
52   cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"),
53                             cl::aliasopt(PrintAnnotatedLLVM));
54   cl::opt<bool>
55   PrintAllCode("print-all-code",
56                cl::desc("Print annotated code for the entire program"));
57 }
58
59 // PairSecondSort - A sorting predicate to sort by the second element of a pair.
60 template<class T>
61 struct PairSecondSortReverse
62   : public std::binary_function<std::pair<T, double>,
63                                 std::pair<T, double>, bool> {
64   bool operator()(const std::pair<T, double> &LHS,
65                   const std::pair<T, double> &RHS) const {
66     return LHS.second > RHS.second;
67   }
68 };
69
70 static double ignoreMissing(double w) {
71   if (w == ProfileInfo::MissingValue) return 0;
72   return w;
73 }
74
75 namespace {
76   class ProfileAnnotator : public AssemblyAnnotationWriter {
77     ProfileInfo &PI;
78   public:
79     ProfileAnnotator(ProfileInfo& pi) : PI(pi) {}
80
81     virtual void emitFunctionAnnot(const Function *F, raw_ostream &OS) {
82       double w = PI.getExecutionCount(F);
83       if (w != ProfileInfo::MissingValue) {
84         OS << ";;; %" << F->getName() << " called "<<(unsigned)w
85            <<" times.\n;;;\n";
86       }
87     }
88     virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
89                                           raw_ostream &OS) {
90       double w = PI.getExecutionCount(BB);
91       if (w != ProfileInfo::MissingValue) {
92         if (w != 0) {
93           OS << "\t;;; Basic block executed " << (unsigned)w << " times.\n";
94         } else {
95           OS << "\t;;; Never executed!\n";
96         }
97       }
98     }
99
100     virtual void emitBasicBlockEndAnnot(const BasicBlock *BB, raw_ostream &OS) {
101       // Figure out how many times each successor executed.
102       std::vector<std::pair<ProfileInfo::Edge, double> > SuccCounts;
103
104       const TerminatorInst *TI = BB->getTerminator();
105       for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {
106         BasicBlock* Succ = TI->getSuccessor(s);
107         double w = ignoreMissing(PI.getEdgeWeight(std::make_pair(BB, Succ)));
108         if (w != 0)
109           SuccCounts.push_back(std::make_pair(std::make_pair(BB, Succ), w));
110       }
111       if (!SuccCounts.empty()) {
112         OS << "\t;;; Out-edge counts:";
113         for (unsigned i = 0, e = SuccCounts.size(); i != e; ++i)
114           OS << " [" << (SuccCounts[i]).second << " -> "
115              << (SuccCounts[i]).first.second->getName() << "]";
116         OS << "\n";
117       }
118     }
119   };
120 }
121
122 namespace {
123   /// ProfileInfoPrinterPass - Helper pass to dump the profile information for
124   /// a module.
125   //
126   // FIXME: This should move elsewhere.
127   class ProfileInfoPrinterPass : public ModulePass {
128     ProfileInfoLoader &PIL;
129   public:
130     static char ID; // Class identification, replacement for typeinfo.
131     explicit ProfileInfoPrinterPass(ProfileInfoLoader &_PIL) 
132       : ModulePass(&ID), PIL(_PIL) {}
133
134     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
135       AU.setPreservesAll();
136       AU.addRequired<ProfileInfo>();
137     }
138
139     bool runOnModule(Module &M);
140   };
141 }
142
143 char ProfileInfoPrinterPass::ID = 0;
144
145 bool ProfileInfoPrinterPass::runOnModule(Module &M) {
146   ProfileInfo &PI = getAnalysis<ProfileInfo>();
147   std::map<const Function  *, unsigned> FuncFreqs;
148   std::map<const BasicBlock*, unsigned> BlockFreqs;
149   std::map<ProfileInfo::Edge, unsigned> EdgeFreqs;
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->getNameStr() << "\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->getNameStr() << "() - "
230        << Counts[i].first->getNameStr() << "\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   try {
260     cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");
261
262     // Read in the bitcode file...
263     std::string ErrorMessage;
264     Module *M = 0;
265     if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BitcodeFile,
266                                                             &ErrorMessage)) {
267       M = ParseBitcodeFile(Buffer, Context, &ErrorMessage);
268       delete Buffer;
269     }
270     if (M == 0) {
271       errs() << argv[0] << ": " << BitcodeFile << ": "
272         << ErrorMessage << "\n";
273       return 1;
274     }
275
276     // Read the profiling information. This is redundant since we load it again
277     // using the standard profile info provider pass, but for now this gives us
278     // access to additional information not exposed via the ProfileInfo
279     // interface.
280     ProfileInfoLoader PIL(argv[0], ProfileDataFile, *M);
281
282     // Run the printer pass.
283     PassManager PassMgr;
284     PassMgr.add(createProfileLoaderPass(ProfileDataFile));
285     PassMgr.add(new ProfileInfoPrinterPass(PIL));
286     PassMgr.run(*M);
287
288     return 0;
289   } catch (const std::string& msg) {
290     errs() << argv[0] << ": " << msg << "\n";
291   } catch (...) {
292     errs() << argv[0] << ": Unexpected unknown exception occurred.\n";
293   }
294   
295   return 1;
296 }