Switch the asmprinter (.ll) and all the stuff it requires over to
[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/Module.h"
18 #include "llvm/Assembly/AsmAnnotationWriter.h"
19 #include "llvm/Analysis/ProfileInfoLoader.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/System/Signals.h"
26 #include <algorithm>
27 #include <iostream>
28 #include <iomanip>
29 #include <map>
30 #include <set>
31
32 using namespace llvm;
33
34 namespace {
35   cl::opt<std::string>
36   BitcodeFile(cl::Positional, cl::desc("<program bitcode file>"),
37               cl::Required);
38
39   cl::opt<std::string>
40   ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
41                   cl::Optional, cl::init("llvmprof.out"));
42
43   cl::opt<bool>
44   PrintAnnotatedLLVM("annotated-llvm",
45                      cl::desc("Print LLVM code with frequency annotations"));
46   cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"),
47                             cl::aliasopt(PrintAnnotatedLLVM));
48   cl::opt<bool>
49   PrintAllCode("print-all-code",
50                cl::desc("Print annotated code for the entire program"));
51 }
52
53 // PairSecondSort - A sorting predicate to sort by the second element of a pair.
54 template<class T>
55 struct PairSecondSortReverse
56   : public std::binary_function<std::pair<T, unsigned>,
57                                 std::pair<T, unsigned>, bool> {
58   bool operator()(const std::pair<T, unsigned> &LHS,
59                   const std::pair<T, unsigned> &RHS) const {
60     return LHS.second > RHS.second;
61   }
62 };
63
64 namespace {
65   class ProfileAnnotator : public AssemblyAnnotationWriter {
66     std::map<const Function  *, unsigned> &FuncFreqs;
67     std::map<const BasicBlock*, unsigned> &BlockFreqs;
68     std::map<ProfileInfoLoader::Edge, unsigned> &EdgeFreqs;
69   public:
70     ProfileAnnotator(std::map<const Function  *, unsigned> &FF,
71                      std::map<const BasicBlock*, unsigned> &BF,
72                      std::map<ProfileInfoLoader::Edge, unsigned> &EF)
73       : FuncFreqs(FF), BlockFreqs(BF), EdgeFreqs(EF) {}
74
75     virtual void emitFunctionAnnot(const Function *F, raw_ostream &OS) {
76       OS << ";;; %" << F->getName() << " called " << FuncFreqs[F]
77          << " times.\n;;;\n";
78     }
79     virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
80                                           raw_ostream &OS) {
81       if (BlockFreqs.empty()) return;
82       if (unsigned Count = BlockFreqs[BB])
83         OS << "\t;;; Basic block executed " << Count << " times.\n";
84       else
85         OS << "\t;;; Never executed!\n";
86     }
87
88     virtual void emitBasicBlockEndAnnot(const BasicBlock *BB, raw_ostream &OS) {
89       if (EdgeFreqs.empty()) return;
90
91       // Figure out how many times each successor executed.
92       std::vector<std::pair<const BasicBlock*, unsigned> > SuccCounts;
93       const TerminatorInst *TI = BB->getTerminator();
94
95       std::map<ProfileInfoLoader::Edge, unsigned>::iterator I =
96         EdgeFreqs.lower_bound(std::make_pair(const_cast<BasicBlock*>(BB), 0U));
97       for (; I != EdgeFreqs.end() && I->first.first == BB; ++I)
98         if (I->second)
99           SuccCounts.push_back(std::make_pair(TI->getSuccessor(I->first.second),
100                                               I->second));
101       if (!SuccCounts.empty()) {
102         OS << "\t;;; Out-edge counts:";
103         for (unsigned i = 0, e = SuccCounts.size(); i != e; ++i)
104           OS << " [" << SuccCounts[i].second << " -> "
105              << SuccCounts[i].first->getName() << "]";
106         OS << "\n";
107       }
108     }
109   };
110 }
111
112
113 int main(int argc, char **argv) {
114   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
115   try {
116     cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");
117     sys::PrintStackTraceOnErrorSignal();
118
119     // Read in the bitcode file...
120     std::string ErrorMessage;
121     Module *M = 0;
122     if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BitcodeFile,
123                                                             &ErrorMessage)) {
124       M = ParseBitcodeFile(Buffer, &ErrorMessage);
125       delete Buffer;
126     }
127     if (M == 0) {
128       std::cerr << argv[0] << ": " << BitcodeFile << ": " 
129         << ErrorMessage << "\n";
130       return 1;
131     }
132
133     // Read the profiling information
134     ProfileInfoLoader PI(argv[0], ProfileDataFile, *M);
135
136     std::map<const Function  *, unsigned> FuncFreqs;
137     std::map<const BasicBlock*, unsigned> BlockFreqs;
138     std::map<ProfileInfoLoader::Edge, unsigned> EdgeFreqs;
139
140     // Output a report. Eventually, there will be multiple reports selectable on
141     // the command line, for now, just keep things simple.
142
143     // Emit the most frequent function table...
144     std::vector<std::pair<Function*, unsigned> > FunctionCounts;
145     PI.getFunctionCounts(FunctionCounts);
146     FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end());
147
148     // Sort by the frequency, backwards.
149     sort(FunctionCounts.begin(), FunctionCounts.end(),
150               PairSecondSortReverse<Function*>());
151
152     uint64_t TotalExecutions = 0;
153     for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
154       TotalExecutions += FunctionCounts[i].second;
155
156     std::cout << "===" << std::string(73, '-') << "===\n"
157               << "LLVM profiling output for execution";
158     if (PI.getNumExecutions() != 1) std::cout << "s";
159     std::cout << ":\n";
160
161     for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) {
162       std::cout << "  ";
163       if (e != 1) std::cout << i+1 << ". ";
164       std::cout << PI.getExecution(i) << "\n";
165     }
166
167     std::cout << "\n===" << std::string(73, '-') << "===\n";
168     std::cout << "Function execution frequencies:\n\n";
169
170     // Print out the function frequencies...
171     std::cout << " ##   Frequency\n";
172     for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
173       if (FunctionCounts[i].second == 0) {
174         std::cout << "\n  NOTE: " << e-i << " function" <<
175                (e-i-1 ? "s were" : " was") << " never executed!\n";
176         break;
177       }
178
179       std::cout << std::setw(3) << i+1 << ". " 
180         << std::setw(5) << FunctionCounts[i].second << "/"
181         << TotalExecutions << " "
182         << FunctionCounts[i].first->getName().c_str() << "\n";
183     }
184
185     std::set<Function*> FunctionsToPrint;
186
187     // If we have block count information, print out the LLVM module with
188     // frequency annotations.
189     if (PI.hasAccurateBlockCounts()) {
190       std::vector<std::pair<BasicBlock*, unsigned> > Counts;
191       PI.getBlockCounts(Counts);
192
193       TotalExecutions = 0;
194       for (unsigned i = 0, e = Counts.size(); i != e; ++i)
195         TotalExecutions += Counts[i].second;
196
197       // Sort by the frequency, backwards.
198       sort(Counts.begin(), Counts.end(),
199                 PairSecondSortReverse<BasicBlock*>());
200
201       std::cout << "\n===" << std::string(73, '-') << "===\n";
202       std::cout << "Top 20 most frequently executed basic blocks:\n\n";
203
204       // Print out the function frequencies...
205       std::cout <<" ##      %% \tFrequency\n";
206       unsigned BlocksToPrint = Counts.size();
207       if (BlocksToPrint > 20) BlocksToPrint = 20;
208       for (unsigned i = 0; i != BlocksToPrint; ++i) {
209         if (Counts[i].second == 0) break;
210         Function *F = Counts[i].first->getParent();
211         std::cout << std::setw(3) << i+1 << ". " 
212           << std::setw(5) << std::setprecision(2) 
213           << Counts[i].second/(double)TotalExecutions*100 << "% "
214           << std::setw(5) << Counts[i].second << "/"
215           << TotalExecutions << "\t"
216           << F->getName().c_str() << "() - "
217           << Counts[i].first->getName().c_str() << "\n";
218         FunctionsToPrint.insert(F);
219       }
220
221       BlockFreqs.insert(Counts.begin(), Counts.end());
222     }
223
224     if (PI.hasAccurateEdgeCounts()) {
225       std::vector<std::pair<ProfileInfoLoader::Edge, unsigned> > Counts;
226       PI.getEdgeCounts(Counts);
227       EdgeFreqs.insert(Counts.begin(), Counts.end());
228     }
229
230     if (PrintAnnotatedLLVM || PrintAllCode) {
231       std::cout << "\n===" << std::string(73, '-') << "===\n";
232       std::cout << "Annotated LLVM code for the module:\n\n";
233
234       ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs);
235
236       if (FunctionsToPrint.empty() || PrintAllCode)
237         M->print(std::cout, &PA);
238       else
239         // Print just a subset of the functions.
240         for (std::set<Function*>::iterator I = FunctionsToPrint.begin(),
241                E = FunctionsToPrint.end(); I != E; ++I)
242           (*I)->print(std::cout, &PA);
243     }
244
245     return 0;
246   } catch (const std::string& msg) {
247     std::cerr << argv[0] << ": " << msg << "\n";
248   } catch (...) {
249     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
250   }
251   return 1;
252 }