blob: 04a6560262cb3cc70ac759ce60c8ba0b4d13843e [file] [log] [blame]
Bill Wendling0c34ae82012-08-15 12:22:35 +00001//===-- BranchProbabilityInfo.cpp - Branch Probability Analysis -----------===//
Andrew Trick9e764222011-06-04 01:16:30 +00002//
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
Jakub Staszaka5dd5502011-07-31 03:27:24 +000014#include "llvm/Constants.h"
Chandler Carruth14edd312011-10-23 21:21:50 +000015#include "llvm/Function.h"
Andrew Trick9e764222011-06-04 01:16:30 +000016#include "llvm/Instructions.h"
Chandler Carruth99d01c52011-10-19 10:30:30 +000017#include "llvm/LLVMContext.h"
18#include "llvm/Metadata.h"
Andrew Trick9e764222011-06-04 01:16:30 +000019#include "llvm/Analysis/BranchProbabilityInfo.h"
Jakub Staszak12af93a2011-07-16 20:31:15 +000020#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthde1c9bb2011-10-24 12:01:08 +000021#include "llvm/ADT/PostOrderIterator.h"
Chandler Carruth14edd312011-10-23 21:21:50 +000022#include "llvm/Support/CFG.h"
Andrew Trickf289df22011-06-11 01:05:22 +000023#include "llvm/Support/Debug.h"
Andrew Trick9e764222011-06-04 01:16:30 +000024
25using namespace llvm;
26
27INITIALIZE_PASS_BEGIN(BranchProbabilityInfo, "branch-prob",
28 "Branch Probability Analysis", false, true)
29INITIALIZE_PASS_DEPENDENCY(LoopInfo)
30INITIALIZE_PASS_END(BranchProbabilityInfo, "branch-prob",
31 "Branch Probability Analysis", false, true)
32
33char BranchProbabilityInfo::ID = 0;
34
Chandler Carruthb068bbba2011-10-24 01:40:45 +000035// Weights are for internal use only. They are used by heuristics to help to
36// estimate edges' probability. Example:
37//
38// Using "Loop Branch Heuristics" we predict weights of edges for the
39// block BB2.
40// ...
41// |
42// V
43// BB1<-+
44// | |
45// | | (Weight = 124)
46// V |
47// BB2--+
48// |
49// | (Weight = 4)
50// V
51// BB3
52//
53// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
54// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
55static const uint32_t LBH_TAKEN_WEIGHT = 124;
56static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
Andrew Trick9e764222011-06-04 01:16:30 +000057
Chandler Carruthde1c9bb2011-10-24 12:01:08 +000058/// \brief Unreachable-terminating branch taken weight.
59///
60/// This is the weight for a branch being taken to a block that terminates
61/// (eventually) in unreachable. These are predicted as unlikely as possible.
62static const uint32_t UR_TAKEN_WEIGHT = 1;
63
64/// \brief Unreachable-terminating branch not-taken weight.
65///
66/// This is the weight for a branch not being taken toward a block that
67/// terminates (eventually) in unreachable. Such a branch is essentially never
Chandler Carruth51f40a72011-12-22 09:26:37 +000068/// taken. Set the weight to an absurdly high value so that nested loops don't
69/// easily subsume it.
70static const uint32_t UR_NONTAKEN_WEIGHT = 1024*1024 - 1;
Andrew Trick9e764222011-06-04 01:16:30 +000071
Chandler Carruthb068bbba2011-10-24 01:40:45 +000072static const uint32_t PH_TAKEN_WEIGHT = 20;
73static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick9e764222011-06-04 01:16:30 +000074
Chandler Carruthb068bbba2011-10-24 01:40:45 +000075static const uint32_t ZH_TAKEN_WEIGHT = 20;
76static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick9e764222011-06-04 01:16:30 +000077
Chandler Carruthb068bbba2011-10-24 01:40:45 +000078static const uint32_t FPH_TAKEN_WEIGHT = 20;
79static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick9e764222011-06-04 01:16:30 +000080
Bill Wendling0c34ae82012-08-15 12:22:35 +000081/// \brief Invoke-terminating normal branch taken weight
82///
83/// This is the weight for branching to the normal destination of an invoke
84/// instruction. We expect this to happen most of the time. Set the weight to an
85/// absurdly high value so that nested loops subsume it.
86static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
87
88/// \brief Invoke-terminating normal branch not-taken weight.
89///
90/// This is the weight for branching to the unwind destination of an invoke
91/// instruction. This is essentially never taken.
92static const uint32_t IH_NONTAKEN_WEIGHT = 1;
93
Chandler Carruthb068bbba2011-10-24 01:40:45 +000094// Standard weight value. Used when none of the heuristics set weight for
95// the edge.
96static const uint32_t NORMAL_WEIGHT = 16;
Andrew Trick9e764222011-06-04 01:16:30 +000097
Chandler Carruthb068bbba2011-10-24 01:40:45 +000098// Minimum weight of an edge. Please note, that weight is NEVER 0.
99static const uint32_t MIN_WEIGHT = 1;
Andrew Trick9e764222011-06-04 01:16:30 +0000100
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000101static uint32_t getMaxWeightFor(BasicBlock *BB) {
102 return UINT32_MAX / BB->getTerminator()->getNumSuccessors();
103}
Andrew Trick9e764222011-06-04 01:16:30 +0000104
Andrew Trick9e764222011-06-04 01:16:30 +0000105
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000106/// \brief Calculate edge weights for successors lead to unreachable.
107///
108/// Predict that a successor which leads necessarily to an
109/// unreachable-terminated block as extremely unlikely.
110bool BranchProbabilityInfo::calcUnreachableHeuristics(BasicBlock *BB) {
111 TerminatorInst *TI = BB->getTerminator();
112 if (TI->getNumSuccessors() == 0) {
113 if (isa<UnreachableInst>(TI))
114 PostDominatedByUnreachable.insert(BB);
115 return false;
116 }
117
Manman Ren1a710fd2012-08-24 18:14:27 +0000118 SmallVector<unsigned, 4> UnreachableEdges;
119 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000120
121 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
122 if (PostDominatedByUnreachable.count(*I))
Manman Ren1a710fd2012-08-24 18:14:27 +0000123 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000124 else
Manman Ren1a710fd2012-08-24 18:14:27 +0000125 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000126 }
127
128 // If all successors are in the set of blocks post-dominated by unreachable,
129 // this block is too.
130 if (UnreachableEdges.size() == TI->getNumSuccessors())
131 PostDominatedByUnreachable.insert(BB);
132
133 // Skip probabilities if this block has a single successor or if all were
134 // reachable.
135 if (TI->getNumSuccessors() == 1 || UnreachableEdges.empty())
136 return false;
137
138 uint32_t UnreachableWeight =
Manman Ren1a710fd2012-08-24 18:14:27 +0000139 std::max(UR_TAKEN_WEIGHT / (unsigned)UnreachableEdges.size(), MIN_WEIGHT);
140 for (SmallVector<unsigned, 4>::iterator I = UnreachableEdges.begin(),
141 E = UnreachableEdges.end();
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000142 I != E; ++I)
143 setEdgeWeight(BB, *I, UnreachableWeight);
144
145 if (ReachableEdges.empty())
146 return true;
147 uint32_t ReachableWeight =
Manman Ren1a710fd2012-08-24 18:14:27 +0000148 std::max(UR_NONTAKEN_WEIGHT / (unsigned)ReachableEdges.size(),
149 NORMAL_WEIGHT);
150 for (SmallVector<unsigned, 4>::iterator I = ReachableEdges.begin(),
151 E = ReachableEdges.end();
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000152 I != E; ++I)
153 setEdgeWeight(BB, *I, ReachableWeight);
154
155 return true;
156}
157
Chandler Carruth99d01c52011-10-19 10:30:30 +0000158// Propagate existing explicit probabilities from either profile data or
159// 'expect' intrinsic processing.
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000160bool BranchProbabilityInfo::calcMetadataWeights(BasicBlock *BB) {
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000161 TerminatorInst *TI = BB->getTerminator();
162 if (TI->getNumSuccessors() == 1)
163 return false;
164 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
Chandler Carruth99d01c52011-10-19 10:30:30 +0000165 return false;
166
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000167 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
168 if (!WeightsNode)
Chandler Carruth99d01c52011-10-19 10:30:30 +0000169 return false;
170
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000171 // Ensure there are weights for all of the successors. Note that the first
172 // operand to the metadata node is a name, not a weight.
173 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruth99d01c52011-10-19 10:30:30 +0000174 return false;
175
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000176 // Build up the final weights that will be used in a temporary buffer, but
177 // don't add them until all weihts are present. Each weight value is clamped
178 // to [1, getMaxWeightFor(BB)].
Chandler Carruth99d01c52011-10-19 10:30:30 +0000179 uint32_t WeightLimit = getMaxWeightFor(BB);
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000180 SmallVector<uint32_t, 2> Weights;
181 Weights.reserve(TI->getNumSuccessors());
182 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
183 ConstantInt *Weight = dyn_cast<ConstantInt>(WeightsNode->getOperand(i));
184 if (!Weight)
185 return false;
186 Weights.push_back(
187 std::max<uint32_t>(1, Weight->getLimitedValue(WeightLimit)));
188 }
189 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
190 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Manman Ren1a710fd2012-08-24 18:14:27 +0000191 setEdgeWeight(BB, i, Weights[i]);
Chandler Carruth99d01c52011-10-19 10:30:30 +0000192
193 return true;
194}
195
Andrew Trick9e764222011-06-04 01:16:30 +0000196// Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
197// between two pointer or pointer and NULL will fail.
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000198bool BranchProbabilityInfo::calcPointerHeuristics(BasicBlock *BB) {
Andrew Trick9e764222011-06-04 01:16:30 +0000199 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
200 if (!BI || !BI->isConditional())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000201 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000202
203 Value *Cond = BI->getCondition();
204 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakd7932ca2011-07-15 20:51:06 +0000205 if (!CI || !CI->isEquality())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000206 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000207
208 Value *LHS = CI->getOperand(0);
Andrew Trick9e764222011-06-04 01:16:30 +0000209
210 if (!LHS->getType()->isPointerTy())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000211 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000212
Nick Lewycky404b53e2011-06-04 02:07:10 +0000213 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick9e764222011-06-04 01:16:30 +0000214
Andrew Trick9e764222011-06-04 01:16:30 +0000215 // p != 0 -> isProb = true
216 // p == 0 -> isProb = false
217 // p != q -> isProb = true
218 // p == q -> isProb = false;
Manman Ren1a710fd2012-08-24 18:14:27 +0000219 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszakd7932ca2011-07-15 20:51:06 +0000220 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick9e764222011-06-04 01:16:30 +0000221 if (!isProb)
Manman Ren1a710fd2012-08-24 18:14:27 +0000222 std::swap(TakenIdx, NonTakenIdx);
Andrew Trick9e764222011-06-04 01:16:30 +0000223
Manman Ren1a710fd2012-08-24 18:14:27 +0000224 setEdgeWeight(BB, TakenIdx, PH_TAKEN_WEIGHT);
225 setEdgeWeight(BB, NonTakenIdx, PH_NONTAKEN_WEIGHT);
Jakub Staszak7241caf2011-07-28 21:45:07 +0000226 return true;
Andrew Trick9e764222011-06-04 01:16:30 +0000227}
228
229// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
230// as taken, exiting edges as not-taken.
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000231bool BranchProbabilityInfo::calcLoopBranchHeuristics(BasicBlock *BB) {
Andrew Trick9e764222011-06-04 01:16:30 +0000232 Loop *L = LI->getLoopFor(BB);
233 if (!L)
Jakub Staszak7241caf2011-07-28 21:45:07 +0000234 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000235
Manman Ren1a710fd2012-08-24 18:14:27 +0000236 SmallVector<unsigned, 8> BackEdges;
237 SmallVector<unsigned, 8> ExitingEdges;
238 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
Jakub Staszakfa447252011-07-28 21:33:46 +0000239
Andrew Trick9e764222011-06-04 01:16:30 +0000240 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Chandler Carruth45baf6b2011-10-25 09:47:41 +0000241 if (!L->contains(*I))
Manman Ren1a710fd2012-08-24 18:14:27 +0000242 ExitingEdges.push_back(I.getSuccessorIndex());
Chandler Carruth45baf6b2011-10-25 09:47:41 +0000243 else if (L->getHeader() == *I)
Manman Ren1a710fd2012-08-24 18:14:27 +0000244 BackEdges.push_back(I.getSuccessorIndex());
Chandler Carruth45baf6b2011-10-25 09:47:41 +0000245 else
Manman Ren1a710fd2012-08-24 18:14:27 +0000246 InEdges.push_back(I.getSuccessorIndex());
Andrew Trick9e764222011-06-04 01:16:30 +0000247 }
248
Andrew Trickf289df22011-06-11 01:05:22 +0000249 if (uint32_t numBackEdges = BackEdges.size()) {
250 uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000251 if (backWeight < NORMAL_WEIGHT)
252 backWeight = NORMAL_WEIGHT;
253
Manman Ren1a710fd2012-08-24 18:14:27 +0000254 for (SmallVector<unsigned, 8>::iterator EI = BackEdges.begin(),
Andrew Trick9e764222011-06-04 01:16:30 +0000255 EE = BackEdges.end(); EI != EE; ++EI) {
Manman Ren1a710fd2012-08-24 18:14:27 +0000256 setEdgeWeight(BB, *EI, backWeight);
Andrew Trick9e764222011-06-04 01:16:30 +0000257 }
258 }
259
Jakub Staszakfa447252011-07-28 21:33:46 +0000260 if (uint32_t numInEdges = InEdges.size()) {
261 uint32_t inWeight = LBH_TAKEN_WEIGHT / numInEdges;
262 if (inWeight < NORMAL_WEIGHT)
263 inWeight = NORMAL_WEIGHT;
264
Manman Ren1a710fd2012-08-24 18:14:27 +0000265 for (SmallVector<unsigned, 8>::iterator EI = InEdges.begin(),
Jakub Staszakfa447252011-07-28 21:33:46 +0000266 EE = InEdges.end(); EI != EE; ++EI) {
Manman Ren1a710fd2012-08-24 18:14:27 +0000267 setEdgeWeight(BB, *EI, inWeight);
Jakub Staszakfa447252011-07-28 21:33:46 +0000268 }
269 }
270
Chandler Carruth45baf6b2011-10-25 09:47:41 +0000271 if (uint32_t numExitingEdges = ExitingEdges.size()) {
272 uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numExitingEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000273 if (exitWeight < MIN_WEIGHT)
274 exitWeight = MIN_WEIGHT;
275
Manman Ren1a710fd2012-08-24 18:14:27 +0000276 for (SmallVector<unsigned, 8>::iterator EI = ExitingEdges.begin(),
Andrew Trick9e764222011-06-04 01:16:30 +0000277 EE = ExitingEdges.end(); EI != EE; ++EI) {
Manman Ren1a710fd2012-08-24 18:14:27 +0000278 setEdgeWeight(BB, *EI, exitWeight);
Andrew Trick9e764222011-06-04 01:16:30 +0000279 }
280 }
Jakub Staszak7241caf2011-07-28 21:45:07 +0000281
282 return true;
Andrew Trick9e764222011-06-04 01:16:30 +0000283}
284
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000285bool BranchProbabilityInfo::calcZeroHeuristics(BasicBlock *BB) {
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000286 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
287 if (!BI || !BI->isConditional())
288 return false;
289
290 Value *Cond = BI->getCondition();
291 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
292 if (!CI)
293 return false;
294
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000295 Value *RHS = CI->getOperand(1);
Jakub Staszaka385c202011-07-31 04:47:20 +0000296 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000297 if (!CV)
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000298 return false;
299
300 bool isProb;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000301 if (CV->isZero()) {
302 switch (CI->getPredicate()) {
303 case CmpInst::ICMP_EQ:
304 // X == 0 -> Unlikely
305 isProb = false;
306 break;
307 case CmpInst::ICMP_NE:
308 // X != 0 -> Likely
309 isProb = true;
310 break;
311 case CmpInst::ICMP_SLT:
312 // X < 0 -> Unlikely
313 isProb = false;
314 break;
315 case CmpInst::ICMP_SGT:
316 // X > 0 -> Likely
317 isProb = true;
318 break;
319 default:
320 return false;
321 }
322 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
323 // InstCombine canonicalizes X <= 0 into X < 1.
324 // X <= 0 -> Unlikely
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000325 isProb = false;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000326 } else if (CV->isAllOnesValue() && CI->getPredicate() == CmpInst::ICMP_SGT) {
327 // InstCombine canonicalizes X >= 0 into X > -1.
328 // X >= 0 -> Likely
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000329 isProb = true;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000330 } else {
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000331 return false;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000332 }
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000333
Manman Ren1a710fd2012-08-24 18:14:27 +0000334 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000335
336 if (!isProb)
Manman Ren1a710fd2012-08-24 18:14:27 +0000337 std::swap(TakenIdx, NonTakenIdx);
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000338
Manman Ren1a710fd2012-08-24 18:14:27 +0000339 setEdgeWeight(BB, TakenIdx, ZH_TAKEN_WEIGHT);
340 setEdgeWeight(BB, NonTakenIdx, ZH_NONTAKEN_WEIGHT);
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000341
342 return true;
343}
344
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000345bool BranchProbabilityInfo::calcFloatingPointHeuristics(BasicBlock *BB) {
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000346 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
347 if (!BI || !BI->isConditional())
348 return false;
349
350 Value *Cond = BI->getCondition();
351 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer675c02b2011-10-21 21:13:47 +0000352 if (!FCmp)
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000353 return false;
354
Benjamin Kramer675c02b2011-10-21 21:13:47 +0000355 bool isProb;
356 if (FCmp->isEquality()) {
357 // f1 == f2 -> Unlikely
358 // f1 != f2 -> Likely
359 isProb = !FCmp->isTrueWhenEqual();
360 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
361 // !isnan -> Likely
362 isProb = true;
363 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
364 // isnan -> Unlikely
365 isProb = false;
366 } else {
367 return false;
368 }
369
Manman Ren1a710fd2012-08-24 18:14:27 +0000370 unsigned TakenIdx = 0, NonTakenIdx = 1;
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000371
Benjamin Kramer675c02b2011-10-21 21:13:47 +0000372 if (!isProb)
Manman Ren1a710fd2012-08-24 18:14:27 +0000373 std::swap(TakenIdx, NonTakenIdx);
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000374
Manman Ren1a710fd2012-08-24 18:14:27 +0000375 setEdgeWeight(BB, TakenIdx, FPH_TAKEN_WEIGHT);
376 setEdgeWeight(BB, NonTakenIdx, FPH_NONTAKEN_WEIGHT);
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000377
378 return true;
379}
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000380
Bill Wendling0c34ae82012-08-15 12:22:35 +0000381bool BranchProbabilityInfo::calcInvokeHeuristics(BasicBlock *BB) {
382 InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
383 if (!II)
384 return false;
385
Manman Ren1a710fd2012-08-24 18:14:27 +0000386 setEdgeWeight(BB, 0/*Index for Normal*/, IH_TAKEN_WEIGHT);
387 setEdgeWeight(BB, 1/*Index for Unwind*/, IH_NONTAKEN_WEIGHT);
Bill Wendling0c34ae82012-08-15 12:22:35 +0000388 return true;
389}
390
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000391void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
392 AU.addRequired<LoopInfo>();
393 AU.setPreservesAll();
394}
395
396bool BranchProbabilityInfo::runOnFunction(Function &F) {
397 LastF = &F; // Store the last function we ran on for printing.
398 LI = &getAnalysis<LoopInfo>();
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000399 assert(PostDominatedByUnreachable.empty());
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000400
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000401 // Walk the basic blocks in post-order so that we can build up state about
402 // the successors of a block iteratively.
403 for (po_iterator<BasicBlock *> I = po_begin(&F.getEntryBlock()),
404 E = po_end(&F.getEntryBlock());
405 I != E; ++I) {
406 DEBUG(dbgs() << "Computing probabilities for " << I->getName() << "\n");
407 if (calcUnreachableHeuristics(*I))
Chandler Carruth99d01c52011-10-19 10:30:30 +0000408 continue;
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000409 if (calcMetadataWeights(*I))
Jakub Staszak7241caf2011-07-28 21:45:07 +0000410 continue;
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000411 if (calcLoopBranchHeuristics(*I))
Jakub Staszak7241caf2011-07-28 21:45:07 +0000412 continue;
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000413 if (calcPointerHeuristics(*I))
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000414 continue;
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000415 if (calcZeroHeuristics(*I))
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000416 continue;
Bill Wendling0c34ae82012-08-15 12:22:35 +0000417 if (calcFloatingPointHeuristics(*I))
418 continue;
419 calcInvokeHeuristics(*I);
Andrew Trick9e764222011-06-04 01:16:30 +0000420 }
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000421
422 PostDominatedByUnreachable.clear();
Andrew Trick9e764222011-06-04 01:16:30 +0000423 return false;
424}
425
Chandler Carruth14edd312011-10-23 21:21:50 +0000426void BranchProbabilityInfo::print(raw_ostream &OS, const Module *) const {
427 OS << "---- Branch Probabilities ----\n";
428 // We print the probabilities from the last function the analysis ran over,
429 // or the function it is currently running over.
430 assert(LastF && "Cannot print prior to running over a function");
431 for (Function::const_iterator BI = LastF->begin(), BE = LastF->end();
432 BI != BE; ++BI) {
433 for (succ_const_iterator SI = succ_begin(BI), SE = succ_end(BI);
434 SI != SE; ++SI) {
435 printEdgeProbability(OS << " ", BI, *SI);
436 }
437 }
438}
439
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000440uint32_t BranchProbabilityInfo::getSumForBlock(const BasicBlock *BB) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000441 uint32_t Sum = 0;
442
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000443 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Manman Ren1a710fd2012-08-24 18:14:27 +0000444 uint32_t Weight = getEdgeWeight(BB, I.getSuccessorIndex());
Andrew Trickf289df22011-06-11 01:05:22 +0000445 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000446
447 Sum += Weight;
448 assert(Sum > PrevSum); (void) PrevSum;
449 }
450
Andrew Trickf289df22011-06-11 01:05:22 +0000451 return Sum;
452}
453
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000454bool BranchProbabilityInfo::
455isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000456 // Hot probability is at least 4/5 = 80%
Benjamin Kramer341473c2011-10-23 11:19:14 +0000457 // FIXME: Compare against a static "hot" BranchProbability.
458 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick9e764222011-06-04 01:16:30 +0000459}
460
461BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000462 uint32_t Sum = 0;
463 uint32_t MaxWeight = 0;
Andrew Trick9e764222011-06-04 01:16:30 +0000464 BasicBlock *MaxSucc = 0;
465
466 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
467 BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000468 uint32_t Weight = getEdgeWeight(BB, Succ);
469 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000470
471 Sum += Weight;
472 assert(Sum > PrevSum); (void) PrevSum;
473
474 if (Weight > MaxWeight) {
475 MaxWeight = Weight;
476 MaxSucc = Succ;
477 }
478 }
479
Benjamin Kramer341473c2011-10-23 11:19:14 +0000480 // Hot probability is at least 4/5 = 80%
481 if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5))
Andrew Trick9e764222011-06-04 01:16:30 +0000482 return MaxSucc;
483
484 return 0;
485}
486
Manman Ren1a710fd2012-08-24 18:14:27 +0000487/// Get the raw edge weight for the edge. If can't find it, return
488/// DEFAULT_WEIGHT value. Here an edge is specified using PredBlock and an index
489/// to the successors.
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000490uint32_t BranchProbabilityInfo::
Manman Ren1a710fd2012-08-24 18:14:27 +0000491getEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors) const {
492 DenseMap<Edge, uint32_t>::const_iterator I =
493 Weights.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick9e764222011-06-04 01:16:30 +0000494
495 if (I != Weights.end())
496 return I->second;
497
498 return DEFAULT_WEIGHT;
499}
500
Manman Ren1a710fd2012-08-24 18:14:27 +0000501/// Get the raw edge weight calculated for the block pair. This returns the sum
502/// of all raw edge weights from Src to Dst.
503uint32_t BranchProbabilityInfo::
504getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) const {
505 uint32_t Weight = 0;
506 DenseMap<Edge, uint32_t>::const_iterator MapI;
507 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
508 if (*I == Dst) {
509 MapI = Weights.find(std::make_pair(Src, I.getSuccessorIndex()));
510 if (MapI != Weights.end())
511 Weight += MapI->second;
512 }
513 return (Weight == 0) ? DEFAULT_WEIGHT : Weight;
Andrew Trickf289df22011-06-11 01:05:22 +0000514}
515
Manman Ren1a710fd2012-08-24 18:14:27 +0000516/// Set the edge weight for a given edge specified by PredBlock and an index
517/// to the successors.
518void BranchProbabilityInfo::
519setEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors,
520 uint32_t Weight) {
521 Weights[std::make_pair(Src, IndexInSuccessors)] = Weight;
522 DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
523 << IndexInSuccessors << " successor weight to "
524 << Weight << "\n");
525}
Andrew Trickf289df22011-06-11 01:05:22 +0000526
Manman Ren1a710fd2012-08-24 18:14:27 +0000527/// Get an edge's probability, relative to other out-edges from Src.
528BranchProbability BranchProbabilityInfo::
529getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const {
530 uint32_t N = getEdgeWeight(Src, IndexInSuccessors);
531 uint32_t D = getSumForBlock(Src);
532
533 return BranchProbability(N, D);
534}
535
536/// Get the probability of going from Src to Dst. It returns the sum of all
537/// probabilities for edges from Src to Dst.
Andrew Trickf289df22011-06-11 01:05:22 +0000538BranchProbability BranchProbabilityInfo::
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000539getEdgeProbability(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000540
541 uint32_t N = getEdgeWeight(Src, Dst);
542 uint32_t D = getSumForBlock(Src);
543
544 return BranchProbability(N, D);
Andrew Trick9e764222011-06-04 01:16:30 +0000545}
546
547raw_ostream &
Chandler Carruth14edd312011-10-23 21:21:50 +0000548BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
549 const BasicBlock *Src,
550 const BasicBlock *Dst) const {
Andrew Trick9e764222011-06-04 01:16:30 +0000551
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000552 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000553 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trickf289df22011-06-11 01:05:22 +0000554 << " probability is " << Prob
555 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick9e764222011-06-04 01:16:30 +0000556
557 return OS;
558}