blob: c6d17d2936d922e522ad69aa52e4dc580d169e9a [file] [log] [blame]
Eugene Zelenko38c02bc2017-07-21 21:37:46 +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
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/Analysis/BranchProbabilityInfo.h"
15#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/Analysis/LoopInfo.h"
John Brawnda4a68a2017-06-08 09:44:40 +000019#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000020#include "llvm/IR/Attributes.h"
21#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000022#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/Function.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000025#include "llvm/IR/InstrTypes.h"
26#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Metadata.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000030#include "llvm/IR/PassManager.h"
31#include "llvm/IR/Type.h"
32#include "llvm/IR/Value.h"
33#include "llvm/Pass.h"
34#include "llvm/Support/BranchProbability.h"
35#include "llvm/Support/Casting.h"
Andrew Trick3d4e64b2011-06-11 01:05:22 +000036#include "llvm/Support/Debug.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000037#include "llvm/Support/raw_ostream.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000038#include <cassert>
39#include <cstdint>
40#include <iterator>
41#include <utility>
Andrew Trick49371f32011-06-04 01:16:30 +000042
43using namespace llvm;
44
Chandler Carruthf1221bd2014-04-22 02:48:03 +000045#define DEBUG_TYPE "branch-prob"
46
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +000047static cl::opt<bool> PrintBranchProb(
48 "print-bpi", cl::init(false), cl::Hidden,
49 cl::desc("Print the branch probability info."));
50
51cl::opt<std::string> PrintBranchProbFuncName(
52 "print-bpi-func-name", cl::Hidden,
53 cl::desc("The option to specify the name of the function "
54 "whose branch probability info is printed."));
55
Cong Houab23bfb2015-07-15 22:48:29 +000056INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000057 "Branch Probability Analysis", false, true)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000058INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
John Brawnda4a68a2017-06-08 09:44:40 +000059INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Cong Houab23bfb2015-07-15 22:48:29 +000060INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000061 "Branch Probability Analysis", false, true)
62
Cong Houab23bfb2015-07-15 22:48:29 +000063char BranchProbabilityInfoWrapperPass::ID = 0;
Andrew Trick49371f32011-06-04 01:16:30 +000064
Chandler Carruth7a0094a2011-10-24 01:40:45 +000065// Weights are for internal use only. They are used by heuristics to help to
66// estimate edges' probability. Example:
67//
68// Using "Loop Branch Heuristics" we predict weights of edges for the
69// block BB2.
70// ...
71// |
72// V
73// BB1<-+
74// | |
75// | | (Weight = 124)
76// V |
77// BB2--+
78// |
79// | (Weight = 4)
80// V
81// BB3
82//
83// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
84// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
85static const uint32_t LBH_TAKEN_WEIGHT = 124;
86static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
Andrew Trick49371f32011-06-04 01:16:30 +000087
Serguei Katkovba831f72017-05-18 06:11:56 +000088/// \brief Unreachable-terminating branch taken probability.
Chandler Carruth7111f452011-10-24 12:01:08 +000089///
Serguei Katkovba831f72017-05-18 06:11:56 +000090/// This is the probability for a branch being taken to a block that terminates
Chandler Carruth7111f452011-10-24 12:01:08 +000091/// (eventually) in unreachable. These are predicted as unlikely as possible.
Serguei Katkovba831f72017-05-18 06:11:56 +000092/// All reachable probability will equally share the remaining part.
93static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +000094
Diego Novilloc6399532013-05-24 12:26:52 +000095/// \brief Weight for a branch taken going into a cold block.
96///
97/// This is the weight for a branch taken toward a block marked
98/// cold. A block is marked cold if it's postdominated by a
99/// block containing a call to a cold function. Cold functions
100/// are those marked with attribute 'cold'.
101static const uint32_t CC_TAKEN_WEIGHT = 4;
102
103/// \brief Weight for a branch not-taken into a cold block.
104///
105/// This is the weight for a branch not taken toward a block marked
106/// cold.
107static const uint32_t CC_NONTAKEN_WEIGHT = 64;
108
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000109static const uint32_t PH_TAKEN_WEIGHT = 20;
110static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000111
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000112static const uint32_t ZH_TAKEN_WEIGHT = 20;
113static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000114
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000115static const uint32_t FPH_TAKEN_WEIGHT = 20;
116static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000117
Bill Wendlinge1c54262012-08-15 12:22:35 +0000118/// \brief Invoke-terminating normal branch taken weight
119///
120/// This is the weight for branching to the normal destination of an invoke
121/// instruction. We expect this to happen most of the time. Set the weight to an
122/// absurdly high value so that nested loops subsume it.
123static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
124
125/// \brief Invoke-terminating normal branch not-taken weight.
126///
127/// This is the weight for branching to the unwind destination of an invoke
128/// instruction. This is essentially never taken.
129static const uint32_t IH_NONTAKEN_WEIGHT = 1;
130
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000131/// \brief Add \p BB to PostDominatedByUnreachable set if applicable.
132void
133BranchProbabilityInfo::updatePostDominatedByUnreachable(const BasicBlock *BB) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000134 const TerminatorInst *TI = BB->getTerminator();
Chandler Carruth7111f452011-10-24 12:01:08 +0000135 if (TI->getNumSuccessors() == 0) {
Sanjoy Das432c1c32016-04-18 19:01:28 +0000136 if (isa<UnreachableInst>(TI) ||
137 // If this block is terminated by a call to
138 // @llvm.experimental.deoptimize then treat it like an unreachable since
139 // the @llvm.experimental.deoptimize call is expected to practically
140 // never execute.
141 BB->getTerminatingDeoptimizeCall())
Chandler Carruth7111f452011-10-24 12:01:08 +0000142 PostDominatedByUnreachable.insert(BB);
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000143 return;
Chandler Carruth7111f452011-10-24 12:01:08 +0000144 }
145
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000146 // If the terminator is an InvokeInst, check only the normal destination block
147 // as the unwind edge of InvokeInst is also very unlikely taken.
148 if (auto *II = dyn_cast<InvokeInst>(TI)) {
149 if (PostDominatedByUnreachable.count(II->getNormalDest()))
150 PostDominatedByUnreachable.insert(BB);
151 return;
152 }
153
154 for (auto *I : successors(BB))
155 // If any of successor is not post dominated then BB is also not.
156 if (!PostDominatedByUnreachable.count(I))
157 return;
158
159 PostDominatedByUnreachable.insert(BB);
160}
161
162/// \brief Add \p BB to PostDominatedByColdCall set if applicable.
163void
164BranchProbabilityInfo::updatePostDominatedByColdCall(const BasicBlock *BB) {
165 assert(!PostDominatedByColdCall.count(BB));
166 const TerminatorInst *TI = BB->getTerminator();
167 if (TI->getNumSuccessors() == 0)
168 return;
169
170 // If all of successor are post dominated then BB is also done.
171 if (llvm::all_of(successors(BB), [&](const BasicBlock *SuccBB) {
172 return PostDominatedByColdCall.count(SuccBB);
173 })) {
174 PostDominatedByColdCall.insert(BB);
175 return;
176 }
177
178 // If the terminator is an InvokeInst, check only the normal destination
179 // block as the unwind edge of InvokeInst is also very unlikely taken.
180 if (auto *II = dyn_cast<InvokeInst>(TI))
181 if (PostDominatedByColdCall.count(II->getNormalDest())) {
182 PostDominatedByColdCall.insert(BB);
183 return;
184 }
185
186 // Otherwise, if the block itself contains a cold function, add it to the
187 // set of blocks post-dominated by a cold call.
188 for (auto &I : *BB)
189 if (const CallInst *CI = dyn_cast<CallInst>(&I))
190 if (CI->hasFnAttr(Attribute::Cold)) {
191 PostDominatedByColdCall.insert(BB);
192 return;
193 }
194}
195
196/// \brief Calculate edge weights for successors lead to unreachable.
197///
198/// Predict that a successor which leads necessarily to an
199/// unreachable-terminated block as extremely unlikely.
200bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
201 const TerminatorInst *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000202 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
203
204 // Return false here so that edge weights for InvokeInst could be decided
205 // in calcInvokeHeuristics().
206 if (isa<InvokeInst>(TI))
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000207 return false;
208
Manman Rencf104462012-08-24 18:14:27 +0000209 SmallVector<unsigned, 4> UnreachableEdges;
210 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000211
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000212 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Chandler Carruth7111f452011-10-24 12:01:08 +0000213 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000214 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000215 else
Manman Rencf104462012-08-24 18:14:27 +0000216 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000217
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000218 // Skip probabilities if all were reachable.
219 if (UnreachableEdges.empty())
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000220 return false;
Jun Bum Lima23e5f72015-12-21 22:00:51 +0000221
Cong Houe93b8e12015-12-22 18:56:14 +0000222 if (ReachableEdges.empty()) {
223 BranchProbability Prob(1, UnreachableEdges.size());
224 for (unsigned SuccIdx : UnreachableEdges)
225 setEdgeProbability(BB, SuccIdx, Prob);
Chandler Carruth7111f452011-10-24 12:01:08 +0000226 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000227 }
228
Serguei Katkovba831f72017-05-18 06:11:56 +0000229 auto UnreachableProb = UR_TAKEN_PROB;
230 auto ReachableProb =
231 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
232 ReachableEdges.size();
Cong Houe93b8e12015-12-22 18:56:14 +0000233
234 for (unsigned SuccIdx : UnreachableEdges)
235 setEdgeProbability(BB, SuccIdx, UnreachableProb);
236 for (unsigned SuccIdx : ReachableEdges)
237 setEdgeProbability(BB, SuccIdx, ReachableProb);
Chandler Carruth7111f452011-10-24 12:01:08 +0000238
239 return true;
240}
241
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000242// Propagate existing explicit probabilities from either profile data or
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000243// 'expect' intrinsic processing. Examine metadata against unreachable
244// heuristic. The probability of the edge coming to unreachable block is
245// set to min of metadata and unreachable heuristic.
Mehdi Aminia7978772016-04-07 21:59:28 +0000246bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
247 const TerminatorInst *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000248 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Rong Xu15848e52017-08-23 21:36:02 +0000249 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI)))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000250 return false;
251
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000252 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000253 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000254 return false;
255
Diego Novillode5b8012015-05-07 17:22:06 +0000256 // Check that the number of successors is manageable.
257 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
258
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000259 // Ensure there are weights for all of the successors. Note that the first
260 // operand to the metadata node is a name, not a weight.
261 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000262 return false;
263
Diego Novillode5b8012015-05-07 17:22:06 +0000264 // Build up the final weights that will be used in a temporary buffer.
265 // Compute the sum of all weights to later decide whether they need to
266 // be scaled to fit in 32 bits.
267 uint64_t WeightSum = 0;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000268 SmallVector<uint32_t, 2> Weights;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000269 SmallVector<unsigned, 2> UnreachableIdxs;
270 SmallVector<unsigned, 2> ReachableIdxs;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000271 Weights.reserve(TI->getNumSuccessors());
272 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000273 ConstantInt *Weight =
274 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i));
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000275 if (!Weight)
276 return false;
Diego Novillode5b8012015-05-07 17:22:06 +0000277 assert(Weight->getValue().getActiveBits() <= 32 &&
278 "Too many bits for uint32_t");
279 Weights.push_back(Weight->getZExtValue());
280 WeightSum += Weights.back();
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000281 if (PostDominatedByUnreachable.count(TI->getSuccessor(i - 1)))
282 UnreachableIdxs.push_back(i - 1);
283 else
284 ReachableIdxs.push_back(i - 1);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000285 }
286 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
Diego Novillode5b8012015-05-07 17:22:06 +0000287
288 // If the sum of weights does not fit in 32 bits, scale every weight down
289 // accordingly.
290 uint64_t ScalingFactor =
291 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
292
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000293 if (ScalingFactor > 1) {
294 WeightSum = 0;
295 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
296 Weights[i] /= ScalingFactor;
297 WeightSum += Weights[i];
298 }
Diego Novillode5b8012015-05-07 17:22:06 +0000299 }
Serguei Katkov63c9c812017-05-12 07:50:06 +0000300 assert(WeightSum <= UINT32_MAX &&
301 "Expected weights to scale down to 32 bits");
Cong Hou6a2c71a2015-12-22 23:45:55 +0000302
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000303 if (WeightSum == 0 || ReachableIdxs.size() == 0) {
Cong Hou6a2c71a2015-12-22 23:45:55 +0000304 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000305 Weights[i] = 1;
306 WeightSum = TI->getNumSuccessors();
Cong Hou6a2c71a2015-12-22 23:45:55 +0000307 }
Cong Houe93b8e12015-12-22 18:56:14 +0000308
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000309 // Set the probability.
310 SmallVector<BranchProbability, 2> BP;
311 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
312 BP.push_back({ Weights[i], static_cast<uint32_t>(WeightSum) });
313
314 // Examine the metadata against unreachable heuristic.
315 // If the unreachable heuristic is more strong then we use it for this edge.
316 if (UnreachableIdxs.size() > 0 && ReachableIdxs.size() > 0) {
317 auto ToDistribute = BranchProbability::getZero();
Serguei Katkovba831f72017-05-18 06:11:56 +0000318 auto UnreachableProb = UR_TAKEN_PROB;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000319 for (auto i : UnreachableIdxs)
320 if (UnreachableProb < BP[i]) {
321 ToDistribute += BP[i] - UnreachableProb;
322 BP[i] = UnreachableProb;
323 }
324
325 // If we modified the probability of some edges then we must distribute
326 // the difference between reachable blocks.
327 if (ToDistribute > BranchProbability::getZero()) {
328 BranchProbability PerEdge = ToDistribute / ReachableIdxs.size();
Serguei Katkov63c9c812017-05-12 07:50:06 +0000329 for (auto i : ReachableIdxs)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000330 BP[i] += PerEdge;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000331 }
332 }
333
334 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
335 setEdgeProbability(BB, i, BP[i]);
336
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000337 return true;
338}
339
Diego Novilloc6399532013-05-24 12:26:52 +0000340/// \brief Calculate edge weights for edges leading to cold blocks.
341///
342/// A cold block is one post-dominated by a block with a call to a
343/// cold function. Those edges are unlikely to be taken, so we give
344/// them relatively low weight.
345///
346/// Return true if we could compute the weights for cold edges.
347/// Return false, otherwise.
Mehdi Aminia7978772016-04-07 21:59:28 +0000348bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
349 const TerminatorInst *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000350 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
351
352 // Return false here so that edge weights for InvokeInst could be decided
353 // in calcInvokeHeuristics().
354 if (isa<InvokeInst>(TI))
Diego Novilloc6399532013-05-24 12:26:52 +0000355 return false;
356
357 // Determine which successors are post-dominated by a cold block.
358 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000359 SmallVector<unsigned, 4> NormalEdges;
Mehdi Aminia7978772016-04-07 21:59:28 +0000360 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Diego Novilloc6399532013-05-24 12:26:52 +0000361 if (PostDominatedByColdCall.count(*I))
362 ColdEdges.push_back(I.getSuccessorIndex());
363 else
364 NormalEdges.push_back(I.getSuccessorIndex());
365
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000366 // Skip probabilities if no cold edges.
367 if (ColdEdges.empty())
Diego Novilloc6399532013-05-24 12:26:52 +0000368 return false;
369
Cong Houe93b8e12015-12-22 18:56:14 +0000370 if (NormalEdges.empty()) {
371 BranchProbability Prob(1, ColdEdges.size());
372 for (unsigned SuccIdx : ColdEdges)
373 setEdgeProbability(BB, SuccIdx, Prob);
Diego Novilloc6399532013-05-24 12:26:52 +0000374 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000375 }
376
Vedant Kumara4bd1462016-12-17 01:02:08 +0000377 auto ColdProb = BranchProbability::getBranchProbability(
378 CC_TAKEN_WEIGHT,
379 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
380 auto NormalProb = BranchProbability::getBranchProbability(
381 CC_NONTAKEN_WEIGHT,
382 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
Cong Houe93b8e12015-12-22 18:56:14 +0000383
384 for (unsigned SuccIdx : ColdEdges)
385 setEdgeProbability(BB, SuccIdx, ColdProb);
386 for (unsigned SuccIdx : NormalEdges)
387 setEdgeProbability(BB, SuccIdx, NormalProb);
Diego Novilloc6399532013-05-24 12:26:52 +0000388
389 return true;
390}
391
Andrew Trick49371f32011-06-04 01:16:30 +0000392// Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
393// between two pointer or pointer and NULL will fail.
Mehdi Aminia7978772016-04-07 21:59:28 +0000394bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
395 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Andrew Trick49371f32011-06-04 01:16:30 +0000396 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000397 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000398
399 Value *Cond = BI->getCondition();
400 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000401 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000402 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000403
404 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000405
406 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000407 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000408
Nick Lewycky75b20532011-06-04 02:07:10 +0000409 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000410
Andrew Trick49371f32011-06-04 01:16:30 +0000411 // p != 0 -> isProb = true
412 // p == 0 -> isProb = false
413 // p != q -> isProb = true
414 // p == q -> isProb = false;
Manman Rencf104462012-08-24 18:14:27 +0000415 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000416 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000417 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000418 std::swap(TakenIdx, NonTakenIdx);
Andrew Trick49371f32011-06-04 01:16:30 +0000419
Cong Houe93b8e12015-12-22 18:56:14 +0000420 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
421 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
422 setEdgeProbability(BB, TakenIdx, TakenProb);
423 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000424 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000425}
426
427// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
428// as taken, exiting edges as not-taken.
Mehdi Aminia7978772016-04-07 21:59:28 +0000429bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
Cong Houab23bfb2015-07-15 22:48:29 +0000430 const LoopInfo &LI) {
431 Loop *L = LI.getLoopFor(BB);
Andrew Trick49371f32011-06-04 01:16:30 +0000432 if (!L)
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000433 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000434
Manman Rencf104462012-08-24 18:14:27 +0000435 SmallVector<unsigned, 8> BackEdges;
436 SmallVector<unsigned, 8> ExitingEdges;
437 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000438
Mehdi Aminia7978772016-04-07 21:59:28 +0000439 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Chandler Carruth32f46e72011-10-25 09:47:41 +0000440 if (!L->contains(*I))
Manman Rencf104462012-08-24 18:14:27 +0000441 ExitingEdges.push_back(I.getSuccessorIndex());
Chandler Carruth32f46e72011-10-25 09:47:41 +0000442 else if (L->getHeader() == *I)
Manman Rencf104462012-08-24 18:14:27 +0000443 BackEdges.push_back(I.getSuccessorIndex());
Chandler Carruth32f46e72011-10-25 09:47:41 +0000444 else
Manman Rencf104462012-08-24 18:14:27 +0000445 InEdges.push_back(I.getSuccessorIndex());
Andrew Trick49371f32011-06-04 01:16:30 +0000446 }
447
Akira Hatanaka5638b892014-04-14 16:56:19 +0000448 if (BackEdges.empty() && ExitingEdges.empty())
449 return false;
450
Cong Houe93b8e12015-12-22 18:56:14 +0000451 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
452 // normalize them so that they sum up to one.
Benjamin Kramer1d67ac52016-06-17 13:15:10 +0000453 BranchProbability Probs[] = {BranchProbability::getZero(),
454 BranchProbability::getZero(),
455 BranchProbability::getZero()};
Cong Houe93b8e12015-12-22 18:56:14 +0000456 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
457 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
458 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
459 if (!BackEdges.empty())
460 Probs[0] = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
461 if (!InEdges.empty())
462 Probs[1] = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
463 if (!ExitingEdges.empty())
464 Probs[2] = BranchProbability(LBH_NONTAKEN_WEIGHT, Denom);
Andrew Trick49371f32011-06-04 01:16:30 +0000465
Cong Houe93b8e12015-12-22 18:56:14 +0000466 if (uint32_t numBackEdges = BackEdges.size()) {
467 auto Prob = Probs[0] / numBackEdges;
468 for (unsigned SuccIdx : BackEdges)
469 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000470 }
471
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000472 if (uint32_t numInEdges = InEdges.size()) {
Cong Houe93b8e12015-12-22 18:56:14 +0000473 auto Prob = Probs[1] / numInEdges;
474 for (unsigned SuccIdx : InEdges)
475 setEdgeProbability(BB, SuccIdx, Prob);
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000476 }
477
Chandler Carruth32f46e72011-10-25 09:47:41 +0000478 if (uint32_t numExitingEdges = ExitingEdges.size()) {
Cong Houe93b8e12015-12-22 18:56:14 +0000479 auto Prob = Probs[2] / numExitingEdges;
480 for (unsigned SuccIdx : ExitingEdges)
481 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000482 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000483
484 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000485}
486
John Brawnda4a68a2017-06-08 09:44:40 +0000487bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
488 const TargetLibraryInfo *TLI) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000489 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000490 if (!BI || !BI->isConditional())
491 return false;
492
493 Value *Cond = BI->getCondition();
494 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
495 if (!CI)
496 return false;
497
Jakub Staszak17af66a2011-07-31 03:27:24 +0000498 Value *RHS = CI->getOperand(1);
Jakub Staszakbfb1ae22011-07-31 04:47:20 +0000499 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000500 if (!CV)
Jakub Staszak17af66a2011-07-31 03:27:24 +0000501 return false;
502
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000503 // If the LHS is the result of AND'ing a value with a single bit bitmask,
504 // we don't have information about probabilities.
505 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
506 if (LHS->getOpcode() == Instruction::And)
507 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
Craig Topper4e22ee62017-08-04 16:59:29 +0000508 if (AndRHS->getValue().isPowerOf2())
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000509 return false;
510
John Brawnda4a68a2017-06-08 09:44:40 +0000511 // Check if the LHS is the return value of a library function
512 LibFunc Func = NumLibFuncs;
513 if (TLI)
514 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
515 if (Function *CalledFn = Call->getCalledFunction())
516 TLI->getLibFunc(*CalledFn, Func);
517
Jakub Staszak17af66a2011-07-31 03:27:24 +0000518 bool isProb;
John Brawnda4a68a2017-06-08 09:44:40 +0000519 if (Func == LibFunc_strcasecmp ||
520 Func == LibFunc_strcmp ||
521 Func == LibFunc_strncasecmp ||
522 Func == LibFunc_strncmp ||
523 Func == LibFunc_memcmp) {
524 // strcmp and similar functions return zero, negative, or positive, if the
525 // first string is equal, less, or greater than the second. We consider it
526 // likely that the strings are not equal, so a comparison with zero is
527 // probably false, but also a comparison with any other number is also
528 // probably false given that what exactly is returned for nonzero values is
529 // not specified. Any kind of comparison other than equality we know
530 // nothing about.
531 switch (CI->getPredicate()) {
532 case CmpInst::ICMP_EQ:
533 isProb = false;
534 break;
535 case CmpInst::ICMP_NE:
536 isProb = true;
537 break;
538 default:
539 return false;
540 }
541 } else if (CV->isZero()) {
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000542 switch (CI->getPredicate()) {
543 case CmpInst::ICMP_EQ:
544 // X == 0 -> Unlikely
545 isProb = false;
546 break;
547 case CmpInst::ICMP_NE:
548 // X != 0 -> Likely
549 isProb = true;
550 break;
551 case CmpInst::ICMP_SLT:
552 // X < 0 -> Unlikely
553 isProb = false;
554 break;
555 case CmpInst::ICMP_SGT:
556 // X > 0 -> Likely
557 isProb = true;
558 break;
559 default:
560 return false;
561 }
562 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
563 // InstCombine canonicalizes X <= 0 into X < 1.
564 // X <= 0 -> Unlikely
Jakub Staszak17af66a2011-07-31 03:27:24 +0000565 isProb = false;
Craig Topper79ab6432017-07-06 18:39:47 +0000566 } else if (CV->isMinusOne()) {
Hal Finkel4d949302013-11-01 10:58:22 +0000567 switch (CI->getPredicate()) {
568 case CmpInst::ICMP_EQ:
569 // X == -1 -> Unlikely
570 isProb = false;
571 break;
572 case CmpInst::ICMP_NE:
573 // X != -1 -> Likely
574 isProb = true;
575 break;
576 case CmpInst::ICMP_SGT:
577 // InstCombine canonicalizes X >= 0 into X > -1.
578 // X >= 0 -> Likely
579 isProb = true;
580 break;
581 default:
582 return false;
583 }
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000584 } else {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000585 return false;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000586 }
Jakub Staszak17af66a2011-07-31 03:27:24 +0000587
Manman Rencf104462012-08-24 18:14:27 +0000588 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszak17af66a2011-07-31 03:27:24 +0000589
590 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000591 std::swap(TakenIdx, NonTakenIdx);
Jakub Staszak17af66a2011-07-31 03:27:24 +0000592
Cong Houe93b8e12015-12-22 18:56:14 +0000593 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
594 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
595 setEdgeProbability(BB, TakenIdx, TakenProb);
596 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000597 return true;
598}
599
Mehdi Aminia7978772016-04-07 21:59:28 +0000600bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
601 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000602 if (!BI || !BI->isConditional())
603 return false;
604
605 Value *Cond = BI->getCondition();
606 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000607 if (!FCmp)
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000608 return false;
609
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000610 bool isProb;
611 if (FCmp->isEquality()) {
612 // f1 == f2 -> Unlikely
613 // f1 != f2 -> Likely
614 isProb = !FCmp->isTrueWhenEqual();
615 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
616 // !isnan -> Likely
617 isProb = true;
618 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
619 // isnan -> Unlikely
620 isProb = false;
621 } else {
622 return false;
623 }
624
Manman Rencf104462012-08-24 18:14:27 +0000625 unsigned TakenIdx = 0, NonTakenIdx = 1;
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000626
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000627 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000628 std::swap(TakenIdx, NonTakenIdx);
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000629
Cong Houe93b8e12015-12-22 18:56:14 +0000630 BranchProbability TakenProb(FPH_TAKEN_WEIGHT,
631 FPH_TAKEN_WEIGHT + FPH_NONTAKEN_WEIGHT);
632 setEdgeProbability(BB, TakenIdx, TakenProb);
633 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000634 return true;
635}
Jakub Staszak17af66a2011-07-31 03:27:24 +0000636
Mehdi Aminia7978772016-04-07 21:59:28 +0000637bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
638 const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000639 if (!II)
640 return false;
641
Cong Houe93b8e12015-12-22 18:56:14 +0000642 BranchProbability TakenProb(IH_TAKEN_WEIGHT,
643 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
644 setEdgeProbability(BB, 0 /*Index for Normal*/, TakenProb);
645 setEdgeProbability(BB, 1 /*Index for Unwind*/, TakenProb.getCompl());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000646 return true;
647}
648
Pete Cooperb9d2e342015-05-28 19:43:06 +0000649void BranchProbabilityInfo::releaseMemory() {
Cong Houe93b8e12015-12-22 18:56:14 +0000650 Probs.clear();
Pete Cooperb9d2e342015-05-28 19:43:06 +0000651}
652
Cong Houab23bfb2015-07-15 22:48:29 +0000653void BranchProbabilityInfo::print(raw_ostream &OS) const {
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000654 OS << "---- Branch Probabilities ----\n";
655 // We print the probabilities from the last function the analysis ran over,
656 // or the function it is currently running over.
657 assert(LastF && "Cannot print prior to running over a function");
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000658 for (const auto &BI : *LastF) {
659 for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
660 ++SI) {
661 printEdgeProbability(OS << " ", &BI, *SI);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000662 }
663 }
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000664}
665
Jakub Staszakefd94c82011-07-29 19:30:00 +0000666bool BranchProbabilityInfo::
667isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000668 // Hot probability is at least 4/5 = 80%
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000669 // FIXME: Compare against a static "hot" BranchProbability.
670 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick49371f32011-06-04 01:16:30 +0000671}
672
Mehdi Aminia7978772016-04-07 21:59:28 +0000673const BasicBlock *
674BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
Cong Houe93b8e12015-12-22 18:56:14 +0000675 auto MaxProb = BranchProbability::getZero();
Mehdi Aminia7978772016-04-07 21:59:28 +0000676 const BasicBlock *MaxSucc = nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000677
Mehdi Aminia7978772016-04-07 21:59:28 +0000678 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
679 const BasicBlock *Succ = *I;
Cong Houe93b8e12015-12-22 18:56:14 +0000680 auto Prob = getEdgeProbability(BB, Succ);
681 if (Prob > MaxProb) {
682 MaxProb = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000683 MaxSucc = Succ;
684 }
685 }
686
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000687 // Hot probability is at least 4/5 = 80%
Cong Houe93b8e12015-12-22 18:56:14 +0000688 if (MaxProb > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +0000689 return MaxSucc;
690
Craig Topper9f008862014-04-15 04:59:12 +0000691 return nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000692}
693
Cong Houe93b8e12015-12-22 18:56:14 +0000694/// Get the raw edge probability for the edge. If can't find it, return a
695/// default probability 1/N where N is the number of successors. Here an edge is
696/// specified using PredBlock and an
697/// index to the successors.
698BranchProbability
699BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
700 unsigned IndexInSuccessors) const {
701 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick49371f32011-06-04 01:16:30 +0000702
Cong Houe93b8e12015-12-22 18:56:14 +0000703 if (I != Probs.end())
Andrew Trick49371f32011-06-04 01:16:30 +0000704 return I->second;
705
Cong Houe93b8e12015-12-22 18:56:14 +0000706 return {1,
707 static_cast<uint32_t>(std::distance(succ_begin(Src), succ_end(Src)))};
Andrew Trick49371f32011-06-04 01:16:30 +0000708}
709
Cong Houd97c1002015-12-01 05:29:22 +0000710BranchProbability
711BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
712 succ_const_iterator Dst) const {
713 return getEdgeProbability(Src, Dst.getSuccessorIndex());
714}
715
Cong Houe93b8e12015-12-22 18:56:14 +0000716/// Get the raw edge probability calculated for the block pair. This returns the
717/// sum of all raw edge probabilities from Src to Dst.
718BranchProbability
719BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
720 const BasicBlock *Dst) const {
721 auto Prob = BranchProbability::getZero();
722 bool FoundProb = false;
723 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
724 if (*I == Dst) {
725 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
726 if (MapI != Probs.end()) {
727 FoundProb = true;
728 Prob += MapI->second;
729 }
730 }
731 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
732 return FoundProb ? Prob : BranchProbability(1, succ_num);
733}
734
735/// Set the edge probability for a given edge specified by PredBlock and an
736/// index to the successors.
737void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
738 unsigned IndexInSuccessors,
739 BranchProbability Prob) {
740 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000741 Handles.insert(BasicBlockCallbackVH(Src, this));
Cong Houe93b8e12015-12-22 18:56:14 +0000742 DEBUG(dbgs() << "set edge " << Src->getName() << " -> " << IndexInSuccessors
743 << " successor probability to " << Prob << "\n");
744}
745
Andrew Trick49371f32011-06-04 01:16:30 +0000746raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000747BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
748 const BasicBlock *Src,
749 const BasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +0000750 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000751 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000752 << " probability is " << Prob
753 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +0000754
755 return OS;
756}
Cong Houab23bfb2015-07-15 22:48:29 +0000757
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000758void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
759 for (auto I = Probs.begin(), E = Probs.end(); I != E; ++I) {
760 auto Key = I->first;
761 if (Key.first == BB)
762 Probs.erase(Key);
763 }
764}
765
John Brawnda4a68a2017-06-08 09:44:40 +0000766void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
767 const TargetLibraryInfo *TLI) {
Cong Houab23bfb2015-07-15 22:48:29 +0000768 DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
769 << " ----\n\n");
770 LastF = &F; // Store the last function we ran on for printing.
771 assert(PostDominatedByUnreachable.empty());
772 assert(PostDominatedByColdCall.empty());
773
774 // Walk the basic blocks in post-order so that we can build up state about
775 // the successors of a block iteratively.
776 for (auto BB : post_order(&F.getEntryBlock())) {
777 DEBUG(dbgs() << "Computing probabilities for " << BB->getName() << "\n");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000778 updatePostDominatedByUnreachable(BB);
779 updatePostDominatedByColdCall(BB);
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000780 // If there is no at least two successors, no sense to set probability.
781 if (BB->getTerminator()->getNumSuccessors() < 2)
782 continue;
Cong Houab23bfb2015-07-15 22:48:29 +0000783 if (calcMetadataWeights(BB))
784 continue;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000785 if (calcUnreachableHeuristics(BB))
786 continue;
Cong Houab23bfb2015-07-15 22:48:29 +0000787 if (calcColdCallHeuristics(BB))
788 continue;
789 if (calcLoopBranchHeuristics(BB, LI))
790 continue;
791 if (calcPointerHeuristics(BB))
792 continue;
John Brawnda4a68a2017-06-08 09:44:40 +0000793 if (calcZeroHeuristics(BB, TLI))
Cong Houab23bfb2015-07-15 22:48:29 +0000794 continue;
795 if (calcFloatingPointHeuristics(BB))
796 continue;
797 calcInvokeHeuristics(BB);
798 }
799
800 PostDominatedByUnreachable.clear();
801 PostDominatedByColdCall.clear();
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +0000802
803 if (PrintBranchProb &&
804 (PrintBranchProbFuncName.empty() ||
805 F.getName().equals(PrintBranchProbFuncName))) {
806 print(dbgs());
807 }
Cong Houab23bfb2015-07-15 22:48:29 +0000808}
809
810void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
811 AnalysisUsage &AU) const {
812 AU.addRequired<LoopInfoWrapperPass>();
John Brawnda4a68a2017-06-08 09:44:40 +0000813 AU.addRequired<TargetLibraryInfoWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +0000814 AU.setPreservesAll();
815}
816
817bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
818 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
John Brawnda4a68a2017-06-08 09:44:40 +0000819 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
820 BPI.calculate(F, LI, &TLI);
Cong Houab23bfb2015-07-15 22:48:29 +0000821 return false;
822}
823
824void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
825
826void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
827 const Module *) const {
828 BPI.print(OS);
829}
Xinliang David Li6e5dd412016-05-05 02:59:57 +0000830
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000831AnalysisKey BranchProbabilityAnalysis::Key;
Xinliang David Li6e5dd412016-05-05 02:59:57 +0000832BranchProbabilityInfo
Sean Silva36e0d012016-08-09 00:28:15 +0000833BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +0000834 BranchProbabilityInfo BPI;
John Brawnda4a68a2017-06-08 09:44:40 +0000835 BPI.calculate(F, AM.getResult<LoopAnalysis>(F), &AM.getResult<TargetLibraryAnalysis>(F));
Xinliang David Li6e5dd412016-05-05 02:59:57 +0000836 return BPI;
837}
838
839PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +0000840BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +0000841 OS << "Printing analysis results of BPI for function "
842 << "'" << F.getName() << "':"
843 << "\n";
844 AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
845 return PreservedAnalyses::all();
846}