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