Add InEdges (edges from header to the loop) in Loop Branch Heuristics, so
[oota-llvm.git] / lib / Analysis / BranchProbabilityInfo.cpp
1 //===-- BranchProbabilityInfo.cpp - Branch Probability Analysis -*- C++ -*-===//
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 // Loops should be simplified before this analysis.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Instructions.h"
15 #include "llvm/Analysis/BranchProbabilityInfo.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Support/Debug.h"
18
19 using namespace llvm;
20
21 INITIALIZE_PASS_BEGIN(BranchProbabilityInfo, "branch-prob",
22                       "Branch Probability Analysis", false, true)
23 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
24 INITIALIZE_PASS_END(BranchProbabilityInfo, "branch-prob",
25                     "Branch Probability Analysis", false, true)
26
27 char BranchProbabilityInfo::ID = 0;
28
29 namespace {
30 // Please note that BranchProbabilityAnalysis is not a FunctionPass.
31 // It is created by BranchProbabilityInfo (which is a FunctionPass), which
32 // provides a clear interface. Thanks to that, all heuristics and other
33 // private methods are hidden in the .cpp file.
34 class BranchProbabilityAnalysis {
35
36   typedef std::pair<BasicBlock *, BasicBlock *> Edge;
37
38   DenseMap<Edge, uint32_t> *Weights;
39
40   BranchProbabilityInfo *BP;
41
42   LoopInfo *LI;
43
44
45   // Weights are for internal use only. They are used by heuristics to help to
46   // estimate edges' probability. Example:
47   //
48   // Using "Loop Branch Heuristics" we predict weights of edges for the
49   // block BB2.
50   //         ...
51   //          |
52   //          V
53   //         BB1<-+
54   //          |   |
55   //          |   | (Weight = 128)
56   //          V   |
57   //         BB2--+
58   //          |
59   //          | (Weight = 4)
60   //          V
61   //         BB3
62   //
63   // Probability of the edge BB2->BB1 = 128 / (128 + 4) = 0.9696..
64   // Probability of the edge BB2->BB3 = 4 / (128 + 4) = 0.0303..
65
66   static const uint32_t LBH_TAKEN_WEIGHT = 128;
67   static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
68
69   // Standard weight value. Used when none of the heuristics set weight for
70   // the edge.
71   static const uint32_t NORMAL_WEIGHT = 16;
72
73   // Minimum weight of an edge. Please note, that weight is NEVER 0.
74   static const uint32_t MIN_WEIGHT = 1;
75
76   // Return TRUE if BB leads directly to a Return Instruction.
77   static bool isReturningBlock(BasicBlock *BB) {
78     SmallPtrSet<BasicBlock *, 8> Visited;
79
80     while (true) {
81       TerminatorInst *TI = BB->getTerminator();
82       if (isa<ReturnInst>(TI))
83         return true;
84
85       if (TI->getNumSuccessors() > 1)
86         break;
87
88       // It is unreachable block which we can consider as a return instruction.
89       if (TI->getNumSuccessors() == 0)
90         return true;
91
92       Visited.insert(BB);
93       BB = TI->getSuccessor(0);
94
95       // Stop if cycle is detected.
96       if (Visited.count(BB))
97         return false;
98     }
99
100     return false;
101   }
102
103   // Multiply Edge Weight by two.
104   void incEdgeWeight(BasicBlock *Src, BasicBlock *Dst) {
105     uint32_t Weight = BP->getEdgeWeight(Src, Dst);
106     uint32_t MaxWeight = getMaxWeightFor(Src);
107
108     if (Weight * 2 > MaxWeight)
109       BP->setEdgeWeight(Src, Dst, MaxWeight);
110     else
111       BP->setEdgeWeight(Src, Dst, Weight * 2);
112   }
113
114   // Divide Edge Weight by two.
115   void decEdgeWeight(BasicBlock *Src, BasicBlock *Dst) {
116     uint32_t Weight = BP->getEdgeWeight(Src, Dst);
117
118     assert(Weight > 0);
119     if (Weight / 2 < MIN_WEIGHT)
120       BP->setEdgeWeight(Src, Dst, MIN_WEIGHT);
121     else
122       BP->setEdgeWeight(Src, Dst, Weight / 2);
123   }
124
125
126   uint32_t getMaxWeightFor(BasicBlock *BB) const {
127     return UINT32_MAX / BB->getTerminator()->getNumSuccessors();
128   }
129
130 public:
131   BranchProbabilityAnalysis(DenseMap<Edge, uint32_t> *W,
132                             BranchProbabilityInfo *BP, LoopInfo *LI)
133     : Weights(W), BP(BP), LI(LI) {
134   }
135
136   // Return Heuristics
137   void calcReturnHeuristics(BasicBlock *BB);
138
139   // Pointer Heuristics
140   void calcPointerHeuristics(BasicBlock *BB);
141
142   // Loop Branch Heuristics
143   void calcLoopBranchHeuristics(BasicBlock *BB);
144
145   bool runOnFunction(Function &F);
146 };
147 } // end anonymous namespace
148
149 // Calculate Edge Weights using "Return Heuristics". Predict a successor which
150 // leads directly to Return Instruction will not be taken.
151 void BranchProbabilityAnalysis::calcReturnHeuristics(BasicBlock *BB){
152   if (BB->getTerminator()->getNumSuccessors() == 1)
153     return;
154
155   for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
156     BasicBlock *Succ = *I;
157     if (isReturningBlock(Succ)) {
158       decEdgeWeight(BB, Succ);
159     }
160   }
161 }
162
163 // Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
164 // between two pointer or pointer and NULL will fail.
165 void BranchProbabilityAnalysis::calcPointerHeuristics(BasicBlock *BB) {
166   BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
167   if (!BI || !BI->isConditional())
168     return;
169
170   Value *Cond = BI->getCondition();
171   ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
172   if (!CI || !CI->isEquality())
173     return;
174
175   Value *LHS = CI->getOperand(0);
176
177   if (!LHS->getType()->isPointerTy())
178     return;
179
180   assert(CI->getOperand(1)->getType()->isPointerTy());
181
182   BasicBlock *Taken = BI->getSuccessor(0);
183   BasicBlock *NonTaken = BI->getSuccessor(1);
184
185   // p != 0   ->   isProb = true
186   // p == 0   ->   isProb = false
187   // p != q   ->   isProb = true
188   // p == q   ->   isProb = false;
189   bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
190   if (!isProb)
191     std::swap(Taken, NonTaken);
192
193   incEdgeWeight(BB, Taken);
194   decEdgeWeight(BB, NonTaken);
195 }
196
197 // Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
198 // as taken, exiting edges as not-taken.
199 void BranchProbabilityAnalysis::calcLoopBranchHeuristics(BasicBlock *BB) {
200   uint32_t numSuccs = BB->getTerminator()->getNumSuccessors();
201
202   Loop *L = LI->getLoopFor(BB);
203   if (!L)
204     return;
205
206   SmallVector<BasicBlock *, 8> BackEdges;
207   SmallVector<BasicBlock *, 8> ExitingEdges;
208   SmallVector<BasicBlock *, 8> InEdges; // Edges from header to the loop.
209
210   bool isHeader = BB == L->getHeader();
211
212   for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
213     BasicBlock *Succ = *I;
214     Loop *SuccL = LI->getLoopFor(Succ);
215     if (SuccL != L)
216       ExitingEdges.push_back(Succ);
217     else if (Succ == L->getHeader())
218       BackEdges.push_back(Succ);
219     else if (isHeader)
220       InEdges.push_back(Succ);
221   }
222
223   if (uint32_t numBackEdges = BackEdges.size()) {
224     uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges;
225     if (backWeight < NORMAL_WEIGHT)
226       backWeight = NORMAL_WEIGHT;
227
228     for (SmallVector<BasicBlock *, 8>::iterator EI = BackEdges.begin(),
229          EE = BackEdges.end(); EI != EE; ++EI) {
230       BasicBlock *Back = *EI;
231       BP->setEdgeWeight(BB, Back, backWeight);
232     }
233   }
234
235   if (uint32_t numInEdges = InEdges.size()) {
236     uint32_t inWeight = LBH_TAKEN_WEIGHT / numInEdges;
237     if (inWeight < NORMAL_WEIGHT)
238       inWeight = NORMAL_WEIGHT;
239
240     for (SmallVector<BasicBlock *, 8>::iterator EI = InEdges.begin(),
241          EE = InEdges.end(); EI != EE; ++EI) {
242       BasicBlock *Back = *EI;
243       BP->setEdgeWeight(BB, Back, inWeight);
244     }
245   }
246
247   uint32_t numExitingEdges = ExitingEdges.size();
248   if (uint32_t numNonExitingEdges = numSuccs - numExitingEdges) {
249     uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numNonExitingEdges;
250     if (exitWeight < MIN_WEIGHT)
251       exitWeight = MIN_WEIGHT;
252
253     for (SmallVector<BasicBlock *, 8>::iterator EI = ExitingEdges.begin(),
254          EE = ExitingEdges.end(); EI != EE; ++EI) {
255       BasicBlock *Exiting = *EI;
256       BP->setEdgeWeight(BB, Exiting, exitWeight);
257     }
258   }
259 }
260
261 bool BranchProbabilityAnalysis::runOnFunction(Function &F) {
262
263   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
264     BasicBlock *BB = I++;
265
266     // Only LBH uses setEdgeWeight method.
267     calcLoopBranchHeuristics(BB);
268
269     // PH and RH use only incEdgeWeight and decEwdgeWeight methods to
270     // not efface LBH results.
271     calcPointerHeuristics(BB);
272     calcReturnHeuristics(BB);
273   }
274
275   return false;
276 }
277
278 void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
279     AU.addRequired<LoopInfo>();
280     AU.setPreservesAll();
281 }
282
283 bool BranchProbabilityInfo::runOnFunction(Function &F) {
284   LoopInfo &LI = getAnalysis<LoopInfo>();
285   BranchProbabilityAnalysis BPA(&Weights, this, &LI);
286   return BPA.runOnFunction(F);
287 }
288
289 uint32_t BranchProbabilityInfo::getSumForBlock(BasicBlock *BB) const {
290   uint32_t Sum = 0;
291
292   for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
293     BasicBlock *Succ = *I;
294     uint32_t Weight = getEdgeWeight(BB, Succ);
295     uint32_t PrevSum = Sum;
296
297     Sum += Weight;
298     assert(Sum > PrevSum); (void) PrevSum;
299   }
300
301   return Sum;
302 }
303
304 bool BranchProbabilityInfo::isEdgeHot(BasicBlock *Src, BasicBlock *Dst) const {
305   // Hot probability is at least 4/5 = 80%
306   uint32_t Weight = getEdgeWeight(Src, Dst);
307   uint32_t Sum = getSumForBlock(Src);
308
309   // FIXME: Implement BranchProbability::compare then change this code to
310   // compare this BranchProbability against a static "hot" BranchProbability.
311   return (uint64_t)Weight * 5 > (uint64_t)Sum * 4;
312 }
313
314 BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
315   uint32_t Sum = 0;
316   uint32_t MaxWeight = 0;
317   BasicBlock *MaxSucc = 0;
318
319   for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
320     BasicBlock *Succ = *I;
321     uint32_t Weight = getEdgeWeight(BB, Succ);
322     uint32_t PrevSum = Sum;
323
324     Sum += Weight;
325     assert(Sum > PrevSum); (void) PrevSum;
326
327     if (Weight > MaxWeight) {
328       MaxWeight = Weight;
329       MaxSucc = Succ;
330     }
331   }
332
333   // FIXME: Use BranchProbability::compare.
334   if ((uint64_t)MaxWeight * 5 > (uint64_t)Sum * 4)
335     return MaxSucc;
336
337   return 0;
338 }
339
340 // Return edge's weight. If can't find it, return DEFAULT_WEIGHT value.
341 uint32_t
342 BranchProbabilityInfo::getEdgeWeight(BasicBlock *Src, BasicBlock *Dst) const {
343   Edge E(Src, Dst);
344   DenseMap<Edge, uint32_t>::const_iterator I = Weights.find(E);
345
346   if (I != Weights.end())
347     return I->second;
348
349   return DEFAULT_WEIGHT;
350 }
351
352 void BranchProbabilityInfo::setEdgeWeight(BasicBlock *Src, BasicBlock *Dst,
353                                      uint32_t Weight) {
354   Weights[std::make_pair(Src, Dst)] = Weight;
355   DEBUG(dbgs() << "set edge " << Src->getNameStr() << " -> "
356                << Dst->getNameStr() << " weight to " << Weight
357                << (isEdgeHot(Src, Dst) ? " [is HOT now]\n" : "\n"));
358 }
359
360
361 BranchProbability BranchProbabilityInfo::
362 getEdgeProbability(BasicBlock *Src, BasicBlock *Dst) const {
363
364   uint32_t N = getEdgeWeight(Src, Dst);
365   uint32_t D = getSumForBlock(Src);
366
367   return BranchProbability(N, D);
368 }
369
370 raw_ostream &
371 BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS, BasicBlock *Src,
372                                             BasicBlock *Dst) const {
373
374   const BranchProbability Prob = getEdgeProbability(Src, Dst);
375   OS << "edge " << Src->getNameStr() << " -> " << Dst->getNameStr()
376      << " probability is " << Prob
377      << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
378
379   return OS;
380 }