Begin adding static dependence information to passes, which will allow us to
[oota-llvm.git] / lib / Analysis / ProfileEstimatorPass.cpp
1 //===- ProfileEstimatorPass.cpp - LLVM Pass to estimate 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 // estimates the profiling information in a very crude and unimaginative way.
12 //
13 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "profile-estimator"
15 #include "llvm/Pass.h"
16 #include "llvm/Analysis/Passes.h"
17 #include "llvm/Analysis/ProfileInfo.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Support/Format.h"
23 using namespace llvm;
24
25 static cl::opt<double>
26 LoopWeight(
27     "profile-estimator-loop-weight", cl::init(10),
28     cl::value_desc("loop-weight"),
29     cl::desc("Number of loop executions used for profile-estimator")
30 );
31
32 namespace {
33   class ProfileEstimatorPass : public FunctionPass, public ProfileInfo {
34     double ExecCount;
35     LoopInfo *LI;
36     std::set<BasicBlock*>  BBToVisit;
37     std::map<Loop*,double> LoopExitWeights;
38     std::map<Edge,double>  MinimalWeight;
39   public:
40     static char ID; // Class identification, replacement for typeinfo
41     explicit ProfileEstimatorPass(const double execcount = 0)
42       : FunctionPass(ID), ExecCount(execcount) {
43       if (execcount == 0) ExecCount = LoopWeight;
44     }
45
46     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47       AU.setPreservesAll();
48       AU.addRequired<LoopInfo>();
49     }
50
51     virtual const char *getPassName() const {
52       return "Profiling information estimator";
53     }
54
55     /// run - Estimate the profile information from the specified file.
56     virtual bool runOnFunction(Function &F);
57
58     /// getAdjustedAnalysisPointer - This method is used when a pass implements
59     /// an analysis interface through multiple inheritance.  If needed, it
60     /// should override this to adjust the this pointer as needed for the
61     /// specified pass info.
62     virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
63       if (PI == &ProfileInfo::ID)
64         return (ProfileInfo*)this;
65       return this;
66     }
67     
68     virtual void recurseBasicBlock(BasicBlock *BB);
69
70     void inline printEdgeWeight(Edge);
71   };
72 }  // End of anonymous namespace
73
74 char ProfileEstimatorPass::ID = 0;
75 INITIALIZE_AG_PASS_BEGIN(ProfileEstimatorPass, ProfileInfo, "profile-estimator",
76                 "Estimate profiling information", false, true, false)
77 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
78 INITIALIZE_AG_PASS_END(ProfileEstimatorPass, ProfileInfo, "profile-estimator",
79                 "Estimate profiling information", false, true, false)
80
81 namespace llvm {
82   char &ProfileEstimatorPassID = ProfileEstimatorPass::ID;
83
84   FunctionPass *createProfileEstimatorPass() {
85     return new ProfileEstimatorPass();
86   }
87
88   /// createProfileEstimatorPass - This function returns a Pass that estimates
89   /// profiling information using the given loop execution count.
90   Pass *createProfileEstimatorPass(const unsigned execcount) {
91     return new ProfileEstimatorPass(execcount);
92   }
93 }
94
95 static double ignoreMissing(double w) {
96   if (w == ProfileInfo::MissingValue) return 0;
97   return w;
98 }
99
100 static void inline printEdgeError(ProfileInfo::Edge e, const char *M) {
101   DEBUG(dbgs() << "-- Edge " << e << " is not calculated, " << M << "\n");
102 }
103
104 void inline ProfileEstimatorPass::printEdgeWeight(Edge E) {
105   DEBUG(dbgs() << "-- Weight of Edge " << E << ":"
106                << format("%20.20g", getEdgeWeight(E)) << "\n");
107 }
108
109 // recurseBasicBlock() - This calculates the ProfileInfo estimation for a
110 // single block and then recurses into the successors.
111 // The algorithm preserves the flow condition, meaning that the sum of the
112 // weight of the incoming edges must be equal the block weight which must in
113 // turn be equal to the sume of the weights of the outgoing edges.
114 // Since the flow of an block is deterimined from the current state of the
115 // flow, once an edge has a flow assigned this flow is never changed again,
116 // otherwise it would be possible to violate the flow condition in another
117 // block.
118 void ProfileEstimatorPass::recurseBasicBlock(BasicBlock *BB) {
119
120   // Break the recursion if this BasicBlock was already visited.
121   if (BBToVisit.find(BB) == BBToVisit.end()) return;
122
123   // Read the LoopInfo for this block.
124   bool  BBisHeader = LI->isLoopHeader(BB);
125   Loop* BBLoop     = LI->getLoopFor(BB);
126
127   // To get the block weight, read all incoming edges.
128   double BBWeight = 0;
129   std::set<BasicBlock*> ProcessedPreds;
130   for ( pred_iterator bbi = pred_begin(BB), bbe = pred_end(BB);
131         bbi != bbe; ++bbi ) {
132     // If this block was not considered already, add weight.
133     Edge edge = getEdge(*bbi,BB);
134     double w = getEdgeWeight(edge);
135     if (ProcessedPreds.insert(*bbi).second) {
136       BBWeight += ignoreMissing(w);
137     }
138     // If this block is a loop header and the predecessor is contained in this
139     // loop, thus the edge is a backedge, continue and do not check if the
140     // value is valid.
141     if (BBisHeader && BBLoop->contains(*bbi)) {
142       printEdgeError(edge, "but is backedge, continueing");
143       continue;
144     }
145     // If the edges value is missing (and this is no loop header, and this is
146     // no backedge) return, this block is currently non estimatable.
147     if (w == MissingValue) {
148       printEdgeError(edge, "returning");
149       return;
150     }
151   }
152   if (getExecutionCount(BB) != MissingValue) {
153     BBWeight = getExecutionCount(BB);
154   }
155
156   // Fetch all necessary information for current block.
157   SmallVector<Edge, 8> ExitEdges;
158   SmallVector<Edge, 8> Edges;
159   if (BBLoop) {
160     BBLoop->getExitEdges(ExitEdges);
161   }
162
163   // If this is a loop header, consider the following:
164   // Exactly the flow that is entering this block, must exit this block too. So
165   // do the following: 
166   // *) get all the exit edges, read the flow that is already leaving this
167   // loop, remember the edges that do not have any flow on them right now.
168   // (The edges that have already flow on them are most likely exiting edges of
169   // other loops, do not touch those flows because the previously caclulated
170   // loopheaders would not be exact anymore.)
171   // *) In case there is not a single exiting edge left, create one at the loop
172   // latch to prevent the flow from building up in the loop.
173   // *) Take the flow that is not leaving the loop already and distribute it on
174   // the remaining exiting edges.
175   // (This ensures that all flow that enters the loop also leaves it.)
176   // *) Increase the flow into the loop by increasing the weight of this block.
177   // There is at least one incoming backedge that will bring us this flow later
178   // on. (So that the flow condition in this node is valid again.)
179   if (BBisHeader) {
180     double incoming = BBWeight;
181     // Subtract the flow leaving the loop.
182     std::set<Edge> ProcessedExits;
183     for (SmallVector<Edge, 8>::iterator ei = ExitEdges.begin(),
184          ee = ExitEdges.end(); ei != ee; ++ei) {
185       if (ProcessedExits.insert(*ei).second) {
186         double w = getEdgeWeight(*ei);
187         if (w == MissingValue) {
188           Edges.push_back(*ei);
189           // Check if there is a necessary minimal weight, if yes, subtract it 
190           // from weight.
191           if (MinimalWeight.find(*ei) != MinimalWeight.end()) {
192             incoming -= MinimalWeight[*ei];
193             DEBUG(dbgs() << "Reserving " << format("%.20g",MinimalWeight[*ei]) << " at " << (*ei) << "\n");
194           }
195         } else {
196           incoming -= w;
197         }
198       }
199     }
200     // If no exit edges, create one:
201     if (Edges.size() == 0) {
202       BasicBlock *Latch = BBLoop->getLoopLatch();
203       if (Latch) {
204         Edge edge = getEdge(Latch,0);
205         EdgeInformation[BB->getParent()][edge] = BBWeight;
206         printEdgeWeight(edge);
207         edge = getEdge(Latch, BB);
208         EdgeInformation[BB->getParent()][edge] = BBWeight * ExecCount;
209         printEdgeWeight(edge);
210       }
211     }
212
213     // Distribute remaining weight to the exting edges. To prevent fractions
214     // from building up and provoking precision problems the weight which is to
215     // be distributed is split and the rounded, the last edge gets a somewhat
216     // bigger value, but we are close enough for an estimation.
217     double fraction = floor(incoming/Edges.size());
218     for (SmallVector<Edge, 8>::iterator ei = Edges.begin(), ee = Edges.end();
219          ei != ee; ++ei) {
220       double w = 0;
221       if (ei != (ee-1)) {
222         w = fraction;
223         incoming -= fraction;
224       } else {
225         w = incoming;
226       }
227       EdgeInformation[BB->getParent()][*ei] += w;
228       // Read necessary minimal weight.
229       if (MinimalWeight.find(*ei) != MinimalWeight.end()) {
230         EdgeInformation[BB->getParent()][*ei] += MinimalWeight[*ei];
231         DEBUG(dbgs() << "Additionally " << format("%.20g",MinimalWeight[*ei]) << " at " << (*ei) << "\n");
232       }
233       printEdgeWeight(*ei);
234       
235       // Add minimal weight to paths to all exit edges, this is used to ensure
236       // that enough flow is reaching this edges.
237       Path p;
238       const BasicBlock *Dest = GetPath(BB, (*ei).first, p, GetPathToDest);
239       while (Dest != BB) {
240         const BasicBlock *Parent = p.find(Dest)->second;
241         Edge e = getEdge(Parent, Dest);
242         if (MinimalWeight.find(e) == MinimalWeight.end()) {
243           MinimalWeight[e] = 0;
244         }
245         MinimalWeight[e] += w;
246         DEBUG(dbgs() << "Minimal Weight for " << e << ": " << format("%.20g",MinimalWeight[e]) << "\n");
247         Dest = Parent;
248       }
249     }
250     // Increase flow into the loop.
251     BBWeight *= (ExecCount+1);
252   }
253
254   BlockInformation[BB->getParent()][BB] = BBWeight;
255   // Up until now we considered only the loop exiting edges, now we have a
256   // definite block weight and must distribute this onto the outgoing edges.
257   // Since there may be already flow attached to some of the edges, read this
258   // flow first and remember the edges that have still now flow attached.
259   Edges.clear();
260   std::set<BasicBlock*> ProcessedSuccs;
261
262   succ_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
263   // Also check for (BB,0) edges that may already contain some flow. (But only
264   // in case there are no successors.)
265   if (bbi == bbe) {
266     Edge edge = getEdge(BB,0);
267     EdgeInformation[BB->getParent()][edge] = BBWeight;
268     printEdgeWeight(edge);
269   }
270   for ( ; bbi != bbe; ++bbi ) {
271     if (ProcessedSuccs.insert(*bbi).second) {
272       Edge edge = getEdge(BB,*bbi);
273       double w = getEdgeWeight(edge);
274       if (w != MissingValue) {
275         BBWeight -= getEdgeWeight(edge);
276       } else {
277         Edges.push_back(edge);
278         // If minimal weight is necessary, reserve weight by subtracting weight
279         // from block weight, this is readded later on.
280         if (MinimalWeight.find(edge) != MinimalWeight.end()) {
281           BBWeight -= MinimalWeight[edge];
282           DEBUG(dbgs() << "Reserving " << format("%.20g",MinimalWeight[edge]) << " at " << edge << "\n");
283         }
284       }
285     }
286   }
287
288   double fraction = floor(BBWeight/Edges.size());
289   // Finally we know what flow is still not leaving the block, distribute this
290   // flow onto the empty edges.
291   for (SmallVector<Edge, 8>::iterator ei = Edges.begin(), ee = Edges.end();
292        ei != ee; ++ei) {
293     if (ei != (ee-1)) {
294       EdgeInformation[BB->getParent()][*ei] += fraction;
295       BBWeight -= fraction;
296     } else {
297       EdgeInformation[BB->getParent()][*ei] += BBWeight;
298     }
299     // Readd minial necessary weight.
300     if (MinimalWeight.find(*ei) != MinimalWeight.end()) {
301       EdgeInformation[BB->getParent()][*ei] += MinimalWeight[*ei];
302       DEBUG(dbgs() << "Additionally " << format("%.20g",MinimalWeight[*ei]) << " at " << (*ei) << "\n");
303     }
304     printEdgeWeight(*ei);
305   }
306
307   // This block is visited, mark this before the recursion.
308   BBToVisit.erase(BB);
309
310   // Recurse into successors.
311   for (succ_iterator bbi = succ_begin(BB), bbe = succ_end(BB);
312        bbi != bbe; ++bbi) {
313     recurseBasicBlock(*bbi);
314   }
315 }
316
317 bool ProfileEstimatorPass::runOnFunction(Function &F) {
318   if (F.isDeclaration()) return false;
319
320   // Fetch LoopInfo and clear ProfileInfo for this function.
321   LI = &getAnalysis<LoopInfo>();
322   FunctionInformation.erase(&F);
323   BlockInformation[&F].clear();
324   EdgeInformation[&F].clear();
325
326   // Mark all blocks as to visit.
327   for (Function::iterator bi = F.begin(), be = F.end(); bi != be; ++bi)
328     BBToVisit.insert(bi);
329
330   // Clear Minimal Edges.
331   MinimalWeight.clear();
332
333   DEBUG(dbgs() << "Working on function " << F.getNameStr() << "\n");
334
335   // Since the entry block is the first one and has no predecessors, the edge
336   // (0,entry) is inserted with the starting weight of 1.
337   BasicBlock *entry = &F.getEntryBlock();
338   BlockInformation[&F][entry] = pow(2.0, 32.0);
339   Edge edge = getEdge(0,entry);
340   EdgeInformation[&F][edge] = BlockInformation[&F][entry];
341   printEdgeWeight(edge);
342
343   // Since recurseBasicBlock() maybe returns with a block which was not fully
344   // estimated, use recurseBasicBlock() until everything is calculated.
345   bool cleanup = false;
346   recurseBasicBlock(entry);
347   while (BBToVisit.size() > 0 && !cleanup) {
348     // Remember number of open blocks, this is later used to check if progress
349     // was made.
350     unsigned size = BBToVisit.size();
351
352     // Try to calculate all blocks in turn.
353     for (std::set<BasicBlock*>::iterator bi = BBToVisit.begin(),
354          be = BBToVisit.end(); bi != be; ++bi) {
355       recurseBasicBlock(*bi);
356       // If at least one block was finished, break because iterator may be
357       // invalid.
358       if (BBToVisit.size() < size) break;
359     }
360
361     // If there was not a single block resolved, make some assumptions.
362     if (BBToVisit.size() == size) {
363       bool found = false;
364       for (std::set<BasicBlock*>::iterator BBI = BBToVisit.begin(), BBE = BBToVisit.end(); 
365            (BBI != BBE) && (!found); ++BBI) {
366         BasicBlock *BB = *BBI;
367         // Try each predecessor if it can be assumend.
368         for (pred_iterator bbi = pred_begin(BB), bbe = pred_end(BB);
369              (bbi != bbe) && (!found); ++bbi) {
370           Edge e = getEdge(*bbi,BB);
371           double w = getEdgeWeight(e);
372           // Check that edge from predecessor is still free.
373           if (w == MissingValue) {
374             // Check if there is a circle from this block to predecessor.
375             Path P;
376             const BasicBlock *Dest = GetPath(BB, *bbi, P, GetPathToDest);
377             if (Dest != *bbi) {
378               // If there is no circle, just set edge weight to 0
379               EdgeInformation[&F][e] = 0;
380               DEBUG(dbgs() << "Assuming edge weight: ");
381               printEdgeWeight(e);
382               found = true;
383             }
384           }
385         }
386       }
387       if (!found) {
388         cleanup = true;
389         DEBUG(dbgs() << "No assumption possible in Fuction "<<F.getName()<<", setting all to zero\n");
390       }
391     }
392   }
393   // In case there was no safe way to assume edges, set as a last measure, 
394   // set _everything_ to zero.
395   if (cleanup) {
396     FunctionInformation[&F] = 0;
397     BlockInformation[&F].clear();
398     EdgeInformation[&F].clear();
399     for (Function::const_iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
400       const BasicBlock *BB = &(*FI);
401       BlockInformation[&F][BB] = 0;
402       const_pred_iterator predi = pred_begin(BB), prede = pred_end(BB);
403       if (predi == prede) {
404         Edge e = getEdge(0,BB);
405         setEdgeWeight(e,0);
406       }
407       for (;predi != prede; ++predi) {
408         Edge e = getEdge(*predi,BB);
409         setEdgeWeight(e,0);
410       }
411       succ_const_iterator succi = succ_begin(BB), succe = succ_end(BB);
412       if (succi == succe) {
413         Edge e = getEdge(BB,0);
414         setEdgeWeight(e,0);
415       }
416       for (;succi != succe; ++succi) {
417         Edge e = getEdge(*succi,BB);
418         setEdgeWeight(e,0);
419       }
420     }
421   }
422
423   return false;
424 }