blob: 5ac2d814a00dbcc2ea7c5ce07e4bb0e686664ad7 [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
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};
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.
151void 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.
165void 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);
Jakub Staszakd7932ca2011-07-15 20:51:06 +0000172 if (!CI || !CI->isEquality())
Andrew Trick9e764222011-06-04 01:16:30 +0000173 return;
174
175 Value *LHS = CI->getOperand(0);
Andrew Trick9e764222011-06-04 01:16:30 +0000176
177 if (!LHS->getType()->isPointerTy())
178 return;
179
Nick Lewycky404b53e2011-06-04 02:07:10 +0000180 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick9e764222011-06-04 01:16:30 +0000181
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;
Jakub Staszakd7932ca2011-07-15 20:51:06 +0000189 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick9e764222011-06-04 01:16:30 +0000190 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.
199void BranchProbabilityAnalysis::calcLoopBranchHeuristics(BasicBlock *BB) {
Andrew Trickf289df22011-06-11 01:05:22 +0000200 uint32_t numSuccs = BB->getTerminator()->getNumSuccessors();
Andrew Trick9e764222011-06-04 01:16:30 +0000201
202 Loop *L = LI->getLoopFor(BB);
203 if (!L)
204 return;
205
206 SmallVector<BasicBlock *, 8> BackEdges;
207 SmallVector<BasicBlock *, 8> ExitingEdges;
Jakub Staszakfa447252011-07-28 21:33:46 +0000208 SmallVector<BasicBlock *, 8> InEdges; // Edges from header to the loop.
209
210 bool isHeader = BB == L->getHeader();
Andrew Trick9e764222011-06-04 01:16:30 +0000211
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);
Jakub Staszakfa447252011-07-28 21:33:46 +0000219 else if (isHeader)
220 InEdges.push_back(Succ);
Andrew Trick9e764222011-06-04 01:16:30 +0000221 }
222
Andrew Trickf289df22011-06-11 01:05:22 +0000223 if (uint32_t numBackEdges = BackEdges.size()) {
224 uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000225 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
Jakub Staszakfa447252011-07-28 21:33:46 +0000235 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
Andrew Trickf289df22011-06-11 01:05:22 +0000247 uint32_t numExitingEdges = ExitingEdges.size();
248 if (uint32_t numNonExitingEdges = numSuccs - numExitingEdges) {
249 uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numNonExitingEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000250 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
261bool 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
Jakub Staszak12af93a2011-07-16 20:31:15 +0000278void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
279 AU.addRequired<LoopInfo>();
280 AU.setPreservesAll();
281}
Andrew Trick9e764222011-06-04 01:16:30 +0000282
283bool BranchProbabilityInfo::runOnFunction(Function &F) {
284 LoopInfo &LI = getAnalysis<LoopInfo>();
285 BranchProbabilityAnalysis BPA(&Weights, this, &LI);
Andrew Trickf289df22011-06-11 01:05:22 +0000286 return BPA.runOnFunction(F);
Andrew Trick9e764222011-06-04 01:16:30 +0000287}
288
Andrew Trickf289df22011-06-11 01:05:22 +0000289uint32_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) {
Andrew Trick9e764222011-06-04 01:16:30 +0000293 BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000294 uint32_t Weight = getEdgeWeight(BB, Succ);
295 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000296
297 Sum += Weight;
298 assert(Sum > PrevSum); (void) PrevSum;
299 }
300
Andrew Trickf289df22011-06-11 01:05:22 +0000301 return Sum;
302}
303
304bool 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;
Andrew Trick9e764222011-06-04 01:16:30 +0000312}
313
314BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000315 uint32_t Sum = 0;
316 uint32_t MaxWeight = 0;
Andrew Trick9e764222011-06-04 01:16:30 +0000317 BasicBlock *MaxSucc = 0;
318
319 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
320 BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000321 uint32_t Weight = getEdgeWeight(BB, Succ);
322 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000323
324 Sum += Weight;
325 assert(Sum > PrevSum); (void) PrevSum;
326
327 if (Weight > MaxWeight) {
328 MaxWeight = Weight;
329 MaxSucc = Succ;
330 }
331 }
332
Andrew Trickf289df22011-06-11 01:05:22 +0000333 // FIXME: Use BranchProbability::compare.
334 if ((uint64_t)MaxWeight * 5 > (uint64_t)Sum * 4)
Andrew Trick9e764222011-06-04 01:16:30 +0000335 return MaxSucc;
336
337 return 0;
338}
339
340// Return edge's weight. If can't find it, return DEFAULT_WEIGHT value.
Andrew Trickf289df22011-06-11 01:05:22 +0000341uint32_t
Andrew Trick9e764222011-06-04 01:16:30 +0000342BranchProbabilityInfo::getEdgeWeight(BasicBlock *Src, BasicBlock *Dst) const {
343 Edge E(Src, Dst);
Andrew Trickf289df22011-06-11 01:05:22 +0000344 DenseMap<Edge, uint32_t>::const_iterator I = Weights.find(E);
Andrew Trick9e764222011-06-04 01:16:30 +0000345
346 if (I != Weights.end())
347 return I->second;
348
349 return DEFAULT_WEIGHT;
350}
351
352void BranchProbabilityInfo::setEdgeWeight(BasicBlock *Src, BasicBlock *Dst,
Andrew Trickf289df22011-06-11 01:05:22 +0000353 uint32_t Weight) {
Andrew Trick9e764222011-06-04 01:16:30 +0000354 Weights[std::make_pair(Src, Dst)] = Weight;
Andrew Trickf289df22011-06-11 01:05:22 +0000355 DEBUG(dbgs() << "set edge " << Src->getNameStr() << " -> "
356 << Dst->getNameStr() << " weight to " << Weight
357 << (isEdgeHot(Src, Dst) ? " [is HOT now]\n" : "\n"));
358}
359
360
361BranchProbability BranchProbabilityInfo::
362getEdgeProbability(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);
Andrew Trick9e764222011-06-04 01:16:30 +0000368}
369
370raw_ostream &
371BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS, BasicBlock *Src,
Andrew Trickf289df22011-06-11 01:05:22 +0000372 BasicBlock *Dst) const {
Andrew Trick9e764222011-06-04 01:16:30 +0000373
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000374 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Andrew Trickf289df22011-06-11 01:05:22 +0000375 OS << "edge " << Src->getNameStr() << " -> " << Dst->getNameStr()
376 << " probability is " << Prob
377 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick9e764222011-06-04 01:16:30 +0000378
379 return OS;
380}