1 //===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/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"
41 BitcodeFile(cl::Positional, cl::desc("<program bitcode file>"),
45 ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
46 cl::Optional, cl::init("llvmprof.out"));
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));
54 PrintAllCode("print-all-code",
55 cl::desc("Print annotated code for the entire program"));
58 // PairSecondSort - A sorting predicate to sort by the second element of a pair.
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;
69 static double ignoreMissing(double w) {
70 if (w == ProfileInfo::MissingValue) return 0;
75 class ProfileAnnotator : public AssemblyAnnotationWriter {
78 ProfileAnnotator(ProfileInfo& pi) : PI(pi) {}
80 virtual void emitFunctionAnnot(const Function *F, raw_ostream &OS) {
81 OS << ";;; %" << F->getName() << " called ";
82 double w = PI.getExecutionCount(F);
83 if (w == ProfileInfo::MissingValue)
87 OS << " times.\n;;;\n";
89 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
91 double w = PI.getExecutionCount(BB);
92 if (w == ProfileInfo::MissingValue)
93 OS << "\t;;; (no value)\n";
96 OS << "\t;;; Basic block executed " << w << " times.\n";
98 OS << "\t;;; Never executed!\n";
101 virtual void emitBasicBlockEndAnnot(const BasicBlock *BB, raw_ostream &OS) {
102 // Figure out how many times each successor executed.
103 std::vector<std::pair<ProfileInfo::Edge, unsigned> > SuccCounts;
105 const TerminatorInst *TI = BB->getTerminator();
106 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {
107 BasicBlock* Succ = TI->getSuccessor(s);
108 double w = ignoreMissing(PI.getEdgeWeight(std::make_pair(BB,Succ)));
109 SuccCounts.push_back(std::make_pair(std::make_pair(BB,Succ), w));
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() << "]";
123 /// ProfileInfoPrinterPass - Helper pass to dump the profile information for
126 // FIXME: This should move elsewhere.
127 class ProfileInfoPrinterPass : public ModulePass {
128 ProfileInfoLoader &PIL;
130 static char ID; // Class identification, replacement for typeinfo.
131 explicit ProfileInfoPrinterPass(ProfileInfoLoader &_PIL)
132 : ModulePass(&ID), PIL(_PIL) {}
134 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
135 AU.setPreservesAll();
136 AU.addRequired<ProfileInfo>();
139 bool runOnModule(Module &M);
143 char ProfileInfoPrinterPass::ID = 0;
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;
151 // Output a report. Eventually, there will be multiple reports selectable on
152 // the command line, for now, just keep things simple.
154 // Emit the most frequent function table...
155 std::vector<std::pair<Function*, unsigned> > FunctionCounts;
156 std::vector<std::pair<BasicBlock*, unsigned> > 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();
163 double w = ignoreMissing(PI.getExecutionCount(BB));
164 Counts.push_back(std::make_pair(BB,w));
168 // Sort by the frequency, backwards.
169 sort(FunctionCounts.begin(), FunctionCounts.end(),
170 PairSecondSortReverse<Function*>());
172 uint64_t TotalExecutions = 0;
173 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
174 TotalExecutions += FunctionCounts[i].second;
176 std::cout << "===" << std::string(73, '-') << "===\n"
177 << "LLVM profiling output for execution";
178 if (PIL.getNumExecutions() != 1) std::cout << "s";
181 for (unsigned i = 0, e = PIL.getNumExecutions(); i != e; ++i) {
183 if (e != 1) std::cout << i+1 << ". ";
184 std::cout << PIL.getExecution(i) << "\n";
187 std::cout << "\n===" << std::string(73, '-') << "===\n";
188 std::cout << "Function execution frequencies:\n\n";
190 // Print out the function frequencies...
191 std::cout << " ## Frequency\n";
192 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
193 if (FunctionCounts[i].second == 0) {
194 std::cout << "\n NOTE: " << e-i << " function" <<
195 (e-i-1 ? "s were" : " was") << " never executed!\n";
199 std::cout << std::setw(3) << i+1 << ". "
200 << std::setw(5) << FunctionCounts[i].second << "/"
201 << TotalExecutions << " "
202 << FunctionCounts[i].first->getNameStr() << "\n";
205 std::set<Function*> FunctionsToPrint;
208 for (unsigned i = 0, e = Counts.size(); i != e; ++i)
209 TotalExecutions += Counts[i].second;
211 // Sort by the frequency, backwards.
212 sort(Counts.begin(), Counts.end(),
213 PairSecondSortReverse<BasicBlock*>());
215 std::cout << "\n===" << std::string(73, '-') << "===\n";
216 std::cout << "Top 20 most frequently executed basic blocks:\n\n";
218 // Print out the function frequencies...
219 std::cout <<" ## %% \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 std::cout << std::setw(3) << i+1 << ". "
226 << std::setw(5) << std::setprecision(3)
227 << Counts[i].second/(double)TotalExecutions*100 << "% "
228 << std::setw(5) << Counts[i].second << "/"
229 << TotalExecutions << "\t"
230 << F->getNameStr() << "() - "
231 << Counts[i].first->getNameStr() << "\n";
232 FunctionsToPrint.insert(F);
235 if (PrintAnnotatedLLVM || PrintAllCode) {
236 std::cout << "\n===" << std::string(73, '-') << "===\n";
237 std::cout << "Annotated LLVM code for the module:\n\n";
239 ProfileAnnotator PA(PI);
241 if (FunctionsToPrint.empty() || PrintAllCode)
242 M.print(std::cout, &PA);
244 // Print just a subset of the functions.
245 for (std::set<Function*>::iterator I = FunctionsToPrint.begin(),
246 E = FunctionsToPrint.end(); I != E; ++I)
247 (*I)->print(std::cout, &PA);
253 int main(int argc, char **argv) {
254 // Print a stack trace if we signal out.
255 sys::PrintStackTraceOnErrorSignal();
256 PrettyStackTraceProgram X(argc, argv);
258 LLVMContext &Context = getGlobalContext();
259 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
261 cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");
263 // Read in the bitcode file...
264 std::string ErrorMessage;
266 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BitcodeFile,
268 M = ParseBitcodeFile(Buffer, Context, &ErrorMessage);
272 errs() << argv[0] << ": " << BitcodeFile << ": "
273 << ErrorMessage << "\n";
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
281 ProfileInfoLoader PIL(argv[0], ProfileDataFile, *M);
283 // Run the printer pass.
285 PassMgr.add(createProfileLoaderPass(ProfileDataFile));
286 PassMgr.add(new ProfileInfoPrinterPass(PIL));
290 } catch (const std::string& msg) {
291 errs() << argv[0] << ": " << msg << "\n";
293 errs() << argv[0] << ": Unexpected unknown exception occurred.\n";