blob: 5eb95003f5d8c79a94745635dc942efca5921e76 [file] [log] [blame]
Eugene Zelenko38c02bc2017-07-21 21:37:46 +00001//===- BranchProbabilityInfo.cpp - Branch Probability Analysis ------------===//
Andrew Trick49371f32011-06-04 01:16:30 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Trick49371f32011-06-04 01:16:30 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Loops should be simplified before this analysis.
10//
11//===----------------------------------------------------------------------===//
12
Chandler Carruthed0881b2012-12-03 16:50:05 +000013#include "llvm/Analysis/BranchProbabilityInfo.h"
14#include "llvm/ADT/PostOrderIterator.h"
Geoff Berryeed65312017-11-01 15:16:50 +000015#include "llvm/ADT/SCCIterator.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"
Mikael Holmen2ca16892018-05-17 09:05:40 +000024#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Function.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000026#include "llvm/IR/InstrTypes.h"
27#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Instructions.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Metadata.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000031#include "llvm/IR/PassManager.h"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Value.h"
34#include "llvm/Pass.h"
35#include "llvm/Support/BranchProbability.h"
36#include "llvm/Support/Casting.h"
Andrew Trick3d4e64b2011-06-11 01:05:22 +000037#include "llvm/Support/Debug.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000038#include "llvm/Support/raw_ostream.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000039#include <cassert>
40#include <cstdint>
41#include <iterator>
42#include <utility>
Andrew Trick49371f32011-06-04 01:16:30 +000043
44using namespace llvm;
45
Chandler Carruthf1221bd2014-04-22 02:48:03 +000046#define DEBUG_TYPE "branch-prob"
47
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +000048static cl::opt<bool> PrintBranchProb(
49 "print-bpi", cl::init(false), cl::Hidden,
50 cl::desc("Print the branch probability info."));
51
52cl::opt<std::string> PrintBranchProbFuncName(
53 "print-bpi-func-name", cl::Hidden,
54 cl::desc("The option to specify the name of the function "
55 "whose branch probability info is printed."));
56
Cong Houab23bfb2015-07-15 22:48:29 +000057INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000058 "Branch Probability Analysis", false, true)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000059INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
John Brawnda4a68a2017-06-08 09:44:40 +000060INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Cong Houab23bfb2015-07-15 22:48:29 +000061INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000062 "Branch Probability Analysis", false, true)
63
Cong Houab23bfb2015-07-15 22:48:29 +000064char BranchProbabilityInfoWrapperPass::ID = 0;
Andrew Trick49371f32011-06-04 01:16:30 +000065
Chandler Carruth7a0094a2011-10-24 01:40:45 +000066// Weights are for internal use only. They are used by heuristics to help to
67// estimate edges' probability. Example:
68//
69// Using "Loop Branch Heuristics" we predict weights of edges for the
70// block BB2.
71// ...
72// |
73// V
74// BB1<-+
75// | |
76// | | (Weight = 124)
77// V |
78// BB2--+
79// |
80// | (Weight = 4)
81// V
82// BB3
83//
84// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
85// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
86static const uint32_t LBH_TAKEN_WEIGHT = 124;
87static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
John Brawn29bbed32018-02-23 17:17:31 +000088// Unlikely edges within a loop are half as likely as other edges
89static const uint32_t LBH_UNLIKELY_WEIGHT = 62;
Andrew Trick49371f32011-06-04 01:16:30 +000090
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000091/// Unreachable-terminating branch taken probability.
Chandler Carruth7111f452011-10-24 12:01:08 +000092///
Serguei Katkovba831f72017-05-18 06:11:56 +000093/// This is the probability for a branch being taken to a block that terminates
Chandler Carruth7111f452011-10-24 12:01:08 +000094/// (eventually) in unreachable. These are predicted as unlikely as possible.
Serguei Katkovba831f72017-05-18 06:11:56 +000095/// All reachable probability will equally share the remaining part.
96static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +000097
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000098/// Weight for a branch taken going into a cold block.
Diego Novilloc6399532013-05-24 12:26:52 +000099///
100/// This is the weight for a branch taken toward a block marked
101/// cold. A block is marked cold if it's postdominated by a
102/// block containing a call to a cold function. Cold functions
103/// are those marked with attribute 'cold'.
104static const uint32_t CC_TAKEN_WEIGHT = 4;
105
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000106/// Weight for a branch not-taken into a cold block.
Diego Novilloc6399532013-05-24 12:26:52 +0000107///
108/// This is the weight for a branch not taken toward a block marked
109/// cold.
110static const uint32_t CC_NONTAKEN_WEIGHT = 64;
111
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000112static const uint32_t PH_TAKEN_WEIGHT = 20;
113static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000114
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000115static const uint32_t ZH_TAKEN_WEIGHT = 20;
116static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000117
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000118static const uint32_t FPH_TAKEN_WEIGHT = 20;
119static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000120
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000121/// Invoke-terminating normal branch taken weight
Bill Wendlinge1c54262012-08-15 12:22:35 +0000122///
123/// This is the weight for branching to the normal destination of an invoke
124/// instruction. We expect this to happen most of the time. Set the weight to an
125/// absurdly high value so that nested loops subsume it.
126static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
127
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000128/// Invoke-terminating normal branch not-taken weight.
Bill Wendlinge1c54262012-08-15 12:22:35 +0000129///
130/// This is the weight for branching to the unwind destination of an invoke
131/// instruction. This is essentially never taken.
132static const uint32_t IH_NONTAKEN_WEIGHT = 1;
133
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000134/// Add \p BB to PostDominatedByUnreachable set if applicable.
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000135void
136BranchProbabilityInfo::updatePostDominatedByUnreachable(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000137 const Instruction *TI = BB->getTerminator();
Chandler Carruth7111f452011-10-24 12:01:08 +0000138 if (TI->getNumSuccessors() == 0) {
Sanjoy Das432c1c32016-04-18 19:01:28 +0000139 if (isa<UnreachableInst>(TI) ||
140 // If this block is terminated by a call to
141 // @llvm.experimental.deoptimize then treat it like an unreachable since
142 // the @llvm.experimental.deoptimize call is expected to practically
143 // never execute.
144 BB->getTerminatingDeoptimizeCall())
Chandler Carruth7111f452011-10-24 12:01:08 +0000145 PostDominatedByUnreachable.insert(BB);
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000146 return;
Chandler Carruth7111f452011-10-24 12:01:08 +0000147 }
148
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000149 // If the terminator is an InvokeInst, check only the normal destination block
150 // as the unwind edge of InvokeInst is also very unlikely taken.
151 if (auto *II = dyn_cast<InvokeInst>(TI)) {
152 if (PostDominatedByUnreachable.count(II->getNormalDest()))
153 PostDominatedByUnreachable.insert(BB);
154 return;
155 }
156
157 for (auto *I : successors(BB))
158 // If any of successor is not post dominated then BB is also not.
159 if (!PostDominatedByUnreachable.count(I))
160 return;
161
162 PostDominatedByUnreachable.insert(BB);
163}
164
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000165/// Add \p BB to PostDominatedByColdCall set if applicable.
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000166void
167BranchProbabilityInfo::updatePostDominatedByColdCall(const BasicBlock *BB) {
168 assert(!PostDominatedByColdCall.count(BB));
Chandler Carruthedb12a82018-10-15 10:04:59 +0000169 const Instruction *TI = BB->getTerminator();
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000170 if (TI->getNumSuccessors() == 0)
171 return;
172
173 // If all of successor are post dominated then BB is also done.
174 if (llvm::all_of(successors(BB), [&](const BasicBlock *SuccBB) {
175 return PostDominatedByColdCall.count(SuccBB);
176 })) {
177 PostDominatedByColdCall.insert(BB);
178 return;
179 }
180
181 // If the terminator is an InvokeInst, check only the normal destination
182 // block as the unwind edge of InvokeInst is also very unlikely taken.
183 if (auto *II = dyn_cast<InvokeInst>(TI))
184 if (PostDominatedByColdCall.count(II->getNormalDest())) {
185 PostDominatedByColdCall.insert(BB);
186 return;
187 }
188
189 // Otherwise, if the block itself contains a cold function, add it to the
190 // set of blocks post-dominated by a cold call.
191 for (auto &I : *BB)
192 if (const CallInst *CI = dyn_cast<CallInst>(&I))
193 if (CI->hasFnAttr(Attribute::Cold)) {
194 PostDominatedByColdCall.insert(BB);
195 return;
196 }
197}
198
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000199/// Calculate edge weights for successors lead to unreachable.
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000200///
201/// Predict that a successor which leads necessarily to an
202/// unreachable-terminated block as extremely unlikely.
203bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000204 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000205 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000206 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000207 assert(!isa<InvokeInst>(TI) &&
208 "Invokes should have already been handled by calcInvokeHeuristics");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000209
Manman Rencf104462012-08-24 18:14:27 +0000210 SmallVector<unsigned, 4> UnreachableEdges;
211 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000212
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000213 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Chandler Carruth7111f452011-10-24 12:01:08 +0000214 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000215 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000216 else
Manman Rencf104462012-08-24 18:14:27 +0000217 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000218
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000219 // Skip probabilities if all were reachable.
220 if (UnreachableEdges.empty())
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000221 return false;
Jun Bum Lima23e5f72015-12-21 22:00:51 +0000222
Cong Houe93b8e12015-12-22 18:56:14 +0000223 if (ReachableEdges.empty()) {
224 BranchProbability Prob(1, UnreachableEdges.size());
225 for (unsigned SuccIdx : UnreachableEdges)
226 setEdgeProbability(BB, SuccIdx, Prob);
Chandler Carruth7111f452011-10-24 12:01:08 +0000227 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000228 }
229
Serguei Katkovba831f72017-05-18 06:11:56 +0000230 auto UnreachableProb = UR_TAKEN_PROB;
231 auto ReachableProb =
232 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
233 ReachableEdges.size();
Cong Houe93b8e12015-12-22 18:56:14 +0000234
235 for (unsigned SuccIdx : UnreachableEdges)
236 setEdgeProbability(BB, SuccIdx, UnreachableProb);
237 for (unsigned SuccIdx : ReachableEdges)
238 setEdgeProbability(BB, SuccIdx, ReachableProb);
Chandler Carruth7111f452011-10-24 12:01:08 +0000239
240 return true;
241}
242
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000243// Propagate existing explicit probabilities from either profile data or
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000244// 'expect' intrinsic processing. Examine metadata against unreachable
245// heuristic. The probability of the edge coming to unreachable block is
246// set to min of metadata and unreachable heuristic.
Mehdi Aminia7978772016-04-07 21:59:28 +0000247bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000248 const Instruction *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000249 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Rong Xu15848e52017-08-23 21:36:02 +0000250 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI)))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000251 return false;
252
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000253 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000254 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000255 return false;
256
Diego Novillode5b8012015-05-07 17:22:06 +0000257 // Check that the number of successors is manageable.
258 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
259
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000260 // Ensure there are weights for all of the successors. Note that the first
261 // operand to the metadata node is a name, not a weight.
262 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000263 return false;
264
Diego Novillode5b8012015-05-07 17:22:06 +0000265 // Build up the final weights that will be used in a temporary buffer.
266 // Compute the sum of all weights to later decide whether they need to
267 // be scaled to fit in 32 bits.
268 uint64_t WeightSum = 0;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000269 SmallVector<uint32_t, 2> Weights;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000270 SmallVector<unsigned, 2> UnreachableIdxs;
271 SmallVector<unsigned, 2> ReachableIdxs;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000272 Weights.reserve(TI->getNumSuccessors());
273 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000274 ConstantInt *Weight =
275 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i));
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000276 if (!Weight)
277 return false;
Diego Novillode5b8012015-05-07 17:22:06 +0000278 assert(Weight->getValue().getActiveBits() <= 32 &&
279 "Too many bits for uint32_t");
280 Weights.push_back(Weight->getZExtValue());
281 WeightSum += Weights.back();
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000282 if (PostDominatedByUnreachable.count(TI->getSuccessor(i - 1)))
283 UnreachableIdxs.push_back(i - 1);
284 else
285 ReachableIdxs.push_back(i - 1);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000286 }
287 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
Diego Novillode5b8012015-05-07 17:22:06 +0000288
289 // If the sum of weights does not fit in 32 bits, scale every weight down
290 // accordingly.
291 uint64_t ScalingFactor =
292 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
293
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000294 if (ScalingFactor > 1) {
295 WeightSum = 0;
296 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
297 Weights[i] /= ScalingFactor;
298 WeightSum += Weights[i];
299 }
Diego Novillode5b8012015-05-07 17:22:06 +0000300 }
Serguei Katkov63c9c812017-05-12 07:50:06 +0000301 assert(WeightSum <= UINT32_MAX &&
302 "Expected weights to scale down to 32 bits");
Cong Hou6a2c71a2015-12-22 23:45:55 +0000303
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000304 if (WeightSum == 0 || ReachableIdxs.size() == 0) {
Cong Hou6a2c71a2015-12-22 23:45:55 +0000305 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000306 Weights[i] = 1;
307 WeightSum = TI->getNumSuccessors();
Cong Hou6a2c71a2015-12-22 23:45:55 +0000308 }
Cong Houe93b8e12015-12-22 18:56:14 +0000309
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000310 // Set the probability.
311 SmallVector<BranchProbability, 2> BP;
312 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
313 BP.push_back({ Weights[i], static_cast<uint32_t>(WeightSum) });
314
315 // Examine the metadata against unreachable heuristic.
316 // If the unreachable heuristic is more strong then we use it for this edge.
317 if (UnreachableIdxs.size() > 0 && ReachableIdxs.size() > 0) {
318 auto ToDistribute = BranchProbability::getZero();
Serguei Katkovba831f72017-05-18 06:11:56 +0000319 auto UnreachableProb = UR_TAKEN_PROB;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000320 for (auto i : UnreachableIdxs)
321 if (UnreachableProb < BP[i]) {
322 ToDistribute += BP[i] - UnreachableProb;
323 BP[i] = UnreachableProb;
324 }
325
326 // If we modified the probability of some edges then we must distribute
327 // the difference between reachable blocks.
328 if (ToDistribute > BranchProbability::getZero()) {
329 BranchProbability PerEdge = ToDistribute / ReachableIdxs.size();
Serguei Katkov63c9c812017-05-12 07:50:06 +0000330 for (auto i : ReachableIdxs)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000331 BP[i] += PerEdge;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000332 }
333 }
334
335 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
336 setEdgeProbability(BB, i, BP[i]);
337
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000338 return true;
339}
340
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000341/// Calculate edge weights for edges leading to cold blocks.
Diego Novilloc6399532013-05-24 12:26:52 +0000342///
343/// A cold block is one post-dominated by a block with a call to a
344/// cold function. Those edges are unlikely to be taken, so we give
345/// them relatively low weight.
346///
347/// Return true if we could compute the weights for cold edges.
348/// Return false, otherwise.
Mehdi Aminia7978772016-04-07 21:59:28 +0000349bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000350 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000351 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000352 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000353 assert(!isa<InvokeInst>(TI) &&
354 "Invokes should have already been handled by calcInvokeHeuristics");
Diego Novilloc6399532013-05-24 12:26:52 +0000355
356 // Determine which successors are post-dominated by a cold block.
357 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000358 SmallVector<unsigned, 4> NormalEdges;
Mehdi Aminia7978772016-04-07 21:59:28 +0000359 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Diego Novilloc6399532013-05-24 12:26:52 +0000360 if (PostDominatedByColdCall.count(*I))
361 ColdEdges.push_back(I.getSuccessorIndex());
362 else
363 NormalEdges.push_back(I.getSuccessorIndex());
364
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000365 // Skip probabilities if no cold edges.
366 if (ColdEdges.empty())
Diego Novilloc6399532013-05-24 12:26:52 +0000367 return false;
368
Cong Houe93b8e12015-12-22 18:56:14 +0000369 if (NormalEdges.empty()) {
370 BranchProbability Prob(1, ColdEdges.size());
371 for (unsigned SuccIdx : ColdEdges)
372 setEdgeProbability(BB, SuccIdx, Prob);
Diego Novilloc6399532013-05-24 12:26:52 +0000373 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000374 }
375
Vedant Kumara4bd1462016-12-17 01:02:08 +0000376 auto ColdProb = BranchProbability::getBranchProbability(
377 CC_TAKEN_WEIGHT,
378 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
379 auto NormalProb = BranchProbability::getBranchProbability(
380 CC_NONTAKEN_WEIGHT,
381 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
Cong Houe93b8e12015-12-22 18:56:14 +0000382
383 for (unsigned SuccIdx : ColdEdges)
384 setEdgeProbability(BB, SuccIdx, ColdProb);
385 for (unsigned SuccIdx : NormalEdges)
386 setEdgeProbability(BB, SuccIdx, NormalProb);
Diego Novilloc6399532013-05-24 12:26:52 +0000387
388 return true;
389}
390
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000391// Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
Andrew Trick49371f32011-06-04 01:16:30 +0000392// between two pointer or pointer and NULL will fail.
Mehdi Aminia7978772016-04-07 21:59:28 +0000393bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
394 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Andrew Trick49371f32011-06-04 01:16:30 +0000395 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000396 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000397
398 Value *Cond = BI->getCondition();
399 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000400 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000401 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000402
403 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000404
405 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000406 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000407
Nick Lewycky75b20532011-06-04 02:07:10 +0000408 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000409
Andrew Trick49371f32011-06-04 01:16:30 +0000410 // p != 0 -> isProb = true
411 // p == 0 -> isProb = false
412 // p != q -> isProb = true
413 // p == q -> isProb = false;
Manman Rencf104462012-08-24 18:14:27 +0000414 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000415 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000416 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000417 std::swap(TakenIdx, NonTakenIdx);
Andrew Trick49371f32011-06-04 01:16:30 +0000418
Cong Houe93b8e12015-12-22 18:56:14 +0000419 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
420 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
421 setEdgeProbability(BB, TakenIdx, TakenProb);
422 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000423 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000424}
425
Geoff Berryeed65312017-11-01 15:16:50 +0000426static int getSCCNum(const BasicBlock *BB,
427 const BranchProbabilityInfo::SccInfo &SccI) {
428 auto SccIt = SccI.SccNums.find(BB);
429 if (SccIt == SccI.SccNums.end())
430 return -1;
431 return SccIt->second;
432}
433
434// Consider any block that is an entry point to the SCC as a header.
435static bool isSCCHeader(const BasicBlock *BB, int SccNum,
436 BranchProbabilityInfo::SccInfo &SccI) {
437 assert(getSCCNum(BB, SccI) == SccNum);
438
439 // Lazily compute the set of headers for a given SCC and cache the results
440 // in the SccHeaderMap.
441 if (SccI.SccHeaders.size() <= static_cast<unsigned>(SccNum))
442 SccI.SccHeaders.resize(SccNum + 1);
443 auto &HeaderMap = SccI.SccHeaders[SccNum];
444 bool Inserted;
445 BranchProbabilityInfo::SccHeaderMap::iterator HeaderMapIt;
446 std::tie(HeaderMapIt, Inserted) = HeaderMap.insert(std::make_pair(BB, false));
447 if (Inserted) {
448 bool IsHeader = llvm::any_of(make_range(pred_begin(BB), pred_end(BB)),
449 [&](const BasicBlock *Pred) {
450 return getSCCNum(Pred, SccI) != SccNum;
451 });
452 HeaderMapIt->second = IsHeader;
453 return IsHeader;
454 } else
455 return HeaderMapIt->second;
456}
457
John Brawn29bbed32018-02-23 17:17:31 +0000458// Compute the unlikely successors to the block BB in the loop L, specifically
459// those that are unlikely because this is a loop, and add them to the
460// UnlikelyBlocks set.
461static void
462computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
463 SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
464 // Sometimes in a loop we have a branch whose condition is made false by
465 // taking it. This is typically something like
466 // int n = 0;
467 // while (...) {
468 // if (++n >= MAX) {
469 // n = 0;
470 // }
471 // }
472 // In this sort of situation taking the branch means that at the very least it
473 // won't be taken again in the next iteration of the loop, so we should
474 // consider it less likely than a typical branch.
475 //
476 // We detect this by looking back through the graph of PHI nodes that sets the
477 // value that the condition depends on, and seeing if we can reach a successor
478 // block which can be determined to make the condition false.
479 //
480 // FIXME: We currently consider unlikely blocks to be half as likely as other
481 // blocks, but if we consider the example above the likelyhood is actually
482 // 1/MAX. We could therefore be more precise in how unlikely we consider
483 // blocks to be, but it would require more careful examination of the form
484 // of the comparison expression.
485 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
486 if (!BI || !BI->isConditional())
487 return;
488
489 // Check if the branch is based on an instruction compared with a constant
490 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
491 if (!CI || !isa<Instruction>(CI->getOperand(0)) ||
492 !isa<Constant>(CI->getOperand(1)))
493 return;
494
495 // Either the instruction must be a PHI, or a chain of operations involving
496 // constants that ends in a PHI which we can then collapse into a single value
497 // if the PHI value is known.
498 Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0));
499 PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
500 Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1));
501 // Collect the instructions until we hit a PHI
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000502 SmallVector<BinaryOperator *, 1> InstChain;
John Brawn29bbed32018-02-23 17:17:31 +0000503 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
504 isa<Constant>(CmpLHS->getOperand(1))) {
505 // Stop if the chain extends outside of the loop
506 if (!L->contains(CmpLHS))
507 return;
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000508 InstChain.push_back(cast<BinaryOperator>(CmpLHS));
John Brawn29bbed32018-02-23 17:17:31 +0000509 CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
510 if (CmpLHS)
511 CmpPHI = dyn_cast<PHINode>(CmpLHS);
512 }
513 if (!CmpPHI || !L->contains(CmpPHI))
514 return;
515
516 // Trace the phi node to find all values that come from successors of BB
517 SmallPtrSet<PHINode*, 8> VisitedInsts;
518 SmallVector<PHINode*, 8> WorkList;
519 WorkList.push_back(CmpPHI);
520 VisitedInsts.insert(CmpPHI);
521 while (!WorkList.empty()) {
522 PHINode *P = WorkList.back();
523 WorkList.pop_back();
524 for (BasicBlock *B : P->blocks()) {
525 // Skip blocks that aren't part of the loop
526 if (!L->contains(B))
527 continue;
528 Value *V = P->getIncomingValueForBlock(B);
529 // If the source is a PHI add it to the work list if we haven't
530 // already visited it.
531 if (PHINode *PN = dyn_cast<PHINode>(V)) {
532 if (VisitedInsts.insert(PN).second)
533 WorkList.push_back(PN);
534 continue;
535 }
536 // If this incoming value is a constant and B is a successor of BB, then
537 // we can constant-evaluate the compare to see if it makes the branch be
538 // taken or not.
539 Constant *CmpLHSConst = dyn_cast<Constant>(V);
540 if (!CmpLHSConst ||
541 std::find(succ_begin(BB), succ_end(BB), B) == succ_end(BB))
542 continue;
543 // First collapse InstChain
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000544 for (Instruction *I : llvm::reverse(InstChain)) {
John Brawn29bbed32018-02-23 17:17:31 +0000545 CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst,
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000546 cast<Constant>(I->getOperand(1)), true);
John Brawn29bbed32018-02-23 17:17:31 +0000547 if (!CmpLHSConst)
548 break;
549 }
550 if (!CmpLHSConst)
551 continue;
552 // Now constant-evaluate the compare
553 Constant *Result = ConstantExpr::getCompare(CI->getPredicate(),
554 CmpLHSConst, CmpConst, true);
555 // If the result means we don't branch to the block then that block is
556 // unlikely.
557 if (Result &&
558 ((Result->isZeroValue() && B == BI->getSuccessor(0)) ||
559 (Result->isOneValue() && B == BI->getSuccessor(1))))
560 UnlikelyBlocks.insert(B);
561 }
562 }
563}
564
Andrew Trick49371f32011-06-04 01:16:30 +0000565// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
566// as taken, exiting edges as not-taken.
Mehdi Aminia7978772016-04-07 21:59:28 +0000567bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
Geoff Berryeed65312017-11-01 15:16:50 +0000568 const LoopInfo &LI,
569 SccInfo &SccI) {
570 int SccNum;
Cong Houab23bfb2015-07-15 22:48:29 +0000571 Loop *L = LI.getLoopFor(BB);
Geoff Berryeed65312017-11-01 15:16:50 +0000572 if (!L) {
573 SccNum = getSCCNum(BB, SccI);
574 if (SccNum < 0)
575 return false;
576 }
Andrew Trick49371f32011-06-04 01:16:30 +0000577
John Brawn29bbed32018-02-23 17:17:31 +0000578 SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks;
579 if (L)
580 computeUnlikelySuccessors(BB, L, UnlikelyBlocks);
581
Manman Rencf104462012-08-24 18:14:27 +0000582 SmallVector<unsigned, 8> BackEdges;
583 SmallVector<unsigned, 8> ExitingEdges;
584 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
John Brawn29bbed32018-02-23 17:17:31 +0000585 SmallVector<unsigned, 8> UnlikelyEdges;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000586
Mehdi Aminia7978772016-04-07 21:59:28 +0000587 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Geoff Berryeed65312017-11-01 15:16:50 +0000588 // Use LoopInfo if we have it, otherwise fall-back to SCC info to catch
589 // irreducible loops.
590 if (L) {
John Brawn29bbed32018-02-23 17:17:31 +0000591 if (UnlikelyBlocks.count(*I) != 0)
592 UnlikelyEdges.push_back(I.getSuccessorIndex());
593 else if (!L->contains(*I))
Geoff Berryeed65312017-11-01 15:16:50 +0000594 ExitingEdges.push_back(I.getSuccessorIndex());
595 else if (L->getHeader() == *I)
596 BackEdges.push_back(I.getSuccessorIndex());
597 else
598 InEdges.push_back(I.getSuccessorIndex());
599 } else {
600 if (getSCCNum(*I, SccI) != SccNum)
601 ExitingEdges.push_back(I.getSuccessorIndex());
602 else if (isSCCHeader(*I, SccNum, SccI))
603 BackEdges.push_back(I.getSuccessorIndex());
604 else
605 InEdges.push_back(I.getSuccessorIndex());
606 }
Andrew Trick49371f32011-06-04 01:16:30 +0000607 }
608
John Brawn29bbed32018-02-23 17:17:31 +0000609 if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty())
Akira Hatanaka5638b892014-04-14 16:56:19 +0000610 return false;
611
Cong Houe93b8e12015-12-22 18:56:14 +0000612 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
613 // normalize them so that they sum up to one.
Cong Houe93b8e12015-12-22 18:56:14 +0000614 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
615 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
John Brawn29bbed32018-02-23 17:17:31 +0000616 (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) +
Cong Houe93b8e12015-12-22 18:56:14 +0000617 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
Andrew Trick49371f32011-06-04 01:16:30 +0000618
Cong Houe93b8e12015-12-22 18:56:14 +0000619 if (uint32_t numBackEdges = BackEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000620 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
621 auto Prob = TakenProb / numBackEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000622 for (unsigned SuccIdx : BackEdges)
623 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000624 }
625
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000626 if (uint32_t numInEdges = InEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000627 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
628 auto Prob = TakenProb / numInEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000629 for (unsigned SuccIdx : InEdges)
630 setEdgeProbability(BB, SuccIdx, Prob);
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000631 }
632
Chandler Carruth32f46e72011-10-25 09:47:41 +0000633 if (uint32_t numExitingEdges = ExitingEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000634 BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT,
635 Denom);
636 auto Prob = NotTakenProb / numExitingEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000637 for (unsigned SuccIdx : ExitingEdges)
638 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000639 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000640
John Brawn29bbed32018-02-23 17:17:31 +0000641 if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) {
642 BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT,
643 Denom);
644 auto Prob = UnlikelyProb / numUnlikelyEdges;
645 for (unsigned SuccIdx : UnlikelyEdges)
646 setEdgeProbability(BB, SuccIdx, Prob);
647 }
648
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000649 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000650}
651
John Brawnda4a68a2017-06-08 09:44:40 +0000652bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
653 const TargetLibraryInfo *TLI) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000654 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000655 if (!BI || !BI->isConditional())
656 return false;
657
658 Value *Cond = BI->getCondition();
659 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
660 if (!CI)
661 return false;
662
Sam Parker0b53e842019-02-15 11:50:21 +0000663 auto GetConstantInt = [](Value *V) {
664 if (auto *I = dyn_cast<BitCastInst>(V))
665 return dyn_cast<ConstantInt>(I->getOperand(0));
666 return dyn_cast<ConstantInt>(V);
667 };
668
Jakub Staszak17af66a2011-07-31 03:27:24 +0000669 Value *RHS = CI->getOperand(1);
Sam Parker0b53e842019-02-15 11:50:21 +0000670 ConstantInt *CV = GetConstantInt(RHS);
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000671 if (!CV)
Jakub Staszak17af66a2011-07-31 03:27:24 +0000672 return false;
673
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000674 // If the LHS is the result of AND'ing a value with a single bit bitmask,
675 // we don't have information about probabilities.
676 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
677 if (LHS->getOpcode() == Instruction::And)
678 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
Craig Topper4e22ee62017-08-04 16:59:29 +0000679 if (AndRHS->getValue().isPowerOf2())
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000680 return false;
681
John Brawnda4a68a2017-06-08 09:44:40 +0000682 // Check if the LHS is the return value of a library function
683 LibFunc Func = NumLibFuncs;
684 if (TLI)
685 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
686 if (Function *CalledFn = Call->getCalledFunction())
687 TLI->getLibFunc(*CalledFn, Func);
688
Jakub Staszak17af66a2011-07-31 03:27:24 +0000689 bool isProb;
John Brawnda4a68a2017-06-08 09:44:40 +0000690 if (Func == LibFunc_strcasecmp ||
691 Func == LibFunc_strcmp ||
692 Func == LibFunc_strncasecmp ||
693 Func == LibFunc_strncmp ||
694 Func == LibFunc_memcmp) {
695 // strcmp and similar functions return zero, negative, or positive, if the
696 // first string is equal, less, or greater than the second. We consider it
697 // likely that the strings are not equal, so a comparison with zero is
698 // probably false, but also a comparison with any other number is also
699 // probably false given that what exactly is returned for nonzero values is
700 // not specified. Any kind of comparison other than equality we know
701 // nothing about.
702 switch (CI->getPredicate()) {
703 case CmpInst::ICMP_EQ:
704 isProb = false;
705 break;
706 case CmpInst::ICMP_NE:
707 isProb = true;
708 break;
709 default:
710 return false;
711 }
712 } else if (CV->isZero()) {
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000713 switch (CI->getPredicate()) {
714 case CmpInst::ICMP_EQ:
715 // X == 0 -> Unlikely
716 isProb = false;
717 break;
718 case CmpInst::ICMP_NE:
719 // X != 0 -> Likely
720 isProb = true;
721 break;
722 case CmpInst::ICMP_SLT:
723 // X < 0 -> Unlikely
724 isProb = false;
725 break;
726 case CmpInst::ICMP_SGT:
727 // X > 0 -> Likely
728 isProb = true;
729 break;
730 default:
731 return false;
732 }
733 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
734 // InstCombine canonicalizes X <= 0 into X < 1.
735 // X <= 0 -> Unlikely
Jakub Staszak17af66a2011-07-31 03:27:24 +0000736 isProb = false;
Craig Topper79ab6432017-07-06 18:39:47 +0000737 } else if (CV->isMinusOne()) {
Hal Finkel4d949302013-11-01 10:58:22 +0000738 switch (CI->getPredicate()) {
739 case CmpInst::ICMP_EQ:
740 // X == -1 -> Unlikely
741 isProb = false;
742 break;
743 case CmpInst::ICMP_NE:
744 // X != -1 -> Likely
745 isProb = true;
746 break;
747 case CmpInst::ICMP_SGT:
748 // InstCombine canonicalizes X >= 0 into X > -1.
749 // X >= 0 -> Likely
750 isProb = true;
751 break;
752 default:
753 return false;
754 }
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000755 } else {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000756 return false;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000757 }
Jakub Staszak17af66a2011-07-31 03:27:24 +0000758
Manman Rencf104462012-08-24 18:14:27 +0000759 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszak17af66a2011-07-31 03:27:24 +0000760
761 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000762 std::swap(TakenIdx, NonTakenIdx);
Jakub Staszak17af66a2011-07-31 03:27:24 +0000763
Cong Houe93b8e12015-12-22 18:56:14 +0000764 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
765 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
766 setEdgeProbability(BB, TakenIdx, TakenProb);
767 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000768 return true;
769}
770
Mehdi Aminia7978772016-04-07 21:59:28 +0000771bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
772 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000773 if (!BI || !BI->isConditional())
774 return false;
775
776 Value *Cond = BI->getCondition();
777 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000778 if (!FCmp)
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000779 return false;
780
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000781 bool isProb;
782 if (FCmp->isEquality()) {
783 // f1 == f2 -> Unlikely
784 // f1 != f2 -> Likely
785 isProb = !FCmp->isTrueWhenEqual();
786 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
787 // !isnan -> Likely
788 isProb = true;
789 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
790 // isnan -> Unlikely
791 isProb = false;
792 } else {
793 return false;
794 }
795
Manman Rencf104462012-08-24 18:14:27 +0000796 unsigned TakenIdx = 0, NonTakenIdx = 1;
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000797
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000798 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000799 std::swap(TakenIdx, NonTakenIdx);
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000800
Cong Houe93b8e12015-12-22 18:56:14 +0000801 BranchProbability TakenProb(FPH_TAKEN_WEIGHT,
802 FPH_TAKEN_WEIGHT + FPH_NONTAKEN_WEIGHT);
803 setEdgeProbability(BB, TakenIdx, TakenProb);
804 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000805 return true;
806}
Jakub Staszak17af66a2011-07-31 03:27:24 +0000807
Mehdi Aminia7978772016-04-07 21:59:28 +0000808bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
809 const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000810 if (!II)
811 return false;
812
Cong Houe93b8e12015-12-22 18:56:14 +0000813 BranchProbability TakenProb(IH_TAKEN_WEIGHT,
814 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
815 setEdgeProbability(BB, 0 /*Index for Normal*/, TakenProb);
816 setEdgeProbability(BB, 1 /*Index for Unwind*/, TakenProb.getCompl());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000817 return true;
818}
819
Pete Cooperb9d2e342015-05-28 19:43:06 +0000820void BranchProbabilityInfo::releaseMemory() {
Cong Houe93b8e12015-12-22 18:56:14 +0000821 Probs.clear();
Pete Cooperb9d2e342015-05-28 19:43:06 +0000822}
823
Cong Houab23bfb2015-07-15 22:48:29 +0000824void BranchProbabilityInfo::print(raw_ostream &OS) const {
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000825 OS << "---- Branch Probabilities ----\n";
826 // We print the probabilities from the last function the analysis ran over,
827 // or the function it is currently running over.
828 assert(LastF && "Cannot print prior to running over a function");
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000829 for (const auto &BI : *LastF) {
830 for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
831 ++SI) {
832 printEdgeProbability(OS << " ", &BI, *SI);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000833 }
834 }
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000835}
836
Jakub Staszakefd94c82011-07-29 19:30:00 +0000837bool BranchProbabilityInfo::
838isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000839 // Hot probability is at least 4/5 = 80%
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000840 // FIXME: Compare against a static "hot" BranchProbability.
841 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick49371f32011-06-04 01:16:30 +0000842}
843
Mehdi Aminia7978772016-04-07 21:59:28 +0000844const BasicBlock *
845BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
Cong Houe93b8e12015-12-22 18:56:14 +0000846 auto MaxProb = BranchProbability::getZero();
Mehdi Aminia7978772016-04-07 21:59:28 +0000847 const BasicBlock *MaxSucc = nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000848
Mehdi Aminia7978772016-04-07 21:59:28 +0000849 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
850 const BasicBlock *Succ = *I;
Cong Houe93b8e12015-12-22 18:56:14 +0000851 auto Prob = getEdgeProbability(BB, Succ);
852 if (Prob > MaxProb) {
853 MaxProb = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000854 MaxSucc = Succ;
855 }
856 }
857
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000858 // Hot probability is at least 4/5 = 80%
Cong Houe93b8e12015-12-22 18:56:14 +0000859 if (MaxProb > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +0000860 return MaxSucc;
861
Craig Topper9f008862014-04-15 04:59:12 +0000862 return nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000863}
864
Cong Houe93b8e12015-12-22 18:56:14 +0000865/// Get the raw edge probability for the edge. If can't find it, return a
866/// default probability 1/N where N is the number of successors. Here an edge is
867/// specified using PredBlock and an
868/// index to the successors.
869BranchProbability
870BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
871 unsigned IndexInSuccessors) const {
872 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick49371f32011-06-04 01:16:30 +0000873
Cong Houe93b8e12015-12-22 18:56:14 +0000874 if (I != Probs.end())
Andrew Trick49371f32011-06-04 01:16:30 +0000875 return I->second;
876
Vedant Kumare0b5f862018-05-10 23:01:54 +0000877 return {1, static_cast<uint32_t>(succ_size(Src))};
Andrew Trick49371f32011-06-04 01:16:30 +0000878}
879
Cong Houd97c1002015-12-01 05:29:22 +0000880BranchProbability
881BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
882 succ_const_iterator Dst) const {
883 return getEdgeProbability(Src, Dst.getSuccessorIndex());
884}
885
Cong Houe93b8e12015-12-22 18:56:14 +0000886/// Get the raw edge probability calculated for the block pair. This returns the
887/// sum of all raw edge probabilities from Src to Dst.
888BranchProbability
889BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
890 const BasicBlock *Dst) const {
891 auto Prob = BranchProbability::getZero();
892 bool FoundProb = false;
893 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
894 if (*I == Dst) {
895 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
896 if (MapI != Probs.end()) {
897 FoundProb = true;
898 Prob += MapI->second;
899 }
900 }
901 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
902 return FoundProb ? Prob : BranchProbability(1, succ_num);
903}
904
905/// Set the edge probability for a given edge specified by PredBlock and an
906/// index to the successors.
907void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
908 unsigned IndexInSuccessors,
909 BranchProbability Prob) {
910 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000911 Handles.insert(BasicBlockCallbackVH(Src, this));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000912 LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
913 << IndexInSuccessors << " successor probability to " << Prob
914 << "\n");
Cong Houe93b8e12015-12-22 18:56:14 +0000915}
916
Andrew Trick49371f32011-06-04 01:16:30 +0000917raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000918BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
919 const BasicBlock *Src,
920 const BasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +0000921 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000922 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000923 << " probability is " << Prob
924 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +0000925
926 return OS;
927}
Cong Houab23bfb2015-07-15 22:48:29 +0000928
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000929void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
930 for (auto I = Probs.begin(), E = Probs.end(); I != E; ++I) {
931 auto Key = I->first;
932 if (Key.first == BB)
933 Probs.erase(Key);
934 }
935}
936
John Brawnda4a68a2017-06-08 09:44:40 +0000937void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
938 const TargetLibraryInfo *TLI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000939 LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
940 << " ----\n\n");
Cong Houab23bfb2015-07-15 22:48:29 +0000941 LastF = &F; // Store the last function we ran on for printing.
942 assert(PostDominatedByUnreachable.empty());
943 assert(PostDominatedByColdCall.empty());
944
Geoff Berryeed65312017-11-01 15:16:50 +0000945 // Record SCC numbers of blocks in the CFG to identify irreducible loops.
946 // FIXME: We could only calculate this if the CFG is known to be irreducible
947 // (perhaps cache this info in LoopInfo if we can easily calculate it there?).
948 int SccNum = 0;
949 SccInfo SccI;
950 for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd();
951 ++It, ++SccNum) {
952 // Ignore single-block SCCs since they either aren't loops or LoopInfo will
953 // catch them.
954 const std::vector<const BasicBlock *> &Scc = *It;
955 if (Scc.size() == 1)
956 continue;
957
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000958 LLVM_DEBUG(dbgs() << "BPI: SCC " << SccNum << ":");
Geoff Berryeed65312017-11-01 15:16:50 +0000959 for (auto *BB : Scc) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000960 LLVM_DEBUG(dbgs() << " " << BB->getName());
Geoff Berryeed65312017-11-01 15:16:50 +0000961 SccI.SccNums[BB] = SccNum;
962 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000963 LLVM_DEBUG(dbgs() << "\n");
Geoff Berryeed65312017-11-01 15:16:50 +0000964 }
965
Cong Houab23bfb2015-07-15 22:48:29 +0000966 // Walk the basic blocks in post-order so that we can build up state about
967 // the successors of a block iteratively.
968 for (auto BB : post_order(&F.getEntryBlock())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000969 LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName()
970 << "\n");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000971 updatePostDominatedByUnreachable(BB);
972 updatePostDominatedByColdCall(BB);
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000973 // If there is no at least two successors, no sense to set probability.
974 if (BB->getTerminator()->getNumSuccessors() < 2)
975 continue;
Cong Houab23bfb2015-07-15 22:48:29 +0000976 if (calcMetadataWeights(BB))
977 continue;
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000978 if (calcInvokeHeuristics(BB))
979 continue;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000980 if (calcUnreachableHeuristics(BB))
981 continue;
Cong Houab23bfb2015-07-15 22:48:29 +0000982 if (calcColdCallHeuristics(BB))
983 continue;
Geoff Berryeed65312017-11-01 15:16:50 +0000984 if (calcLoopBranchHeuristics(BB, LI, SccI))
Cong Houab23bfb2015-07-15 22:48:29 +0000985 continue;
986 if (calcPointerHeuristics(BB))
987 continue;
John Brawnda4a68a2017-06-08 09:44:40 +0000988 if (calcZeroHeuristics(BB, TLI))
Cong Houab23bfb2015-07-15 22:48:29 +0000989 continue;
990 if (calcFloatingPointHeuristics(BB))
991 continue;
Cong Houab23bfb2015-07-15 22:48:29 +0000992 }
993
994 PostDominatedByUnreachable.clear();
995 PostDominatedByColdCall.clear();
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +0000996
997 if (PrintBranchProb &&
998 (PrintBranchProbFuncName.empty() ||
999 F.getName().equals(PrintBranchProbFuncName))) {
1000 print(dbgs());
1001 }
Cong Houab23bfb2015-07-15 22:48:29 +00001002}
1003
1004void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
1005 AnalysisUsage &AU) const {
Mikael Holmen2ca16892018-05-17 09:05:40 +00001006 // We require DT so it's available when LI is available. The LI updating code
1007 // asserts that DT is also present so if we don't make sure that we have DT
1008 // here, that assert will trigger.
1009 AU.addRequired<DominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001010 AU.addRequired<LoopInfoWrapperPass>();
John Brawnda4a68a2017-06-08 09:44:40 +00001011 AU.addRequired<TargetLibraryInfoWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001012 AU.setPreservesAll();
1013}
1014
1015bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
1016 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
John Brawnda4a68a2017-06-08 09:44:40 +00001017 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1018 BPI.calculate(F, LI, &TLI);
Cong Houab23bfb2015-07-15 22:48:29 +00001019 return false;
1020}
1021
1022void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
1023
1024void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
1025 const Module *) const {
1026 BPI.print(OS);
1027}
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001028
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001029AnalysisKey BranchProbabilityAnalysis::Key;
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001030BranchProbabilityInfo
Sean Silva36e0d012016-08-09 00:28:15 +00001031BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001032 BranchProbabilityInfo BPI;
John Brawnda4a68a2017-06-08 09:44:40 +00001033 BPI.calculate(F, AM.getResult<LoopAnalysis>(F), &AM.getResult<TargetLibraryAnalysis>(F));
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001034 return BPI;
1035}
1036
1037PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +00001038BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001039 OS << "Printing analysis results of BPI for function "
1040 << "'" << F.getName() << "':"
1041 << "\n";
1042 AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
1043 return PreservedAnalyses::all();
1044}