ProfileInfoLoaderPass.cpp revision 8be3291f5942e3ae4a5d66c480e7aabe2f771031
1//===- ProfileInfoLoaderPass.cpp - LLVM Pass to load profile info ---------===//
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 file implements a concrete implementation of profiling information that
11// loads the information from a profile dump file.
12//
13//===----------------------------------------------------------------------===//
14#define DEBUG_TYPE "profile-loader"
15#include "llvm/BasicBlock.h"
16#include "llvm/InstrTypes.h"
17#include "llvm/Module.h"
18#include "llvm/Pass.h"
19#include "llvm/Analysis/Passes.h"
20#include "llvm/Analysis/ProfileInfo.h"
21#include "llvm/Analysis/ProfileInfoLoader.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/CFG.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/Support/Format.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/SmallSet.h"
29#include <set>
30using namespace llvm;
31
32STATISTIC(NumEdgesRead, "The # of edges read.");
33
34static cl::opt<std::string>
35ProfileInfoFilename("profile-info-file", cl::init("llvmprof.out"),
36                    cl::value_desc("filename"),
37                    cl::desc("Profile file loaded by -profile-loader"));
38
39namespace {
40  class LoaderPass : public ModulePass, public ProfileInfo {
41    std::string Filename;
42    std::set<Edge> SpanningTree;
43    std::set<const BasicBlock*> BBisUnvisited;
44    unsigned ReadCount;
45  public:
46    static char ID; // Class identification, replacement for typeinfo
47    explicit LoaderPass(const std::string &filename = "")
48      : ModulePass(&ID), Filename(filename) {
49      if (filename.empty()) Filename = ProfileInfoFilename;
50    }
51
52    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53      AU.setPreservesAll();
54    }
55
56    virtual const char *getPassName() const {
57      return "Profiling information loader";
58    }
59
60    // recurseBasicBlock() - Calculates the edge weights for as much basic
61    // blocks as possbile.
62    virtual void recurseBasicBlock(const BasicBlock *BB);
63    virtual void readEdgeOrRemember(Edge, Edge&, unsigned &, double &);
64    virtual void readEdge(ProfileInfo::Edge, std::vector<unsigned>&);
65
66    /// getAdjustedAnalysisPointer - This method is used when a pass implements
67    /// an analysis interface through multiple inheritance.  If needed, it
68    /// should override this to adjust the this pointer as needed for the
69    /// specified pass info.
70    virtual void *getAdjustedAnalysisPointer(const PassInfo *PI) {
71      if (PI->isPassID(&ProfileInfo::ID))
72        return (ProfileInfo*)this;
73      return this;
74    }
75
76    /// run - Load the profile information from the specified file.
77    virtual bool runOnModule(Module &M);
78  };
79}  // End of anonymous namespace
80
81char LoaderPass::ID = 0;
82static RegisterPass<LoaderPass>
83X("profile-loader", "Load profile information from llvmprof.out", false, true);
84
85static RegisterAnalysisGroup<ProfileInfo> Y(X);
86
87const PassInfo *llvm::ProfileLoaderPassID = &X;
88
89ModulePass *llvm::createProfileLoaderPass() { return new LoaderPass(); }
90
91/// createProfileLoaderPass - This function returns a Pass that loads the
92/// profiling information for the module from the specified filename, making it
93/// available to the optimizers.
94Pass *llvm::createProfileLoaderPass(const std::string &Filename) {
95  return new LoaderPass(Filename);
96}
97
98void LoaderPass::readEdgeOrRemember(Edge edge, Edge &tocalc,
99                                    unsigned &uncalc, double &count) {
100  double w;
101  if ((w = getEdgeWeight(edge)) == MissingValue) {
102    tocalc = edge;
103    uncalc++;
104  } else {
105    count+=w;
106  }
107}
108
109// recurseBasicBlock - Visits all neighbours of a block and then tries to
110// calculate the missing edge values.
111void LoaderPass::recurseBasicBlock(const BasicBlock *BB) {
112
113  // break recursion if already visited
114  if (BBisUnvisited.find(BB) == BBisUnvisited.end()) return;
115  BBisUnvisited.erase(BB);
116  if (!BB) return;
117
118  for (succ_const_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
119       bbi != bbe; ++bbi) {
120    recurseBasicBlock(*bbi);
121  }
122  for (const_pred_iterator bbi = pred_begin(BB), bbe = pred_end(BB);
123       bbi != bbe; ++bbi) {
124    recurseBasicBlock(*bbi);
125  }
126
127  Edge tocalc;
128  if (CalculateMissingEdge(BB, tocalc)) {
129    SpanningTree.erase(tocalc);
130  }
131}
132
133void LoaderPass::readEdge(ProfileInfo::Edge e,
134                          std::vector<unsigned> &ECs) {
135  if (ReadCount < ECs.size()) {
136    double weight = ECs[ReadCount++];
137    if (weight != ProfileInfoLoader::Uncounted) {
138      // Here the data realm changes from the unsigned of the file to the
139      // double of the ProfileInfo. This conversion is save because we know
140      // that everything thats representable in unsinged is also representable
141      // in double.
142      EdgeInformation[getFunction(e)][e] += (double)weight;
143
144      DEBUG(dbgs() << "--Read Edge Counter for " << e
145                   << " (# "<< (ReadCount-1) << "): "
146                   << (unsigned)getEdgeWeight(e) << "\n");
147    } else {
148      // This happens only if reading optimal profiling information, not when
149      // reading regular profiling information.
150      SpanningTree.insert(e);
151    }
152  }
153}
154
155bool LoaderPass::runOnModule(Module &M) {
156  ProfileInfoLoader PIL("profile-loader", Filename, M);
157
158  EdgeInformation.clear();
159  std::vector<unsigned> Counters = PIL.getRawEdgeCounts();
160  if (Counters.size() > 0) {
161    ReadCount = 0;
162    for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
163      if (F->isDeclaration()) continue;
164      DEBUG(dbgs()<<"Working on "<<F->getNameStr()<<"\n");
165      readEdge(getEdge(0,&F->getEntryBlock()), Counters);
166      for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
167        TerminatorInst *TI = BB->getTerminator();
168        for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {
169          readEdge(getEdge(BB,TI->getSuccessor(s)), Counters);
170        }
171      }
172    }
173    if (ReadCount != Counters.size()) {
174      errs() << "WARNING: profile information is inconsistent with "
175             << "the current program!\n";
176    }
177    NumEdgesRead = ReadCount;
178  }
179
180  Counters = PIL.getRawOptimalEdgeCounts();
181  if (Counters.size() > 0) {
182    ReadCount = 0;
183    for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
184      if (F->isDeclaration()) continue;
185      DEBUG(dbgs()<<"Working on "<<F->getNameStr()<<"\n");
186      readEdge(getEdge(0,&F->getEntryBlock()), Counters);
187      for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
188        TerminatorInst *TI = BB->getTerminator();
189        if (TI->getNumSuccessors() == 0) {
190          readEdge(getEdge(BB,0), Counters);
191        }
192        for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {
193          readEdge(getEdge(BB,TI->getSuccessor(s)), Counters);
194        }
195      }
196      while (SpanningTree.size() > 0) {
197
198        unsigned size = SpanningTree.size();
199
200        BBisUnvisited.clear();
201        for (std::set<Edge>::iterator ei = SpanningTree.begin(),
202             ee = SpanningTree.end(); ei != ee; ++ei) {
203          BBisUnvisited.insert(ei->first);
204          BBisUnvisited.insert(ei->second);
205        }
206        while (BBisUnvisited.size() > 0) {
207          recurseBasicBlock(*BBisUnvisited.begin());
208        }
209
210        if (SpanningTree.size() == size) {
211          DEBUG(dbgs()<<"{");
212          for (std::set<Edge>::iterator ei = SpanningTree.begin(),
213               ee = SpanningTree.end(); ei != ee; ++ei) {
214            DEBUG(dbgs()<< *ei <<",");
215          }
216          assert(0 && "No edge calculated!");
217        }
218
219      }
220    }
221    if (ReadCount != Counters.size()) {
222      errs() << "WARNING: profile information is inconsistent with "
223             << "the current program!\n";
224    }
225    NumEdgesRead = ReadCount;
226  }
227
228  BlockInformation.clear();
229  Counters = PIL.getRawBlockCounts();
230  if (Counters.size() > 0) {
231    ReadCount = 0;
232    for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
233      if (F->isDeclaration()) continue;
234      for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
235        if (ReadCount < Counters.size())
236          // Here the data realm changes from the unsigned of the file to the
237          // double of the ProfileInfo. This conversion is save because we know
238          // that everything thats representable in unsinged is also
239          // representable in double.
240          BlockInformation[F][BB] = (double)Counters[ReadCount++];
241    }
242    if (ReadCount != Counters.size()) {
243      errs() << "WARNING: profile information is inconsistent with "
244             << "the current program!\n";
245    }
246  }
247
248  FunctionInformation.clear();
249  Counters = PIL.getRawFunctionCounts();
250  if (Counters.size() > 0) {
251    ReadCount = 0;
252    for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
253      if (F->isDeclaration()) continue;
254      if (ReadCount < Counters.size())
255        // Here the data realm changes from the unsigned of the file to the
256        // double of the ProfileInfo. This conversion is save because we know
257        // that everything thats representable in unsinged is also
258        // representable in double.
259        FunctionInformation[F] = (double)Counters[ReadCount++];
260    }
261    if (ReadCount != Counters.size()) {
262      errs() << "WARNING: profile information is inconsistent with "
263             << "the current program!\n";
264    }
265  }
266
267  return false;
268}
269