blob: 9f175b070d3d22617c2b256cc9b13f890af0f9d8 [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
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 Carruth14edd312011-10-23 21:21:50 +000021#include "llvm/Support/CFG.h"
Andrew Trickf289df22011-06-11 01:05:22 +000022#include "llvm/Support/Debug.h"
Andrew Trick9e764222011-06-04 01:16:30 +000023
24using namespace llvm;
25
26INITIALIZE_PASS_BEGIN(BranchProbabilityInfo, "branch-prob",
27 "Branch Probability Analysis", false, true)
28INITIALIZE_PASS_DEPENDENCY(LoopInfo)
29INITIALIZE_PASS_END(BranchProbabilityInfo, "branch-prob",
30 "Branch Probability Analysis", false, true)
31
32char BranchProbabilityInfo::ID = 0;
33
Benjamin Kramerafa88ea2011-06-13 18:38:56 +000034namespace {
Andrew Trick9e764222011-06-04 01:16:30 +000035// Please note that BranchProbabilityAnalysis is not a FunctionPass.
36// It is created by BranchProbabilityInfo (which is a FunctionPass), which
37// provides a clear interface. Thanks to that, all heuristics and other
38// private methods are hidden in the .cpp file.
39class BranchProbabilityAnalysis {
40
Jakub Staszak6f6baf12011-07-29 19:30:00 +000041 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
Andrew Trick9e764222011-06-04 01:16:30 +000042
Andrew Trick9e764222011-06-04 01:16:30 +000043 BranchProbabilityInfo *BP;
44
45 LoopInfo *LI;
46
47
48 // Weights are for internal use only. They are used by heuristics to help to
49 // estimate edges' probability. Example:
50 //
51 // Using "Loop Branch Heuristics" we predict weights of edges for the
52 // block BB2.
53 // ...
54 // |
55 // V
56 // BB1<-+
57 // | |
Jakub Staszak3d8b15e2011-07-28 23:42:08 +000058 // | | (Weight = 124)
Andrew Trick9e764222011-06-04 01:16:30 +000059 // V |
60 // BB2--+
61 // |
62 // | (Weight = 4)
63 // V
64 // BB3
65 //
Jakub Staszak3d8b15e2011-07-28 23:42:08 +000066 // Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
67 // Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
Andrew Trick9e764222011-06-04 01:16:30 +000068
Jakub Staszak3d8b15e2011-07-28 23:42:08 +000069 static const uint32_t LBH_TAKEN_WEIGHT = 124;
Andrew Trickf289df22011-06-11 01:05:22 +000070 static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
Andrew Trick9e764222011-06-04 01:16:30 +000071
Jakub Staszake0058b42011-07-29 02:36:53 +000072 static const uint32_t RH_TAKEN_WEIGHT = 24;
73 static const uint32_t RH_NONTAKEN_WEIGHT = 8;
74
75 static const uint32_t PH_TAKEN_WEIGHT = 20;
76 static const uint32_t PH_NONTAKEN_WEIGHT = 12;
77
Jakub Staszaka5dd5502011-07-31 03:27:24 +000078 static const uint32_t ZH_TAKEN_WEIGHT = 20;
79 static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
80
Benjamin Kramerc888aa42011-10-21 20:12:47 +000081 static const uint32_t FPH_TAKEN_WEIGHT = 20;
82 static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
83
Andrew Trick9e764222011-06-04 01:16:30 +000084 // Standard weight value. Used when none of the heuristics set weight for
85 // the edge.
Andrew Trickf289df22011-06-11 01:05:22 +000086 static const uint32_t NORMAL_WEIGHT = 16;
Andrew Trick9e764222011-06-04 01:16:30 +000087
88 // Minimum weight of an edge. Please note, that weight is NEVER 0.
Andrew Trickf289df22011-06-11 01:05:22 +000089 static const uint32_t MIN_WEIGHT = 1;
Andrew Trick9e764222011-06-04 01:16:30 +000090
91 // Return TRUE if BB leads directly to a Return Instruction.
92 static bool isReturningBlock(BasicBlock *BB) {
93 SmallPtrSet<BasicBlock *, 8> Visited;
94
95 while (true) {
96 TerminatorInst *TI = BB->getTerminator();
97 if (isa<ReturnInst>(TI))
98 return true;
99
100 if (TI->getNumSuccessors() > 1)
101 break;
102
103 // It is unreachable block which we can consider as a return instruction.
104 if (TI->getNumSuccessors() == 0)
105 return true;
106
107 Visited.insert(BB);
108 BB = TI->getSuccessor(0);
109
110 // Stop if cycle is detected.
111 if (Visited.count(BB))
112 return false;
113 }
114
115 return false;
116 }
117
Andrew Trickf289df22011-06-11 01:05:22 +0000118 uint32_t getMaxWeightFor(BasicBlock *BB) const {
119 return UINT32_MAX / BB->getTerminator()->getNumSuccessors();
Andrew Trick9e764222011-06-04 01:16:30 +0000120 }
121
122public:
Chandler Carruth7a34c8b2011-10-16 22:27:54 +0000123 BranchProbabilityAnalysis(BranchProbabilityInfo *BP, LoopInfo *LI)
124 : BP(BP), LI(LI) {
Andrew Trick9e764222011-06-04 01:16:30 +0000125 }
126
Chandler Carruth99d01c52011-10-19 10:30:30 +0000127 // Metadata Weights
128 bool calcMetadataWeights(BasicBlock *BB);
129
Andrew Trick9e764222011-06-04 01:16:30 +0000130 // Return Heuristics
Jakub Staszak7241caf2011-07-28 21:45:07 +0000131 bool calcReturnHeuristics(BasicBlock *BB);
Andrew Trick9e764222011-06-04 01:16:30 +0000132
133 // Pointer Heuristics
Jakub Staszak7241caf2011-07-28 21:45:07 +0000134 bool calcPointerHeuristics(BasicBlock *BB);
Andrew Trick9e764222011-06-04 01:16:30 +0000135
136 // Loop Branch Heuristics
Jakub Staszak7241caf2011-07-28 21:45:07 +0000137 bool calcLoopBranchHeuristics(BasicBlock *BB);
Andrew Trick9e764222011-06-04 01:16:30 +0000138
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000139 // Zero Heuristics
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000140 bool calcZeroHeuristics(BasicBlock *BB);
141
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000142 // Floating Point Heuristics
143 bool calcFloatingPointHeuristics(BasicBlock *BB);
144
Andrew Trick9e764222011-06-04 01:16:30 +0000145 bool runOnFunction(Function &F);
146};
Benjamin Kramerafa88ea2011-06-13 18:38:56 +0000147} // end anonymous namespace
Andrew Trick9e764222011-06-04 01:16:30 +0000148
Chandler Carruth99d01c52011-10-19 10:30:30 +0000149// Propagate existing explicit probabilities from either profile data or
150// 'expect' intrinsic processing.
Chandler Carruth99d01c52011-10-19 10:30:30 +0000151bool BranchProbabilityAnalysis::calcMetadataWeights(BasicBlock *BB) {
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000152 TerminatorInst *TI = BB->getTerminator();
153 if (TI->getNumSuccessors() == 1)
154 return false;
155 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
Chandler Carruth99d01c52011-10-19 10:30:30 +0000156 return false;
157
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000158 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
159 if (!WeightsNode)
Chandler Carruth99d01c52011-10-19 10:30:30 +0000160 return false;
161
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000162 // Ensure there are weights for all of the successors. Note that the first
163 // operand to the metadata node is a name, not a weight.
164 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruth99d01c52011-10-19 10:30:30 +0000165 return false;
166
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000167 // Build up the final weights that will be used in a temporary buffer, but
168 // don't add them until all weihts are present. Each weight value is clamped
169 // to [1, getMaxWeightFor(BB)].
Chandler Carruth99d01c52011-10-19 10:30:30 +0000170 uint32_t WeightLimit = getMaxWeightFor(BB);
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000171 SmallVector<uint32_t, 2> Weights;
172 Weights.reserve(TI->getNumSuccessors());
173 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
174 ConstantInt *Weight = dyn_cast<ConstantInt>(WeightsNode->getOperand(i));
175 if (!Weight)
176 return false;
177 Weights.push_back(
178 std::max<uint32_t>(1, Weight->getLimitedValue(WeightLimit)));
179 }
180 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
181 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
182 BP->setEdgeWeight(BB, TI->getSuccessor(i), Weights[i]);
Chandler Carruth99d01c52011-10-19 10:30:30 +0000183
184 return true;
185}
186
Andrew Trick9e764222011-06-04 01:16:30 +0000187// Calculate Edge Weights using "Return Heuristics". Predict a successor which
188// leads directly to Return Instruction will not be taken.
Jakub Staszak7241caf2011-07-28 21:45:07 +0000189bool BranchProbabilityAnalysis::calcReturnHeuristics(BasicBlock *BB){
Andrew Trick9e764222011-06-04 01:16:30 +0000190 if (BB->getTerminator()->getNumSuccessors() == 1)
Jakub Staszak7241caf2011-07-28 21:45:07 +0000191 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000192
Jakub Staszakb137f162011-08-01 19:16:26 +0000193 SmallPtrSet<BasicBlock *, 4> ReturningEdges;
194 SmallPtrSet<BasicBlock *, 4> StayEdges;
Jakub Staszake0058b42011-07-29 02:36:53 +0000195
Andrew Trick9e764222011-06-04 01:16:30 +0000196 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
197 BasicBlock *Succ = *I;
Jakub Staszake0058b42011-07-29 02:36:53 +0000198 if (isReturningBlock(Succ))
Jakub Staszakb137f162011-08-01 19:16:26 +0000199 ReturningEdges.insert(Succ);
Jakub Staszake0058b42011-07-29 02:36:53 +0000200 else
Jakub Staszakb137f162011-08-01 19:16:26 +0000201 StayEdges.insert(Succ);
Jakub Staszake0058b42011-07-29 02:36:53 +0000202 }
203
204 if (uint32_t numStayEdges = StayEdges.size()) {
205 uint32_t stayWeight = RH_TAKEN_WEIGHT / numStayEdges;
206 if (stayWeight < NORMAL_WEIGHT)
207 stayWeight = NORMAL_WEIGHT;
208
Jakub Staszakb137f162011-08-01 19:16:26 +0000209 for (SmallPtrSet<BasicBlock *, 4>::iterator I = StayEdges.begin(),
Jakub Staszake0058b42011-07-29 02:36:53 +0000210 E = StayEdges.end(); I != E; ++I)
211 BP->setEdgeWeight(BB, *I, stayWeight);
212 }
213
214 if (uint32_t numRetEdges = ReturningEdges.size()) {
215 uint32_t retWeight = RH_NONTAKEN_WEIGHT / numRetEdges;
216 if (retWeight < MIN_WEIGHT)
217 retWeight = MIN_WEIGHT;
Jakub Staszakb137f162011-08-01 19:16:26 +0000218 for (SmallPtrSet<BasicBlock *, 4>::iterator I = ReturningEdges.begin(),
Jakub Staszake0058b42011-07-29 02:36:53 +0000219 E = ReturningEdges.end(); I != E; ++I) {
220 BP->setEdgeWeight(BB, *I, retWeight);
Andrew Trick9e764222011-06-04 01:16:30 +0000221 }
222 }
Jakub Staszak7241caf2011-07-28 21:45:07 +0000223
Jakub Staszake0058b42011-07-29 02:36:53 +0000224 return ReturningEdges.size() > 0;
Andrew Trick9e764222011-06-04 01:16:30 +0000225}
226
227// Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
228// between two pointer or pointer and NULL will fail.
Jakub Staszak7241caf2011-07-28 21:45:07 +0000229bool BranchProbabilityAnalysis::calcPointerHeuristics(BasicBlock *BB) {
Andrew Trick9e764222011-06-04 01:16:30 +0000230 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
231 if (!BI || !BI->isConditional())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000232 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000233
234 Value *Cond = BI->getCondition();
235 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakd7932ca2011-07-15 20:51:06 +0000236 if (!CI || !CI->isEquality())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000237 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000238
239 Value *LHS = CI->getOperand(0);
Andrew Trick9e764222011-06-04 01:16:30 +0000240
241 if (!LHS->getType()->isPointerTy())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000242 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000243
Nick Lewycky404b53e2011-06-04 02:07:10 +0000244 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick9e764222011-06-04 01:16:30 +0000245
246 BasicBlock *Taken = BI->getSuccessor(0);
247 BasicBlock *NonTaken = BI->getSuccessor(1);
248
249 // p != 0 -> isProb = true
250 // p == 0 -> isProb = false
251 // p != q -> isProb = true
252 // p == q -> isProb = false;
Jakub Staszakd7932ca2011-07-15 20:51:06 +0000253 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick9e764222011-06-04 01:16:30 +0000254 if (!isProb)
255 std::swap(Taken, NonTaken);
256
Jakub Staszake0058b42011-07-29 02:36:53 +0000257 BP->setEdgeWeight(BB, Taken, PH_TAKEN_WEIGHT);
258 BP->setEdgeWeight(BB, NonTaken, PH_NONTAKEN_WEIGHT);
Jakub Staszak7241caf2011-07-28 21:45:07 +0000259 return true;
Andrew Trick9e764222011-06-04 01:16:30 +0000260}
261
262// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
263// as taken, exiting edges as not-taken.
Jakub Staszak7241caf2011-07-28 21:45:07 +0000264bool BranchProbabilityAnalysis::calcLoopBranchHeuristics(BasicBlock *BB) {
Andrew Trickf289df22011-06-11 01:05:22 +0000265 uint32_t numSuccs = BB->getTerminator()->getNumSuccessors();
Andrew Trick9e764222011-06-04 01:16:30 +0000266
267 Loop *L = LI->getLoopFor(BB);
268 if (!L)
Jakub Staszak7241caf2011-07-28 21:45:07 +0000269 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000270
Jakub Staszakb137f162011-08-01 19:16:26 +0000271 SmallPtrSet<BasicBlock *, 8> BackEdges;
272 SmallPtrSet<BasicBlock *, 8> ExitingEdges;
273 SmallPtrSet<BasicBlock *, 8> InEdges; // Edges from header to the loop.
Jakub Staszakfa447252011-07-28 21:33:46 +0000274
275 bool isHeader = BB == L->getHeader();
Andrew Trick9e764222011-06-04 01:16:30 +0000276
277 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
278 BasicBlock *Succ = *I;
279 Loop *SuccL = LI->getLoopFor(Succ);
280 if (SuccL != L)
Jakub Staszakb137f162011-08-01 19:16:26 +0000281 ExitingEdges.insert(Succ);
Andrew Trick9e764222011-06-04 01:16:30 +0000282 else if (Succ == L->getHeader())
Jakub Staszakb137f162011-08-01 19:16:26 +0000283 BackEdges.insert(Succ);
Jakub Staszakfa447252011-07-28 21:33:46 +0000284 else if (isHeader)
Jakub Staszakb137f162011-08-01 19:16:26 +0000285 InEdges.insert(Succ);
Andrew Trick9e764222011-06-04 01:16:30 +0000286 }
287
Andrew Trickf289df22011-06-11 01:05:22 +0000288 if (uint32_t numBackEdges = BackEdges.size()) {
289 uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000290 if (backWeight < NORMAL_WEIGHT)
291 backWeight = NORMAL_WEIGHT;
292
Jakub Staszakb137f162011-08-01 19:16:26 +0000293 for (SmallPtrSet<BasicBlock *, 8>::iterator EI = BackEdges.begin(),
Andrew Trick9e764222011-06-04 01:16:30 +0000294 EE = BackEdges.end(); EI != EE; ++EI) {
295 BasicBlock *Back = *EI;
296 BP->setEdgeWeight(BB, Back, backWeight);
297 }
298 }
299
Jakub Staszakfa447252011-07-28 21:33:46 +0000300 if (uint32_t numInEdges = InEdges.size()) {
301 uint32_t inWeight = LBH_TAKEN_WEIGHT / numInEdges;
302 if (inWeight < NORMAL_WEIGHT)
303 inWeight = NORMAL_WEIGHT;
304
Jakub Staszakb137f162011-08-01 19:16:26 +0000305 for (SmallPtrSet<BasicBlock *, 8>::iterator EI = InEdges.begin(),
Jakub Staszakfa447252011-07-28 21:33:46 +0000306 EE = InEdges.end(); EI != EE; ++EI) {
307 BasicBlock *Back = *EI;
308 BP->setEdgeWeight(BB, Back, inWeight);
309 }
310 }
311
Andrew Trickf289df22011-06-11 01:05:22 +0000312 uint32_t numExitingEdges = ExitingEdges.size();
313 if (uint32_t numNonExitingEdges = numSuccs - numExitingEdges) {
314 uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numNonExitingEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000315 if (exitWeight < MIN_WEIGHT)
316 exitWeight = MIN_WEIGHT;
317
Jakub Staszakb137f162011-08-01 19:16:26 +0000318 for (SmallPtrSet<BasicBlock *, 8>::iterator EI = ExitingEdges.begin(),
Andrew Trick9e764222011-06-04 01:16:30 +0000319 EE = ExitingEdges.end(); EI != EE; ++EI) {
320 BasicBlock *Exiting = *EI;
321 BP->setEdgeWeight(BB, Exiting, exitWeight);
322 }
323 }
Jakub Staszak7241caf2011-07-28 21:45:07 +0000324
325 return true;
Andrew Trick9e764222011-06-04 01:16:30 +0000326}
327
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000328bool BranchProbabilityAnalysis::calcZeroHeuristics(BasicBlock *BB) {
329 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
330 if (!BI || !BI->isConditional())
331 return false;
332
333 Value *Cond = BI->getCondition();
334 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
335 if (!CI)
336 return false;
337
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000338 Value *RHS = CI->getOperand(1);
Jakub Staszaka385c202011-07-31 04:47:20 +0000339 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000340 if (!CV)
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000341 return false;
342
343 bool isProb;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000344 if (CV->isZero()) {
345 switch (CI->getPredicate()) {
346 case CmpInst::ICMP_EQ:
347 // X == 0 -> Unlikely
348 isProb = false;
349 break;
350 case CmpInst::ICMP_NE:
351 // X != 0 -> Likely
352 isProb = true;
353 break;
354 case CmpInst::ICMP_SLT:
355 // X < 0 -> Unlikely
356 isProb = false;
357 break;
358 case CmpInst::ICMP_SGT:
359 // X > 0 -> Likely
360 isProb = true;
361 break;
362 default:
363 return false;
364 }
365 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
366 // InstCombine canonicalizes X <= 0 into X < 1.
367 // X <= 0 -> Unlikely
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000368 isProb = false;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000369 } else if (CV->isAllOnesValue() && CI->getPredicate() == CmpInst::ICMP_SGT) {
370 // InstCombine canonicalizes X >= 0 into X > -1.
371 // X >= 0 -> Likely
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000372 isProb = true;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000373 } else {
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000374 return false;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000375 }
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000376
377 BasicBlock *Taken = BI->getSuccessor(0);
378 BasicBlock *NonTaken = BI->getSuccessor(1);
379
380 if (!isProb)
381 std::swap(Taken, NonTaken);
382
383 BP->setEdgeWeight(BB, Taken, ZH_TAKEN_WEIGHT);
384 BP->setEdgeWeight(BB, NonTaken, ZH_NONTAKEN_WEIGHT);
385
386 return true;
387}
388
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000389bool BranchProbabilityAnalysis::calcFloatingPointHeuristics(BasicBlock *BB) {
390 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
391 if (!BI || !BI->isConditional())
392 return false;
393
394 Value *Cond = BI->getCondition();
395 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer675c02b2011-10-21 21:13:47 +0000396 if (!FCmp)
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000397 return false;
398
Benjamin Kramer675c02b2011-10-21 21:13:47 +0000399 bool isProb;
400 if (FCmp->isEquality()) {
401 // f1 == f2 -> Unlikely
402 // f1 != f2 -> Likely
403 isProb = !FCmp->isTrueWhenEqual();
404 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
405 // !isnan -> Likely
406 isProb = true;
407 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
408 // isnan -> Unlikely
409 isProb = false;
410 } else {
411 return false;
412 }
413
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000414 BasicBlock *Taken = BI->getSuccessor(0);
415 BasicBlock *NonTaken = BI->getSuccessor(1);
416
Benjamin Kramer675c02b2011-10-21 21:13:47 +0000417 if (!isProb)
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000418 std::swap(Taken, NonTaken);
419
420 BP->setEdgeWeight(BB, Taken, FPH_TAKEN_WEIGHT);
421 BP->setEdgeWeight(BB, NonTaken, FPH_NONTAKEN_WEIGHT);
422
423 return true;
424}
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000425
Andrew Trick9e764222011-06-04 01:16:30 +0000426bool BranchProbabilityAnalysis::runOnFunction(Function &F) {
427
428 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
429 BasicBlock *BB = I++;
430
Chandler Carruth99d01c52011-10-19 10:30:30 +0000431 if (calcMetadataWeights(BB))
432 continue;
433
Jakub Staszak7241caf2011-07-28 21:45:07 +0000434 if (calcLoopBranchHeuristics(BB))
435 continue;
Andrew Trick9e764222011-06-04 01:16:30 +0000436
Jakub Staszak7241caf2011-07-28 21:45:07 +0000437 if (calcReturnHeuristics(BB))
438 continue;
439
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000440 if (calcPointerHeuristics(BB))
441 continue;
442
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000443 if (calcZeroHeuristics(BB))
444 continue;
445
446 calcFloatingPointHeuristics(BB);
Andrew Trick9e764222011-06-04 01:16:30 +0000447 }
448
449 return false;
450}
451
Jakub Staszak12af93a2011-07-16 20:31:15 +0000452void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
453 AU.addRequired<LoopInfo>();
454 AU.setPreservesAll();
455}
Andrew Trick9e764222011-06-04 01:16:30 +0000456
457bool BranchProbabilityInfo::runOnFunction(Function &F) {
Chandler Carruth14edd312011-10-23 21:21:50 +0000458 LastF = &F; // Store the last function we ran on for printing.
Andrew Trick9e764222011-06-04 01:16:30 +0000459 LoopInfo &LI = getAnalysis<LoopInfo>();
Chandler Carruth7a34c8b2011-10-16 22:27:54 +0000460 BranchProbabilityAnalysis BPA(this, &LI);
Andrew Trickf289df22011-06-11 01:05:22 +0000461 return BPA.runOnFunction(F);
Andrew Trick9e764222011-06-04 01:16:30 +0000462}
463
Chandler Carruth14edd312011-10-23 21:21:50 +0000464void BranchProbabilityInfo::print(raw_ostream &OS, const Module *) const {
465 OS << "---- Branch Probabilities ----\n";
466 // We print the probabilities from the last function the analysis ran over,
467 // or the function it is currently running over.
468 assert(LastF && "Cannot print prior to running over a function");
469 for (Function::const_iterator BI = LastF->begin(), BE = LastF->end();
470 BI != BE; ++BI) {
471 for (succ_const_iterator SI = succ_begin(BI), SE = succ_end(BI);
472 SI != SE; ++SI) {
473 printEdgeProbability(OS << " ", BI, *SI);
474 }
475 }
476}
477
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000478uint32_t BranchProbabilityInfo::getSumForBlock(const BasicBlock *BB) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000479 uint32_t Sum = 0;
480
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000481 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
482 const BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000483 uint32_t Weight = getEdgeWeight(BB, Succ);
484 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000485
486 Sum += Weight;
487 assert(Sum > PrevSum); (void) PrevSum;
488 }
489
Andrew Trickf289df22011-06-11 01:05:22 +0000490 return Sum;
491}
492
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000493bool BranchProbabilityInfo::
494isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000495 // Hot probability is at least 4/5 = 80%
Benjamin Kramer341473c2011-10-23 11:19:14 +0000496 // FIXME: Compare against a static "hot" BranchProbability.
497 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick9e764222011-06-04 01:16:30 +0000498}
499
500BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000501 uint32_t Sum = 0;
502 uint32_t MaxWeight = 0;
Andrew Trick9e764222011-06-04 01:16:30 +0000503 BasicBlock *MaxSucc = 0;
504
505 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
506 BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000507 uint32_t Weight = getEdgeWeight(BB, Succ);
508 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000509
510 Sum += Weight;
511 assert(Sum > PrevSum); (void) PrevSum;
512
513 if (Weight > MaxWeight) {
514 MaxWeight = Weight;
515 MaxSucc = Succ;
516 }
517 }
518
Benjamin Kramer341473c2011-10-23 11:19:14 +0000519 // Hot probability is at least 4/5 = 80%
520 if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5))
Andrew Trick9e764222011-06-04 01:16:30 +0000521 return MaxSucc;
522
523 return 0;
524}
525
526// Return edge's weight. If can't find it, return DEFAULT_WEIGHT value.
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000527uint32_t BranchProbabilityInfo::
528getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick9e764222011-06-04 01:16:30 +0000529 Edge E(Src, Dst);
Andrew Trickf289df22011-06-11 01:05:22 +0000530 DenseMap<Edge, uint32_t>::const_iterator I = Weights.find(E);
Andrew Trick9e764222011-06-04 01:16:30 +0000531
532 if (I != Weights.end())
533 return I->second;
534
535 return DEFAULT_WEIGHT;
536}
537
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000538void BranchProbabilityInfo::
539setEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst, uint32_t Weight) {
Andrew Trick9e764222011-06-04 01:16:30 +0000540 Weights[std::make_pair(Src, Dst)] = Weight;
Andrew Trickf289df22011-06-11 01:05:22 +0000541 DEBUG(dbgs() << "set edge " << Src->getNameStr() << " -> "
542 << Dst->getNameStr() << " weight to " << Weight
543 << (isEdgeHot(Src, Dst) ? " [is HOT now]\n" : "\n"));
544}
545
546
547BranchProbability BranchProbabilityInfo::
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000548getEdgeProbability(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000549
550 uint32_t N = getEdgeWeight(Src, Dst);
551 uint32_t D = getSumForBlock(Src);
552
553 return BranchProbability(N, D);
Andrew Trick9e764222011-06-04 01:16:30 +0000554}
555
556raw_ostream &
Chandler Carruth14edd312011-10-23 21:21:50 +0000557BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
558 const BasicBlock *Src,
559 const BasicBlock *Dst) const {
Andrew Trick9e764222011-06-04 01:16:30 +0000560
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000561 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Andrew Trickf289df22011-06-11 01:05:22 +0000562 OS << "edge " << Src->getNameStr() << " -> " << Dst->getNameStr()
563 << " probability is " << Prob
564 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick9e764222011-06-04 01:16:30 +0000565
566 return OS;
567}