blob: 62cc686211a8023e828a895d12b094533de8a84d [file] [log] [blame]
Bill Wendlinge1c54262012-08-15 12:22:35 +00001//===-- BranchProbabilityInfo.cpp - Branch Probability Analysis -----------===//
Andrew Trick49371f32011-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
Michael Gottesmanfb9164f2013-12-14 02:24:25 +000014#define DEBUG_TYPE "branch-prob"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/Analysis/BranchProbabilityInfo.h"
16#include "llvm/ADT/PostOrderIterator.h"
17#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000018#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/Metadata.h"
Andrew Trick3d4e64b2011-06-11 01:05:22 +000024#include "llvm/Support/Debug.h"
Andrew Trick49371f32011-06-04 01:16:30 +000025
26using namespace llvm;
27
28INITIALIZE_PASS_BEGIN(BranchProbabilityInfo, "branch-prob",
29 "Branch Probability Analysis", false, true)
30INITIALIZE_PASS_DEPENDENCY(LoopInfo)
31INITIALIZE_PASS_END(BranchProbabilityInfo, "branch-prob",
32 "Branch Probability Analysis", false, true)
33
34char BranchProbabilityInfo::ID = 0;
35
Chandler Carruth7a0094a2011-10-24 01:40:45 +000036// Weights are for internal use only. They are used by heuristics to help to
37// estimate edges' probability. Example:
38//
39// Using "Loop Branch Heuristics" we predict weights of edges for the
40// block BB2.
41// ...
42// |
43// V
44// BB1<-+
45// | |
46// | | (Weight = 124)
47// V |
48// BB2--+
49// |
50// | (Weight = 4)
51// V
52// BB3
53//
54// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
55// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
56static const uint32_t LBH_TAKEN_WEIGHT = 124;
57static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
Andrew Trick49371f32011-06-04 01:16:30 +000058
Chandler Carruth7111f452011-10-24 12:01:08 +000059/// \brief Unreachable-terminating branch taken weight.
60///
61/// This is the weight for a branch being taken to a block that terminates
62/// (eventually) in unreachable. These are predicted as unlikely as possible.
63static const uint32_t UR_TAKEN_WEIGHT = 1;
64
65/// \brief Unreachable-terminating branch not-taken weight.
66///
67/// This is the weight for a branch not being taken toward a block that
68/// terminates (eventually) in unreachable. Such a branch is essentially never
Chandler Carruthb024aa02011-12-22 09:26:37 +000069/// taken. Set the weight to an absurdly high value so that nested loops don't
70/// easily subsume it.
71static const uint32_t UR_NONTAKEN_WEIGHT = 1024*1024 - 1;
Andrew Trick49371f32011-06-04 01:16:30 +000072
Diego Novilloc6399532013-05-24 12:26:52 +000073/// \brief Weight for a branch taken going into a cold block.
74///
75/// This is the weight for a branch taken toward a block marked
76/// cold. A block is marked cold if it's postdominated by a
77/// block containing a call to a cold function. Cold functions
78/// are those marked with attribute 'cold'.
79static const uint32_t CC_TAKEN_WEIGHT = 4;
80
81/// \brief Weight for a branch not-taken into a cold block.
82///
83/// This is the weight for a branch not taken toward a block marked
84/// cold.
85static const uint32_t CC_NONTAKEN_WEIGHT = 64;
86
Chandler Carruth7a0094a2011-10-24 01:40:45 +000087static const uint32_t PH_TAKEN_WEIGHT = 20;
88static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +000089
Chandler Carruth7a0094a2011-10-24 01:40:45 +000090static const uint32_t ZH_TAKEN_WEIGHT = 20;
91static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +000092
Chandler Carruth7a0094a2011-10-24 01:40:45 +000093static const uint32_t FPH_TAKEN_WEIGHT = 20;
94static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +000095
Bill Wendlinge1c54262012-08-15 12:22:35 +000096/// \brief Invoke-terminating normal branch taken weight
97///
98/// This is the weight for branching to the normal destination of an invoke
99/// instruction. We expect this to happen most of the time. Set the weight to an
100/// absurdly high value so that nested loops subsume it.
101static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
102
103/// \brief Invoke-terminating normal branch not-taken weight.
104///
105/// This is the weight for branching to the unwind destination of an invoke
106/// instruction. This is essentially never taken.
107static const uint32_t IH_NONTAKEN_WEIGHT = 1;
108
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000109// Standard weight value. Used when none of the heuristics set weight for
110// the edge.
111static const uint32_t NORMAL_WEIGHT = 16;
Andrew Trick49371f32011-06-04 01:16:30 +0000112
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000113// Minimum weight of an edge. Please note, that weight is NEVER 0.
114static const uint32_t MIN_WEIGHT = 1;
Andrew Trick49371f32011-06-04 01:16:30 +0000115
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000116static uint32_t getMaxWeightFor(BasicBlock *BB) {
117 return UINT32_MAX / BB->getTerminator()->getNumSuccessors();
118}
Andrew Trick49371f32011-06-04 01:16:30 +0000119
Andrew Trick49371f32011-06-04 01:16:30 +0000120
Chandler Carruth7111f452011-10-24 12:01:08 +0000121/// \brief Calculate edge weights for successors lead to unreachable.
122///
123/// Predict that a successor which leads necessarily to an
124/// unreachable-terminated block as extremely unlikely.
125bool BranchProbabilityInfo::calcUnreachableHeuristics(BasicBlock *BB) {
126 TerminatorInst *TI = BB->getTerminator();
127 if (TI->getNumSuccessors() == 0) {
128 if (isa<UnreachableInst>(TI))
129 PostDominatedByUnreachable.insert(BB);
130 return false;
131 }
132
Manman Rencf104462012-08-24 18:14:27 +0000133 SmallVector<unsigned, 4> UnreachableEdges;
134 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000135
136 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
137 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000138 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000139 else
Manman Rencf104462012-08-24 18:14:27 +0000140 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000141 }
142
143 // If all successors are in the set of blocks post-dominated by unreachable,
144 // this block is too.
145 if (UnreachableEdges.size() == TI->getNumSuccessors())
146 PostDominatedByUnreachable.insert(BB);
147
148 // Skip probabilities if this block has a single successor or if all were
149 // reachable.
150 if (TI->getNumSuccessors() == 1 || UnreachableEdges.empty())
151 return false;
152
153 uint32_t UnreachableWeight =
Manman Rencf104462012-08-24 18:14:27 +0000154 std::max(UR_TAKEN_WEIGHT / (unsigned)UnreachableEdges.size(), MIN_WEIGHT);
Craig Topperaf0dea12013-07-04 01:31:24 +0000155 for (SmallVectorImpl<unsigned>::iterator I = UnreachableEdges.begin(),
156 E = UnreachableEdges.end();
Chandler Carruth7111f452011-10-24 12:01:08 +0000157 I != E; ++I)
158 setEdgeWeight(BB, *I, UnreachableWeight);
159
160 if (ReachableEdges.empty())
161 return true;
162 uint32_t ReachableWeight =
Manman Rencf104462012-08-24 18:14:27 +0000163 std::max(UR_NONTAKEN_WEIGHT / (unsigned)ReachableEdges.size(),
164 NORMAL_WEIGHT);
Craig Topperaf0dea12013-07-04 01:31:24 +0000165 for (SmallVectorImpl<unsigned>::iterator I = ReachableEdges.begin(),
166 E = ReachableEdges.end();
Chandler Carruth7111f452011-10-24 12:01:08 +0000167 I != E; ++I)
168 setEdgeWeight(BB, *I, ReachableWeight);
169
170 return true;
171}
172
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000173// Propagate existing explicit probabilities from either profile data or
174// 'expect' intrinsic processing.
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000175bool BranchProbabilityInfo::calcMetadataWeights(BasicBlock *BB) {
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000176 TerminatorInst *TI = BB->getTerminator();
177 if (TI->getNumSuccessors() == 1)
178 return false;
179 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000180 return false;
181
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000182 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
183 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000184 return false;
185
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000186 // Ensure there are weights for all of the successors. Note that the first
187 // operand to the metadata node is a name, not a weight.
188 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000189 return false;
190
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000191 // Build up the final weights that will be used in a temporary buffer, but
192 // don't add them until all weihts are present. Each weight value is clamped
193 // to [1, getMaxWeightFor(BB)].
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000194 uint32_t WeightLimit = getMaxWeightFor(BB);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000195 SmallVector<uint32_t, 2> Weights;
196 Weights.reserve(TI->getNumSuccessors());
197 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
198 ConstantInt *Weight = dyn_cast<ConstantInt>(WeightsNode->getOperand(i));
199 if (!Weight)
200 return false;
201 Weights.push_back(
202 std::max<uint32_t>(1, Weight->getLimitedValue(WeightLimit)));
203 }
204 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
205 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Manman Rencf104462012-08-24 18:14:27 +0000206 setEdgeWeight(BB, i, Weights[i]);
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000207
208 return true;
209}
210
Diego Novilloc6399532013-05-24 12:26:52 +0000211/// \brief Calculate edge weights for edges leading to cold blocks.
212///
213/// A cold block is one post-dominated by a block with a call to a
214/// cold function. Those edges are unlikely to be taken, so we give
215/// them relatively low weight.
216///
217/// Return true if we could compute the weights for cold edges.
218/// Return false, otherwise.
219bool BranchProbabilityInfo::calcColdCallHeuristics(BasicBlock *BB) {
220 TerminatorInst *TI = BB->getTerminator();
221 if (TI->getNumSuccessors() == 0)
222 return false;
223
224 // Determine which successors are post-dominated by a cold block.
225 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000226 SmallVector<unsigned, 4> NormalEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000227 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
228 if (PostDominatedByColdCall.count(*I))
229 ColdEdges.push_back(I.getSuccessorIndex());
230 else
231 NormalEdges.push_back(I.getSuccessorIndex());
232
233 // If all successors are in the set of blocks post-dominated by cold calls,
234 // this block is in the set post-dominated by cold calls.
235 if (ColdEdges.size() == TI->getNumSuccessors())
236 PostDominatedByColdCall.insert(BB);
237 else {
238 // Otherwise, if the block itself contains a cold function, add it to the
239 // set of blocks postdominated by a cold call.
240 assert(!PostDominatedByColdCall.count(BB));
241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (CallInst *CI = dyn_cast<CallInst>(I))
243 if (CI->hasFnAttr(Attribute::Cold)) {
244 PostDominatedByColdCall.insert(BB);
245 break;
246 }
247 }
248
249 // Skip probabilities if this block has a single successor.
250 if (TI->getNumSuccessors() == 1 || ColdEdges.empty())
251 return false;
252
253 uint32_t ColdWeight =
254 std::max(CC_TAKEN_WEIGHT / (unsigned) ColdEdges.size(), MIN_WEIGHT);
Craig Topperaf0dea12013-07-04 01:31:24 +0000255 for (SmallVectorImpl<unsigned>::iterator I = ColdEdges.begin(),
256 E = ColdEdges.end();
Diego Novilloc6399532013-05-24 12:26:52 +0000257 I != E; ++I)
258 setEdgeWeight(BB, *I, ColdWeight);
259
260 if (NormalEdges.empty())
261 return true;
262 uint32_t NormalWeight = std::max(
263 CC_NONTAKEN_WEIGHT / (unsigned) NormalEdges.size(), NORMAL_WEIGHT);
Craig Topperaf0dea12013-07-04 01:31:24 +0000264 for (SmallVectorImpl<unsigned>::iterator I = NormalEdges.begin(),
265 E = NormalEdges.end();
Diego Novilloc6399532013-05-24 12:26:52 +0000266 I != E; ++I)
267 setEdgeWeight(BB, *I, NormalWeight);
268
269 return true;
270}
271
Andrew Trick49371f32011-06-04 01:16:30 +0000272// Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
273// between two pointer or pointer and NULL will fail.
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000274bool BranchProbabilityInfo::calcPointerHeuristics(BasicBlock *BB) {
Andrew Trick49371f32011-06-04 01:16:30 +0000275 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
276 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000277 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000278
279 Value *Cond = BI->getCondition();
280 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000281 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000282 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000283
284 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000285
286 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000287 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000288
Nick Lewycky75b20532011-06-04 02:07:10 +0000289 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000290
Andrew Trick49371f32011-06-04 01:16:30 +0000291 // p != 0 -> isProb = true
292 // p == 0 -> isProb = false
293 // p != q -> isProb = true
294 // p == q -> isProb = false;
Manman Rencf104462012-08-24 18:14:27 +0000295 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000296 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000297 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000298 std::swap(TakenIdx, NonTakenIdx);
Andrew Trick49371f32011-06-04 01:16:30 +0000299
Manman Rencf104462012-08-24 18:14:27 +0000300 setEdgeWeight(BB, TakenIdx, PH_TAKEN_WEIGHT);
301 setEdgeWeight(BB, NonTakenIdx, PH_NONTAKEN_WEIGHT);
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000302 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000303}
304
305// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
306// as taken, exiting edges as not-taken.
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000307bool BranchProbabilityInfo::calcLoopBranchHeuristics(BasicBlock *BB) {
Andrew Trick49371f32011-06-04 01:16:30 +0000308 Loop *L = LI->getLoopFor(BB);
309 if (!L)
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000310 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000311
Manman Rencf104462012-08-24 18:14:27 +0000312 SmallVector<unsigned, 8> BackEdges;
313 SmallVector<unsigned, 8> ExitingEdges;
314 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000315
Andrew Trick49371f32011-06-04 01:16:30 +0000316 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Chandler Carruth32f46e72011-10-25 09:47:41 +0000317 if (!L->contains(*I))
Manman Rencf104462012-08-24 18:14:27 +0000318 ExitingEdges.push_back(I.getSuccessorIndex());
Chandler Carruth32f46e72011-10-25 09:47:41 +0000319 else if (L->getHeader() == *I)
Manman Rencf104462012-08-24 18:14:27 +0000320 BackEdges.push_back(I.getSuccessorIndex());
Chandler Carruth32f46e72011-10-25 09:47:41 +0000321 else
Manman Rencf104462012-08-24 18:14:27 +0000322 InEdges.push_back(I.getSuccessorIndex());
Andrew Trick49371f32011-06-04 01:16:30 +0000323 }
324
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000325 if (uint32_t numBackEdges = BackEdges.size()) {
326 uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges;
Andrew Trick49371f32011-06-04 01:16:30 +0000327 if (backWeight < NORMAL_WEIGHT)
328 backWeight = NORMAL_WEIGHT;
329
Craig Topperaf0dea12013-07-04 01:31:24 +0000330 for (SmallVectorImpl<unsigned>::iterator EI = BackEdges.begin(),
Andrew Trick49371f32011-06-04 01:16:30 +0000331 EE = BackEdges.end(); EI != EE; ++EI) {
Manman Rencf104462012-08-24 18:14:27 +0000332 setEdgeWeight(BB, *EI, backWeight);
Andrew Trick49371f32011-06-04 01:16:30 +0000333 }
334 }
335
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000336 if (uint32_t numInEdges = InEdges.size()) {
337 uint32_t inWeight = LBH_TAKEN_WEIGHT / numInEdges;
338 if (inWeight < NORMAL_WEIGHT)
339 inWeight = NORMAL_WEIGHT;
340
Craig Topperaf0dea12013-07-04 01:31:24 +0000341 for (SmallVectorImpl<unsigned>::iterator EI = InEdges.begin(),
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000342 EE = InEdges.end(); EI != EE; ++EI) {
Manman Rencf104462012-08-24 18:14:27 +0000343 setEdgeWeight(BB, *EI, inWeight);
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000344 }
345 }
346
Chandler Carruth32f46e72011-10-25 09:47:41 +0000347 if (uint32_t numExitingEdges = ExitingEdges.size()) {
348 uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numExitingEdges;
Andrew Trick49371f32011-06-04 01:16:30 +0000349 if (exitWeight < MIN_WEIGHT)
350 exitWeight = MIN_WEIGHT;
351
Craig Topperaf0dea12013-07-04 01:31:24 +0000352 for (SmallVectorImpl<unsigned>::iterator EI = ExitingEdges.begin(),
Andrew Trick49371f32011-06-04 01:16:30 +0000353 EE = ExitingEdges.end(); EI != EE; ++EI) {
Manman Rencf104462012-08-24 18:14:27 +0000354 setEdgeWeight(BB, *EI, exitWeight);
Andrew Trick49371f32011-06-04 01:16:30 +0000355 }
356 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000357
358 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000359}
360
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000361bool BranchProbabilityInfo::calcZeroHeuristics(BasicBlock *BB) {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000362 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
363 if (!BI || !BI->isConditional())
364 return false;
365
366 Value *Cond = BI->getCondition();
367 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
368 if (!CI)
369 return false;
370
Jakub Staszak17af66a2011-07-31 03:27:24 +0000371 Value *RHS = CI->getOperand(1);
Jakub Staszakbfb1ae22011-07-31 04:47:20 +0000372 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000373 if (!CV)
Jakub Staszak17af66a2011-07-31 03:27:24 +0000374 return false;
375
376 bool isProb;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000377 if (CV->isZero()) {
378 switch (CI->getPredicate()) {
379 case CmpInst::ICMP_EQ:
380 // X == 0 -> Unlikely
381 isProb = false;
382 break;
383 case CmpInst::ICMP_NE:
384 // X != 0 -> Likely
385 isProb = true;
386 break;
387 case CmpInst::ICMP_SLT:
388 // X < 0 -> Unlikely
389 isProb = false;
390 break;
391 case CmpInst::ICMP_SGT:
392 // X > 0 -> Likely
393 isProb = true;
394 break;
395 default:
396 return false;
397 }
398 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
399 // InstCombine canonicalizes X <= 0 into X < 1.
400 // X <= 0 -> Unlikely
Jakub Staszak17af66a2011-07-31 03:27:24 +0000401 isProb = false;
Hal Finkel4d949302013-11-01 10:58:22 +0000402 } else if (CV->isAllOnesValue()) {
403 switch (CI->getPredicate()) {
404 case CmpInst::ICMP_EQ:
405 // X == -1 -> Unlikely
406 isProb = false;
407 break;
408 case CmpInst::ICMP_NE:
409 // X != -1 -> Likely
410 isProb = true;
411 break;
412 case CmpInst::ICMP_SGT:
413 // InstCombine canonicalizes X >= 0 into X > -1.
414 // X >= 0 -> Likely
415 isProb = true;
416 break;
417 default:
418 return false;
419 }
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000420 } else {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000421 return false;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000422 }
Jakub Staszak17af66a2011-07-31 03:27:24 +0000423
Manman Rencf104462012-08-24 18:14:27 +0000424 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszak17af66a2011-07-31 03:27:24 +0000425
426 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000427 std::swap(TakenIdx, NonTakenIdx);
Jakub Staszak17af66a2011-07-31 03:27:24 +0000428
Manman Rencf104462012-08-24 18:14:27 +0000429 setEdgeWeight(BB, TakenIdx, ZH_TAKEN_WEIGHT);
430 setEdgeWeight(BB, NonTakenIdx, ZH_NONTAKEN_WEIGHT);
Jakub Staszak17af66a2011-07-31 03:27:24 +0000431
432 return true;
433}
434
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000435bool BranchProbabilityInfo::calcFloatingPointHeuristics(BasicBlock *BB) {
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000436 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
437 if (!BI || !BI->isConditional())
438 return false;
439
440 Value *Cond = BI->getCondition();
441 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000442 if (!FCmp)
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000443 return false;
444
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000445 bool isProb;
446 if (FCmp->isEquality()) {
447 // f1 == f2 -> Unlikely
448 // f1 != f2 -> Likely
449 isProb = !FCmp->isTrueWhenEqual();
450 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
451 // !isnan -> Likely
452 isProb = true;
453 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
454 // isnan -> Unlikely
455 isProb = false;
456 } else {
457 return false;
458 }
459
Manman Rencf104462012-08-24 18:14:27 +0000460 unsigned TakenIdx = 0, NonTakenIdx = 1;
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000461
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000462 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000463 std::swap(TakenIdx, NonTakenIdx);
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000464
Manman Rencf104462012-08-24 18:14:27 +0000465 setEdgeWeight(BB, TakenIdx, FPH_TAKEN_WEIGHT);
466 setEdgeWeight(BB, NonTakenIdx, FPH_NONTAKEN_WEIGHT);
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000467
468 return true;
469}
Jakub Staszak17af66a2011-07-31 03:27:24 +0000470
Bill Wendlinge1c54262012-08-15 12:22:35 +0000471bool BranchProbabilityInfo::calcInvokeHeuristics(BasicBlock *BB) {
472 InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
473 if (!II)
474 return false;
475
Manman Rencf104462012-08-24 18:14:27 +0000476 setEdgeWeight(BB, 0/*Index for Normal*/, IH_TAKEN_WEIGHT);
477 setEdgeWeight(BB, 1/*Index for Unwind*/, IH_NONTAKEN_WEIGHT);
Bill Wendlinge1c54262012-08-15 12:22:35 +0000478 return true;
479}
480
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000481void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
482 AU.addRequired<LoopInfo>();
483 AU.setPreservesAll();
484}
485
486bool BranchProbabilityInfo::runOnFunction(Function &F) {
Michael Gottesmanfb9164f2013-12-14 02:24:25 +0000487 DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
488 << " ----\n\n");
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000489 LastF = &F; // Store the last function we ran on for printing.
490 LI = &getAnalysis<LoopInfo>();
Chandler Carruth7111f452011-10-24 12:01:08 +0000491 assert(PostDominatedByUnreachable.empty());
Diego Novilloc6399532013-05-24 12:26:52 +0000492 assert(PostDominatedByColdCall.empty());
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000493
Chandler Carruth7111f452011-10-24 12:01:08 +0000494 // Walk the basic blocks in post-order so that we can build up state about
495 // the successors of a block iteratively.
496 for (po_iterator<BasicBlock *> I = po_begin(&F.getEntryBlock()),
497 E = po_end(&F.getEntryBlock());
498 I != E; ++I) {
499 DEBUG(dbgs() << "Computing probabilities for " << I->getName() << "\n");
500 if (calcUnreachableHeuristics(*I))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000501 continue;
Chandler Carruth7111f452011-10-24 12:01:08 +0000502 if (calcMetadataWeights(*I))
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000503 continue;
Diego Novilloc6399532013-05-24 12:26:52 +0000504 if (calcColdCallHeuristics(*I))
505 continue;
Chandler Carruth7111f452011-10-24 12:01:08 +0000506 if (calcLoopBranchHeuristics(*I))
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000507 continue;
Chandler Carruth7111f452011-10-24 12:01:08 +0000508 if (calcPointerHeuristics(*I))
Jakub Staszak17af66a2011-07-31 03:27:24 +0000509 continue;
Chandler Carruth7111f452011-10-24 12:01:08 +0000510 if (calcZeroHeuristics(*I))
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000511 continue;
Bill Wendlinge1c54262012-08-15 12:22:35 +0000512 if (calcFloatingPointHeuristics(*I))
513 continue;
514 calcInvokeHeuristics(*I);
Andrew Trick49371f32011-06-04 01:16:30 +0000515 }
Chandler Carruth7111f452011-10-24 12:01:08 +0000516
517 PostDominatedByUnreachable.clear();
Diego Novilloc6399532013-05-24 12:26:52 +0000518 PostDominatedByColdCall.clear();
Andrew Trick49371f32011-06-04 01:16:30 +0000519 return false;
520}
521
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000522void BranchProbabilityInfo::print(raw_ostream &OS, const Module *) const {
523 OS << "---- Branch Probabilities ----\n";
524 // We print the probabilities from the last function the analysis ran over,
525 // or the function it is currently running over.
526 assert(LastF && "Cannot print prior to running over a function");
527 for (Function::const_iterator BI = LastF->begin(), BE = LastF->end();
528 BI != BE; ++BI) {
529 for (succ_const_iterator SI = succ_begin(BI), SE = succ_end(BI);
530 SI != SE; ++SI) {
531 printEdgeProbability(OS << " ", BI, *SI);
532 }
533 }
534}
535
Jakub Staszakefd94c82011-07-29 19:30:00 +0000536uint32_t BranchProbabilityInfo::getSumForBlock(const BasicBlock *BB) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000537 uint32_t Sum = 0;
538
Jakub Staszakefd94c82011-07-29 19:30:00 +0000539 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Manman Rencf104462012-08-24 18:14:27 +0000540 uint32_t Weight = getEdgeWeight(BB, I.getSuccessorIndex());
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000541 uint32_t PrevSum = Sum;
Andrew Trick49371f32011-06-04 01:16:30 +0000542
543 Sum += Weight;
544 assert(Sum > PrevSum); (void) PrevSum;
545 }
546
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000547 return Sum;
548}
549
Jakub Staszakefd94c82011-07-29 19:30:00 +0000550bool BranchProbabilityInfo::
551isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000552 // Hot probability is at least 4/5 = 80%
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000553 // FIXME: Compare against a static "hot" BranchProbability.
554 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick49371f32011-06-04 01:16:30 +0000555}
556
557BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000558 uint32_t Sum = 0;
559 uint32_t MaxWeight = 0;
Andrew Trick49371f32011-06-04 01:16:30 +0000560 BasicBlock *MaxSucc = 0;
561
562 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
563 BasicBlock *Succ = *I;
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000564 uint32_t Weight = getEdgeWeight(BB, Succ);
565 uint32_t PrevSum = Sum;
Andrew Trick49371f32011-06-04 01:16:30 +0000566
567 Sum += Weight;
568 assert(Sum > PrevSum); (void) PrevSum;
569
570 if (Weight > MaxWeight) {
571 MaxWeight = Weight;
572 MaxSucc = Succ;
573 }
574 }
575
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000576 // Hot probability is at least 4/5 = 80%
577 if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +0000578 return MaxSucc;
579
580 return 0;
581}
582
Manman Rencf104462012-08-24 18:14:27 +0000583/// Get the raw edge weight for the edge. If can't find it, return
584/// DEFAULT_WEIGHT value. Here an edge is specified using PredBlock and an index
585/// to the successors.
Jakub Staszakefd94c82011-07-29 19:30:00 +0000586uint32_t BranchProbabilityInfo::
Manman Rencf104462012-08-24 18:14:27 +0000587getEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors) const {
588 DenseMap<Edge, uint32_t>::const_iterator I =
589 Weights.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick49371f32011-06-04 01:16:30 +0000590
591 if (I != Weights.end())
592 return I->second;
593
594 return DEFAULT_WEIGHT;
595}
596
Duncan P. N. Exon Smith37bd5292014-04-11 23:20:52 +0000597uint32_t BranchProbabilityInfo::getEdgeWeight(const BasicBlock *Src,
598 succ_const_iterator Dst) const {
599 return getEdgeWeight(Src, Dst.getSuccessorIndex());
Michael Gottesmanfb9164f2013-12-14 02:24:25 +0000600}
601
Manman Rencf104462012-08-24 18:14:27 +0000602/// Get the raw edge weight calculated for the block pair. This returns the sum
603/// of all raw edge weights from Src to Dst.
604uint32_t BranchProbabilityInfo::
605getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) const {
606 uint32_t Weight = 0;
607 DenseMap<Edge, uint32_t>::const_iterator MapI;
608 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
609 if (*I == Dst) {
610 MapI = Weights.find(std::make_pair(Src, I.getSuccessorIndex()));
611 if (MapI != Weights.end())
612 Weight += MapI->second;
613 }
614 return (Weight == 0) ? DEFAULT_WEIGHT : Weight;
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000615}
616
Manman Rencf104462012-08-24 18:14:27 +0000617/// Set the edge weight for a given edge specified by PredBlock and an index
618/// to the successors.
619void BranchProbabilityInfo::
620setEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors,
621 uint32_t Weight) {
622 Weights[std::make_pair(Src, IndexInSuccessors)] = Weight;
623 DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
624 << IndexInSuccessors << " successor weight to "
625 << Weight << "\n");
626}
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000627
Manman Rencf104462012-08-24 18:14:27 +0000628/// Get an edge's probability, relative to other out-edges from Src.
629BranchProbability BranchProbabilityInfo::
630getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const {
631 uint32_t N = getEdgeWeight(Src, IndexInSuccessors);
632 uint32_t D = getSumForBlock(Src);
633
634 return BranchProbability(N, D);
635}
636
637/// Get the probability of going from Src to Dst. It returns the sum of all
638/// probabilities for edges from Src to Dst.
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000639BranchProbability BranchProbabilityInfo::
Jakub Staszakefd94c82011-07-29 19:30:00 +0000640getEdgeProbability(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000641
642 uint32_t N = getEdgeWeight(Src, Dst);
643 uint32_t D = getSumForBlock(Src);
644
645 return BranchProbability(N, D);
Andrew Trick49371f32011-06-04 01:16:30 +0000646}
647
648raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000649BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
650 const BasicBlock *Src,
651 const BasicBlock *Dst) const {
Andrew Trick49371f32011-06-04 01:16:30 +0000652
Jakub Staszak12a43bd2011-06-16 20:22:37 +0000653 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000654 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000655 << " probability is " << Prob
656 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +0000657
658 return OS;
659}