blob: 527a4ecbd88a0111da0ee2626639355691039d96 [file] [log] [blame]
Andrew Trick9e764222011-06-04 01:16:30 +00001//===-- 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"
Jakub Staszak12af93a2011-07-16 20:31:15 +000016#include "llvm/Analysis/LoopInfo.h"
Andrew Trickf289df22011-06-11 01:05:22 +000017#include "llvm/Support/Debug.h"
Andrew Trick9e764222011-06-04 01:16:30 +000018
19using namespace llvm;
20
21INITIALIZE_PASS_BEGIN(BranchProbabilityInfo, "branch-prob",
22 "Branch Probability Analysis", false, true)
23INITIALIZE_PASS_DEPENDENCY(LoopInfo)
24INITIALIZE_PASS_END(BranchProbabilityInfo, "branch-prob",
25 "Branch Probability Analysis", false, true)
26
27char BranchProbabilityInfo::ID = 0;
28
Benjamin Kramerafa88ea2011-06-13 18:38:56 +000029namespace {
Andrew Trick9e764222011-06-04 01:16:30 +000030// 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.
34class BranchProbabilityAnalysis {
35
36 typedef std::pair<BasicBlock *, BasicBlock *> Edge;
37
Andrew Trickf289df22011-06-11 01:05:22 +000038 DenseMap<Edge, uint32_t> *Weights;
Andrew Trick9e764222011-06-04 01:16:30 +000039
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
Andrew Trickf289df22011-06-11 01:05:22 +000066 static const uint32_t LBH_TAKEN_WEIGHT = 128;
67 static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
Andrew Trick9e764222011-06-04 01:16:30 +000068
69 // Standard weight value. Used when none of the heuristics set weight for
70 // the edge.
Andrew Trickf289df22011-06-11 01:05:22 +000071 static const uint32_t NORMAL_WEIGHT = 16;
Andrew Trick9e764222011-06-04 01:16:30 +000072
73 // Minimum weight of an edge. Please note, that weight is NEVER 0.
Andrew Trickf289df22011-06-11 01:05:22 +000074 static const uint32_t MIN_WEIGHT = 1;
Andrew Trick9e764222011-06-04 01:16:30 +000075
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) {
Andrew Trickf289df22011-06-11 01:05:22 +0000105 uint32_t Weight = BP->getEdgeWeight(Src, Dst);
106 uint32_t MaxWeight = getMaxWeightFor(Src);
Andrew Trick9e764222011-06-04 01:16:30 +0000107
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) {
Andrew Trickf289df22011-06-11 01:05:22 +0000116 uint32_t Weight = BP->getEdgeWeight(Src, Dst);
Andrew Trick9e764222011-06-04 01:16:30 +0000117
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
Andrew Trickf289df22011-06-11 01:05:22 +0000126 uint32_t getMaxWeightFor(BasicBlock *BB) const {
127 return UINT32_MAX / BB->getTerminator()->getNumSuccessors();
Andrew Trick9e764222011-06-04 01:16:30 +0000128 }
129
130public:
Andrew Trickf289df22011-06-11 01:05:22 +0000131 BranchProbabilityAnalysis(DenseMap<Edge, uint32_t> *W,
Andrew Trick9e764222011-06-04 01:16:30 +0000132 BranchProbabilityInfo *BP, LoopInfo *LI)
133 : Weights(W), BP(BP), LI(LI) {
134 }
135
136 // Return Heuristics
Jakub Staszak7241caf2011-07-28 21:45:07 +0000137 bool calcReturnHeuristics(BasicBlock *BB);
Andrew Trick9e764222011-06-04 01:16:30 +0000138
139 // Pointer Heuristics
Jakub Staszak7241caf2011-07-28 21:45:07 +0000140 bool calcPointerHeuristics(BasicBlock *BB);
Andrew Trick9e764222011-06-04 01:16:30 +0000141
142 // Loop Branch Heuristics
Jakub Staszak7241caf2011-07-28 21:45:07 +0000143 bool calcLoopBranchHeuristics(BasicBlock *BB);
Andrew Trick9e764222011-06-04 01:16:30 +0000144
145 bool runOnFunction(Function &F);
146};
Benjamin Kramerafa88ea2011-06-13 18:38:56 +0000147} // end anonymous namespace
Andrew Trick9e764222011-06-04 01:16:30 +0000148
149// Calculate Edge Weights using "Return Heuristics". Predict a successor which
150// leads directly to Return Instruction will not be taken.
Jakub Staszak7241caf2011-07-28 21:45:07 +0000151bool BranchProbabilityAnalysis::calcReturnHeuristics(BasicBlock *BB){
Andrew Trick9e764222011-06-04 01:16:30 +0000152 if (BB->getTerminator()->getNumSuccessors() == 1)
Jakub Staszak7241caf2011-07-28 21:45:07 +0000153 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000154
Jakub Staszak7241caf2011-07-28 21:45:07 +0000155 bool Any = false;
Andrew Trick9e764222011-06-04 01:16:30 +0000156 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
157 BasicBlock *Succ = *I;
158 if (isReturningBlock(Succ)) {
159 decEdgeWeight(BB, Succ);
Jakub Staszak7241caf2011-07-28 21:45:07 +0000160 Any = true;
Andrew Trick9e764222011-06-04 01:16:30 +0000161 }
162 }
Jakub Staszak7241caf2011-07-28 21:45:07 +0000163
164 return Any;
Andrew Trick9e764222011-06-04 01:16:30 +0000165}
166
167// Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
168// between two pointer or pointer and NULL will fail.
Jakub Staszak7241caf2011-07-28 21:45:07 +0000169bool BranchProbabilityAnalysis::calcPointerHeuristics(BasicBlock *BB) {
Andrew Trick9e764222011-06-04 01:16:30 +0000170 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
171 if (!BI || !BI->isConditional())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000172 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000173
174 Value *Cond = BI->getCondition();
175 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakd7932ca2011-07-15 20:51:06 +0000176 if (!CI || !CI->isEquality())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000177 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000178
179 Value *LHS = CI->getOperand(0);
Andrew Trick9e764222011-06-04 01:16:30 +0000180
181 if (!LHS->getType()->isPointerTy())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000182 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000183
Nick Lewycky404b53e2011-06-04 02:07:10 +0000184 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick9e764222011-06-04 01:16:30 +0000185
186 BasicBlock *Taken = BI->getSuccessor(0);
187 BasicBlock *NonTaken = BI->getSuccessor(1);
188
189 // p != 0 -> isProb = true
190 // p == 0 -> isProb = false
191 // p != q -> isProb = true
192 // p == q -> isProb = false;
Jakub Staszakd7932ca2011-07-15 20:51:06 +0000193 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick9e764222011-06-04 01:16:30 +0000194 if (!isProb)
195 std::swap(Taken, NonTaken);
196
197 incEdgeWeight(BB, Taken);
198 decEdgeWeight(BB, NonTaken);
Jakub Staszak7241caf2011-07-28 21:45:07 +0000199 return true;
Andrew Trick9e764222011-06-04 01:16:30 +0000200}
201
202// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
203// as taken, exiting edges as not-taken.
Jakub Staszak7241caf2011-07-28 21:45:07 +0000204bool BranchProbabilityAnalysis::calcLoopBranchHeuristics(BasicBlock *BB) {
Andrew Trickf289df22011-06-11 01:05:22 +0000205 uint32_t numSuccs = BB->getTerminator()->getNumSuccessors();
Andrew Trick9e764222011-06-04 01:16:30 +0000206
207 Loop *L = LI->getLoopFor(BB);
208 if (!L)
Jakub Staszak7241caf2011-07-28 21:45:07 +0000209 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000210
211 SmallVector<BasicBlock *, 8> BackEdges;
212 SmallVector<BasicBlock *, 8> ExitingEdges;
Jakub Staszakfa447252011-07-28 21:33:46 +0000213 SmallVector<BasicBlock *, 8> InEdges; // Edges from header to the loop.
214
215 bool isHeader = BB == L->getHeader();
Andrew Trick9e764222011-06-04 01:16:30 +0000216
217 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
218 BasicBlock *Succ = *I;
219 Loop *SuccL = LI->getLoopFor(Succ);
220 if (SuccL != L)
221 ExitingEdges.push_back(Succ);
222 else if (Succ == L->getHeader())
223 BackEdges.push_back(Succ);
Jakub Staszakfa447252011-07-28 21:33:46 +0000224 else if (isHeader)
225 InEdges.push_back(Succ);
Andrew Trick9e764222011-06-04 01:16:30 +0000226 }
227
Andrew Trickf289df22011-06-11 01:05:22 +0000228 if (uint32_t numBackEdges = BackEdges.size()) {
229 uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000230 if (backWeight < NORMAL_WEIGHT)
231 backWeight = NORMAL_WEIGHT;
232
233 for (SmallVector<BasicBlock *, 8>::iterator EI = BackEdges.begin(),
234 EE = BackEdges.end(); EI != EE; ++EI) {
235 BasicBlock *Back = *EI;
236 BP->setEdgeWeight(BB, Back, backWeight);
237 }
238 }
239
Jakub Staszakfa447252011-07-28 21:33:46 +0000240 if (uint32_t numInEdges = InEdges.size()) {
241 uint32_t inWeight = LBH_TAKEN_WEIGHT / numInEdges;
242 if (inWeight < NORMAL_WEIGHT)
243 inWeight = NORMAL_WEIGHT;
244
245 for (SmallVector<BasicBlock *, 8>::iterator EI = InEdges.begin(),
246 EE = InEdges.end(); EI != EE; ++EI) {
247 BasicBlock *Back = *EI;
248 BP->setEdgeWeight(BB, Back, inWeight);
249 }
250 }
251
Andrew Trickf289df22011-06-11 01:05:22 +0000252 uint32_t numExitingEdges = ExitingEdges.size();
253 if (uint32_t numNonExitingEdges = numSuccs - numExitingEdges) {
254 uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numNonExitingEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000255 if (exitWeight < MIN_WEIGHT)
256 exitWeight = MIN_WEIGHT;
257
258 for (SmallVector<BasicBlock *, 8>::iterator EI = ExitingEdges.begin(),
259 EE = ExitingEdges.end(); EI != EE; ++EI) {
260 BasicBlock *Exiting = *EI;
261 BP->setEdgeWeight(BB, Exiting, exitWeight);
262 }
263 }
Jakub Staszak7241caf2011-07-28 21:45:07 +0000264
265 return true;
Andrew Trick9e764222011-06-04 01:16:30 +0000266}
267
268bool BranchProbabilityAnalysis::runOnFunction(Function &F) {
269
270 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
271 BasicBlock *BB = I++;
272
273 // Only LBH uses setEdgeWeight method.
Jakub Staszak7241caf2011-07-28 21:45:07 +0000274 if (calcLoopBranchHeuristics(BB))
275 continue;
Andrew Trick9e764222011-06-04 01:16:30 +0000276
277 // PH and RH use only incEdgeWeight and decEwdgeWeight methods to
278 // not efface LBH results.
Jakub Staszak7241caf2011-07-28 21:45:07 +0000279 if (calcReturnHeuristics(BB))
280 continue;
281
Andrew Trick9e764222011-06-04 01:16:30 +0000282 calcPointerHeuristics(BB);
Andrew Trick9e764222011-06-04 01:16:30 +0000283 }
284
285 return false;
286}
287
Jakub Staszak12af93a2011-07-16 20:31:15 +0000288void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
289 AU.addRequired<LoopInfo>();
290 AU.setPreservesAll();
291}
Andrew Trick9e764222011-06-04 01:16:30 +0000292
293bool BranchProbabilityInfo::runOnFunction(Function &F) {
294 LoopInfo &LI = getAnalysis<LoopInfo>();
295 BranchProbabilityAnalysis BPA(&Weights, this, &LI);
Andrew Trickf289df22011-06-11 01:05:22 +0000296 return BPA.runOnFunction(F);
Andrew Trick9e764222011-06-04 01:16:30 +0000297}
298
Andrew Trickf289df22011-06-11 01:05:22 +0000299uint32_t BranchProbabilityInfo::getSumForBlock(BasicBlock *BB) const {
300 uint32_t Sum = 0;
301
302 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Andrew Trick9e764222011-06-04 01:16:30 +0000303 BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000304 uint32_t Weight = getEdgeWeight(BB, Succ);
305 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000306
307 Sum += Weight;
308 assert(Sum > PrevSum); (void) PrevSum;
309 }
310
Andrew Trickf289df22011-06-11 01:05:22 +0000311 return Sum;
312}
313
314bool BranchProbabilityInfo::isEdgeHot(BasicBlock *Src, BasicBlock *Dst) const {
315 // Hot probability is at least 4/5 = 80%
316 uint32_t Weight = getEdgeWeight(Src, Dst);
317 uint32_t Sum = getSumForBlock(Src);
318
319 // FIXME: Implement BranchProbability::compare then change this code to
320 // compare this BranchProbability against a static "hot" BranchProbability.
321 return (uint64_t)Weight * 5 > (uint64_t)Sum * 4;
Andrew Trick9e764222011-06-04 01:16:30 +0000322}
323
324BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000325 uint32_t Sum = 0;
326 uint32_t MaxWeight = 0;
Andrew Trick9e764222011-06-04 01:16:30 +0000327 BasicBlock *MaxSucc = 0;
328
329 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
330 BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000331 uint32_t Weight = getEdgeWeight(BB, Succ);
332 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000333
334 Sum += Weight;
335 assert(Sum > PrevSum); (void) PrevSum;
336
337 if (Weight > MaxWeight) {
338 MaxWeight = Weight;
339 MaxSucc = Succ;
340 }
341 }
342
Andrew Trickf289df22011-06-11 01:05:22 +0000343 // FIXME: Use BranchProbability::compare.
344 if ((uint64_t)MaxWeight * 5 > (uint64_t)Sum * 4)
Andrew Trick9e764222011-06-04 01:16:30 +0000345 return MaxSucc;
346
347 return 0;
348}
349
350// Return edge's weight. If can't find it, return DEFAULT_WEIGHT value.
Andrew Trickf289df22011-06-11 01:05:22 +0000351uint32_t
Andrew Trick9e764222011-06-04 01:16:30 +0000352BranchProbabilityInfo::getEdgeWeight(BasicBlock *Src, BasicBlock *Dst) const {
353 Edge E(Src, Dst);
Andrew Trickf289df22011-06-11 01:05:22 +0000354 DenseMap<Edge, uint32_t>::const_iterator I = Weights.find(E);
Andrew Trick9e764222011-06-04 01:16:30 +0000355
356 if (I != Weights.end())
357 return I->second;
358
359 return DEFAULT_WEIGHT;
360}
361
362void BranchProbabilityInfo::setEdgeWeight(BasicBlock *Src, BasicBlock *Dst,
Andrew Trickf289df22011-06-11 01:05:22 +0000363 uint32_t Weight) {
Andrew Trick9e764222011-06-04 01:16:30 +0000364 Weights[std::make_pair(Src, Dst)] = Weight;
Andrew Trickf289df22011-06-11 01:05:22 +0000365 DEBUG(dbgs() << "set edge " << Src->getNameStr() << " -> "
366 << Dst->getNameStr() << " weight to " << Weight
367 << (isEdgeHot(Src, Dst) ? " [is HOT now]\n" : "\n"));
368}
369
370
371BranchProbability BranchProbabilityInfo::
372getEdgeProbability(BasicBlock *Src, BasicBlock *Dst) const {
373
374 uint32_t N = getEdgeWeight(Src, Dst);
375 uint32_t D = getSumForBlock(Src);
376
377 return BranchProbability(N, D);
Andrew Trick9e764222011-06-04 01:16:30 +0000378}
379
380raw_ostream &
381BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS, BasicBlock *Src,
Andrew Trickf289df22011-06-11 01:05:22 +0000382 BasicBlock *Dst) const {
Andrew Trick9e764222011-06-04 01:16:30 +0000383
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000384 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Andrew Trickf289df22011-06-11 01:05:22 +0000385 OS << "edge " << Src->getNameStr() << " -> " << Dst->getNameStr()
386 << " probability is " << Prob
387 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick9e764222011-06-04 01:16:30 +0000388
389 return OS;
390}