Fix part 1 of pr4682. PICADD is a 16-bit instruction even in thumb2 mode.
[llvm/avr.git] / tools / llvm-prof / llvm-prof.cpp
blob8dd26b03c91c8e759256340d9099bd11088fe453
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.
14 //===----------------------------------------------------------------------===//
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/Bitcode/ReaderWriter.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/System/Signals.h"
30 #include <algorithm>
31 #include <iostream>
32 #include <iomanip>
33 #include <map>
34 #include <set>
36 using namespace llvm;
38 namespace {
39 cl::opt<std::string>
40 BitcodeFile(cl::Positional, cl::desc("<program bitcode file>"),
41 cl::Required);
43 cl::opt<std::string>
44 ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
45 cl::Optional, cl::init("llvmprof.out"));
47 cl::opt<bool>
48 PrintAnnotatedLLVM("annotated-llvm",
49 cl::desc("Print LLVM code with frequency annotations"));
50 cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"),
51 cl::aliasopt(PrintAnnotatedLLVM));
52 cl::opt<bool>
53 PrintAllCode("print-all-code",
54 cl::desc("Print annotated code for the entire program"));
57 // PairSecondSort - A sorting predicate to sort by the second element of a pair.
58 template<class T>
59 struct PairSecondSortReverse
60 : public std::binary_function<std::pair<T, unsigned>,
61 std::pair<T, unsigned>, bool> {
62 bool operator()(const std::pair<T, unsigned> &LHS,
63 const std::pair<T, unsigned> &RHS) const {
64 return LHS.second > RHS.second;
68 namespace {
69 class ProfileAnnotator : public AssemblyAnnotationWriter {
70 std::map<const Function *, unsigned> &FuncFreqs;
71 std::map<const BasicBlock*, unsigned> &BlockFreqs;
72 std::map<ProfileInfoLoader::Edge, unsigned> &EdgeFreqs;
73 public:
74 ProfileAnnotator(std::map<const Function *, unsigned> &FF,
75 std::map<const BasicBlock*, unsigned> &BF,
76 std::map<ProfileInfoLoader::Edge, unsigned> &EF)
77 : FuncFreqs(FF), BlockFreqs(BF), EdgeFreqs(EF) {}
79 virtual void emitFunctionAnnot(const Function *F, raw_ostream &OS) {
80 OS << ";;; %" << F->getName() << " called " << FuncFreqs[F]
81 << " times.\n;;;\n";
83 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
84 raw_ostream &OS) {
85 if (BlockFreqs.empty()) return;
86 std::map<const BasicBlock *, unsigned>::const_iterator I =
87 BlockFreqs.find(BB);
88 if (I != BlockFreqs.end())
89 OS << "\t;;; Basic block executed " << I->second << " times.\n";
90 else
91 OS << "\t;;; Never executed!\n";
94 virtual void emitBasicBlockEndAnnot(const BasicBlock *BB, raw_ostream &OS) {
95 if (EdgeFreqs.empty()) return;
97 // Figure out how many times each successor executed.
98 std::vector<std::pair<const BasicBlock*, unsigned> > SuccCounts;
99 const TerminatorInst *TI = BB->getTerminator();
101 std::map<ProfileInfoLoader::Edge, unsigned>::iterator I =
102 EdgeFreqs.lower_bound(std::make_pair(const_cast<BasicBlock*>(BB), 0U));
103 for (; I != EdgeFreqs.end() && I->first.first == BB; ++I)
104 if (I->second)
105 SuccCounts.push_back(std::make_pair(TI->getSuccessor(I->first.second),
106 I->second));
107 if (!SuccCounts.empty()) {
108 OS << "\t;;; Out-edge counts:";
109 for (unsigned i = 0, e = SuccCounts.size(); i != e; ++i)
110 OS << " [" << SuccCounts[i].second << " -> "
111 << SuccCounts[i].first->getName() << "]";
112 OS << "\n";
118 namespace {
119 /// ProfileInfoPrinterPass - Helper pass to dump the profile information for
120 /// a module.
122 // FIXME: This should move elsewhere.
123 class ProfileInfoPrinterPass : public ModulePass {
124 ProfileInfoLoader &PIL;
125 public:
126 static char ID; // Class identification, replacement for typeinfo.
127 explicit ProfileInfoPrinterPass(ProfileInfoLoader &_PIL)
128 : ModulePass(&ID), PIL(_PIL) {}
130 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
131 AU.setPreservesAll();
132 AU.addRequired<ProfileInfo>();
135 bool runOnModule(Module &M);
139 char ProfileInfoPrinterPass::ID = 0;
141 bool ProfileInfoPrinterPass::runOnModule(Module &M) {
142 std::map<const Function *, unsigned> FuncFreqs;
143 std::map<const BasicBlock*, unsigned> BlockFreqs;
144 std::map<ProfileInfoLoader::Edge, unsigned> EdgeFreqs;
146 // Output a report. Eventually, there will be multiple reports selectable on
147 // the command line, for now, just keep things simple.
149 // Emit the most frequent function table...
150 std::vector<std::pair<Function*, unsigned> > FunctionCounts;
151 PIL.getFunctionCounts(FunctionCounts);
152 FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end());
154 // Sort by the frequency, backwards.
155 sort(FunctionCounts.begin(), FunctionCounts.end(),
156 PairSecondSortReverse<Function*>());
158 uint64_t TotalExecutions = 0;
159 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
160 TotalExecutions += FunctionCounts[i].second;
162 std::cout << "===" << std::string(73, '-') << "===\n"
163 << "LLVM profiling output for execution";
164 if (PIL.getNumExecutions() != 1) std::cout << "s";
165 std::cout << ":\n";
167 for (unsigned i = 0, e = PIL.getNumExecutions(); i != e; ++i) {
168 std::cout << " ";
169 if (e != 1) std::cout << i+1 << ". ";
170 std::cout << PIL.getExecution(i) << "\n";
173 std::cout << "\n===" << std::string(73, '-') << "===\n";
174 std::cout << "Function execution frequencies:\n\n";
176 // Print out the function frequencies...
177 std::cout << " ## Frequency\n";
178 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
179 if (FunctionCounts[i].second == 0) {
180 std::cout << "\n NOTE: " << e-i << " function" <<
181 (e-i-1 ? "s were" : " was") << " never executed!\n";
182 break;
185 std::cout << std::setw(3) << i+1 << ". "
186 << std::setw(5) << FunctionCounts[i].second << "/"
187 << TotalExecutions << " "
188 << FunctionCounts[i].first->getNameStr() << "\n";
191 std::set<Function*> FunctionsToPrint;
193 // If we have block count information, print out the LLVM module with
194 // frequency annotations.
195 if (PIL.hasAccurateBlockCounts()) {
196 std::vector<std::pair<BasicBlock*, unsigned> > Counts;
197 PIL.getBlockCounts(Counts);
199 TotalExecutions = 0;
200 for (unsigned i = 0, e = Counts.size(); i != e; ++i)
201 TotalExecutions += Counts[i].second;
203 // Sort by the frequency, backwards.
204 sort(Counts.begin(), Counts.end(),
205 PairSecondSortReverse<BasicBlock*>());
207 std::cout << "\n===" << std::string(73, '-') << "===\n";
208 std::cout << "Top 20 most frequently executed basic blocks:\n\n";
210 // Print out the function frequencies...
211 std::cout <<" ## %% \tFrequency\n";
212 unsigned BlocksToPrint = Counts.size();
213 if (BlocksToPrint > 20) BlocksToPrint = 20;
214 for (unsigned i = 0; i != BlocksToPrint; ++i) {
215 if (Counts[i].second == 0) break;
216 Function *F = Counts[i].first->getParent();
217 std::cout << std::setw(3) << i+1 << ". "
218 << std::setw(5) << std::setprecision(2)
219 << Counts[i].second/(double)TotalExecutions*100 << "% "
220 << std::setw(5) << Counts[i].second << "/"
221 << TotalExecutions << "\t"
222 << F->getNameStr() << "() - "
223 << Counts[i].first->getNameStr() << "\n";
224 FunctionsToPrint.insert(F);
227 BlockFreqs.insert(Counts.begin(), Counts.end());
230 if (PIL.hasAccurateEdgeCounts()) {
231 std::vector<std::pair<ProfileInfoLoader::Edge, unsigned> > Counts;
232 PIL.getEdgeCounts(Counts);
233 EdgeFreqs.insert(Counts.begin(), Counts.end());
236 if (PrintAnnotatedLLVM || PrintAllCode) {
237 std::cout << "\n===" << std::string(73, '-') << "===\n";
238 std::cout << "Annotated LLVM code for the module:\n\n";
240 ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs);
242 if (FunctionsToPrint.empty() || PrintAllCode)
243 M.print(std::cout, &PA);
244 else
245 // Print just a subset of the functions.
246 for (std::set<Function*>::iterator I = FunctionsToPrint.begin(),
247 E = FunctionsToPrint.end(); I != E; ++I)
248 (*I)->print(std::cout, &PA);
251 return false;
254 int main(int argc, char **argv) {
255 // Print a stack trace if we signal out.
256 sys::PrintStackTraceOnErrorSignal();
257 PrettyStackTraceProgram X(argc, argv);
259 LLVMContext &Context = getGlobalContext();
260 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
261 try {
262 cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");
264 // Read in the bitcode file...
265 std::string ErrorMessage;
266 Module *M = 0;
267 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BitcodeFile,
268 &ErrorMessage)) {
269 M = ParseBitcodeFile(Buffer, Context, &ErrorMessage);
270 delete Buffer;
272 if (M == 0) {
273 errs() << argv[0] << ": " << BitcodeFile << ": "
274 << ErrorMessage << "\n";
275 return 1;
278 // Read the profiling information. This is redundant since we load it again
279 // using the standard profile info provider pass, but for now this gives us
280 // access to additional information not exposed via the ProfileInfo
281 // interface.
282 ProfileInfoLoader PIL(argv[0], ProfileDataFile, *M);
284 // Run the printer pass.
285 PassManager PassMgr;
286 PassMgr.add(createProfileLoaderPass(ProfileDataFile));
287 PassMgr.add(new ProfileInfoPrinterPass(PIL));
288 PassMgr.run(*M);
290 return 0;
291 } catch (const std::string& msg) {
292 errs() << argv[0] << ": " << msg << "\n";
293 } catch (...) {
294 errs() << argv[0] << ": Unexpected unknown exception occurred.\n";
297 return 1;