blob: 7bd237b9ad53718c26f1e79da382a6e017c50376 [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"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080034#include "llvm/InitializePasses.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000035#include "llvm/Pass.h"
36#include "llvm/Support/BranchProbability.h"
37#include "llvm/Support/Casting.h"
Reid Kleckner4c1a1d32019-11-14 15:15:48 -080038#include "llvm/Support/CommandLine.h"
Andrew Trick3d4e64b2011-06-11 01:05:22 +000039#include "llvm/Support/Debug.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000040#include "llvm/Support/raw_ostream.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000041#include <cassert>
42#include <cstdint>
43#include <iterator>
44#include <utility>
Andrew Trick49371f32011-06-04 01:16:30 +000045
46using namespace llvm;
47
Chandler Carruthf1221bd2014-04-22 02:48:03 +000048#define DEBUG_TYPE "branch-prob"
49
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +000050static cl::opt<bool> PrintBranchProb(
51 "print-bpi", cl::init(false), cl::Hidden,
52 cl::desc("Print the branch probability info."));
53
54cl::opt<std::string> PrintBranchProbFuncName(
55 "print-bpi-func-name", cl::Hidden,
56 cl::desc("The option to specify the name of the function "
57 "whose branch probability info is printed."));
58
Cong Houab23bfb2015-07-15 22:48:29 +000059INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000060 "Branch Probability Analysis", false, true)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000061INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
John Brawnda4a68a2017-06-08 09:44:40 +000062INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Cong Houab23bfb2015-07-15 22:48:29 +000063INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000064 "Branch Probability Analysis", false, true)
65
Reid Kleckner05da2fe2019-11-13 13:15:01 -080066BranchProbabilityInfoWrapperPass::BranchProbabilityInfoWrapperPass()
67 : FunctionPass(ID) {
68 initializeBranchProbabilityInfoWrapperPassPass(
69 *PassRegistry::getPassRegistry());
70}
71
Cong Houab23bfb2015-07-15 22:48:29 +000072char BranchProbabilityInfoWrapperPass::ID = 0;
Andrew Trick49371f32011-06-04 01:16:30 +000073
Chandler Carruth7a0094a2011-10-24 01:40:45 +000074// Weights are for internal use only. They are used by heuristics to help to
75// estimate edges' probability. Example:
76//
77// Using "Loop Branch Heuristics" we predict weights of edges for the
78// block BB2.
79// ...
80// |
81// V
82// BB1<-+
83// | |
84// | | (Weight = 124)
85// V |
86// BB2--+
87// |
88// | (Weight = 4)
89// V
90// BB3
91//
92// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
93// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
94static const uint32_t LBH_TAKEN_WEIGHT = 124;
95static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
John Brawn29bbed32018-02-23 17:17:31 +000096// Unlikely edges within a loop are half as likely as other edges
97static const uint32_t LBH_UNLIKELY_WEIGHT = 62;
Andrew Trick49371f32011-06-04 01:16:30 +000098
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000099/// Unreachable-terminating branch taken probability.
Chandler Carruth7111f452011-10-24 12:01:08 +0000100///
Serguei Katkovba831f72017-05-18 06:11:56 +0000101/// This is the probability for a branch being taken to a block that terminates
Chandler Carruth7111f452011-10-24 12:01:08 +0000102/// (eventually) in unreachable. These are predicted as unlikely as possible.
Serguei Katkovba831f72017-05-18 06:11:56 +0000103/// All reachable probability will equally share the remaining part.
104static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000105
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000106/// Weight for a branch taken going into a cold block.
Diego Novilloc6399532013-05-24 12:26:52 +0000107///
108/// This is the weight for a branch taken toward a block marked
109/// cold. A block is marked cold if it's postdominated by a
110/// block containing a call to a cold function. Cold functions
111/// are those marked with attribute 'cold'.
112static const uint32_t CC_TAKEN_WEIGHT = 4;
113
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000114/// Weight for a branch not-taken into a cold block.
Diego Novilloc6399532013-05-24 12:26:52 +0000115///
116/// This is the weight for a branch not taken toward a block marked
117/// cold.
118static const uint32_t CC_NONTAKEN_WEIGHT = 64;
119
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000120static const uint32_t PH_TAKEN_WEIGHT = 20;
121static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000122
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000123static const uint32_t ZH_TAKEN_WEIGHT = 20;
124static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000125
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000126static const uint32_t FPH_TAKEN_WEIGHT = 20;
127static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000128
Guozhi Weib329e072019-09-10 17:25:11 +0000129/// This is the probability for an ordered floating point comparison.
130static const uint32_t FPH_ORD_WEIGHT = 1024 * 1024 - 1;
131/// This is the probability for an unordered floating point comparison, it means
132/// one or two of the operands are NaN. Usually it is used to test for an
133/// exceptional case, so the result is unlikely.
134static const uint32_t FPH_UNO_WEIGHT = 1;
135
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000136/// Invoke-terminating normal branch taken weight
Bill Wendlinge1c54262012-08-15 12:22:35 +0000137///
138/// This is the weight for branching to the normal destination of an invoke
139/// instruction. We expect this to happen most of the time. Set the weight to an
140/// absurdly high value so that nested loops subsume it.
141static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
142
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000143/// Invoke-terminating normal branch not-taken weight.
Bill Wendlinge1c54262012-08-15 12:22:35 +0000144///
145/// This is the weight for branching to the unwind destination of an invoke
146/// instruction. This is essentially never taken.
147static const uint32_t IH_NONTAKEN_WEIGHT = 1;
148
taewookoh5d21f752019-11-27 11:17:10 -0800149/// Add \p BB to PostDominatedByUnreachable set if applicable.
150void
151BranchProbabilityInfo::updatePostDominatedByUnreachable(const BasicBlock *BB) {
152 const Instruction *TI = BB->getTerminator();
153 if (TI->getNumSuccessors() == 0) {
154 if (isa<UnreachableInst>(TI) ||
155 // If this block is terminated by a call to
156 // @llvm.experimental.deoptimize then treat it like an unreachable since
157 // the @llvm.experimental.deoptimize call is expected to practically
158 // never execute.
159 BB->getTerminatingDeoptimizeCall())
160 PostDominatedByUnreachable.insert(BB);
161 return;
162 }
Chandler Carruth7111f452011-10-24 12:01:08 +0000163
taewookoh5d21f752019-11-27 11:17:10 -0800164 // If the terminator is an InvokeInst, check only the normal destination block
165 // as the unwind edge of InvokeInst is also very unlikely taken.
166 if (auto *II = dyn_cast<InvokeInst>(TI)) {
167 if (PostDominatedByUnreachable.count(II->getNormalDest()))
168 PostDominatedByUnreachable.insert(BB);
169 return;
170 }
171
172 for (auto *I : successors(BB))
173 // If any of successor is not post dominated then BB is also not.
174 if (!PostDominatedByUnreachable.count(I))
175 return;
176
177 PostDominatedByUnreachable.insert(BB);
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000178}
179
taewookoh5d21f752019-11-27 11:17:10 -0800180/// Add \p BB to PostDominatedByColdCall set if applicable.
181void
182BranchProbabilityInfo::updatePostDominatedByColdCall(const BasicBlock *BB) {
183 assert(!PostDominatedByColdCall.count(BB));
184 const Instruction *TI = BB->getTerminator();
185 if (TI->getNumSuccessors() == 0)
186 return;
187
188 // If all of successor are post dominated then BB is also done.
189 if (llvm::all_of(successors(BB), [&](const BasicBlock *SuccBB) {
190 return PostDominatedByColdCall.count(SuccBB);
191 })) {
192 PostDominatedByColdCall.insert(BB);
193 return;
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000194 }
195
taewookoh5d21f752019-11-27 11:17:10 -0800196 // If the terminator is an InvokeInst, check only the normal destination
197 // block as the unwind edge of InvokeInst is also very unlikely taken.
198 if (auto *II = dyn_cast<InvokeInst>(TI))
199 if (PostDominatedByColdCall.count(II->getNormalDest())) {
200 PostDominatedByColdCall.insert(BB);
201 return;
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000202 }
203
taewookoh5d21f752019-11-27 11:17:10 -0800204 // Otherwise, if the block itself contains a cold function, add it to the
205 // set of blocks post-dominated by a cold call.
206 for (auto &I : *BB)
207 if (const CallInst *CI = dyn_cast<CallInst>(&I))
208 if (CI->hasFnAttr(Attribute::Cold)) {
209 PostDominatedByColdCall.insert(BB);
210 return;
211 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000212}
213
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000214/// Calculate edge weights for successors lead to unreachable.
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000215///
216/// Predict that a successor which leads necessarily to an
217/// unreachable-terminated block as extremely unlikely.
218bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000219 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000220 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000221 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000222 assert(!isa<InvokeInst>(TI) &&
223 "Invokes should have already been handled by calcInvokeHeuristics");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000224
Manman Rencf104462012-08-24 18:14:27 +0000225 SmallVector<unsigned, 4> UnreachableEdges;
226 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000227
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000228 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Chandler Carruth7111f452011-10-24 12:01:08 +0000229 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000230 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000231 else
Manman Rencf104462012-08-24 18:14:27 +0000232 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000233
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000234 // Skip probabilities if all were reachable.
235 if (UnreachableEdges.empty())
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000236 return false;
Jun Bum Lima23e5f72015-12-21 22:00:51 +0000237
Cong Houe93b8e12015-12-22 18:56:14 +0000238 if (ReachableEdges.empty()) {
239 BranchProbability Prob(1, UnreachableEdges.size());
240 for (unsigned SuccIdx : UnreachableEdges)
241 setEdgeProbability(BB, SuccIdx, Prob);
Chandler Carruth7111f452011-10-24 12:01:08 +0000242 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000243 }
244
Serguei Katkovba831f72017-05-18 06:11:56 +0000245 auto UnreachableProb = UR_TAKEN_PROB;
246 auto ReachableProb =
247 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
248 ReachableEdges.size();
Cong Houe93b8e12015-12-22 18:56:14 +0000249
250 for (unsigned SuccIdx : UnreachableEdges)
251 setEdgeProbability(BB, SuccIdx, UnreachableProb);
252 for (unsigned SuccIdx : ReachableEdges)
253 setEdgeProbability(BB, SuccIdx, ReachableProb);
Chandler Carruth7111f452011-10-24 12:01:08 +0000254
255 return true;
256}
257
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000258// Propagate existing explicit probabilities from either profile data or
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000259// 'expect' intrinsic processing. Examine metadata against unreachable
260// heuristic. The probability of the edge coming to unreachable block is
261// set to min of metadata and unreachable heuristic.
Mehdi Aminia7978772016-04-07 21:59:28 +0000262bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000263 const Instruction *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000264 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Rong Xu15848e52017-08-23 21:36:02 +0000265 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI)))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000266 return false;
267
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000268 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000269 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000270 return false;
271
Diego Novillode5b8012015-05-07 17:22:06 +0000272 // Check that the number of successors is manageable.
273 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
274
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000275 // Ensure there are weights for all of the successors. Note that the first
276 // operand to the metadata node is a name, not a weight.
277 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000278 return false;
279
Diego Novillode5b8012015-05-07 17:22:06 +0000280 // Build up the final weights that will be used in a temporary buffer.
281 // Compute the sum of all weights to later decide whether they need to
282 // be scaled to fit in 32 bits.
283 uint64_t WeightSum = 0;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000284 SmallVector<uint32_t, 2> Weights;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000285 SmallVector<unsigned, 2> UnreachableIdxs;
286 SmallVector<unsigned, 2> ReachableIdxs;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000287 Weights.reserve(TI->getNumSuccessors());
288 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000289 ConstantInt *Weight =
290 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i));
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000291 if (!Weight)
292 return false;
Diego Novillode5b8012015-05-07 17:22:06 +0000293 assert(Weight->getValue().getActiveBits() <= 32 &&
294 "Too many bits for uint32_t");
295 Weights.push_back(Weight->getZExtValue());
296 WeightSum += Weights.back();
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000297 if (PostDominatedByUnreachable.count(TI->getSuccessor(i - 1)))
298 UnreachableIdxs.push_back(i - 1);
299 else
300 ReachableIdxs.push_back(i - 1);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000301 }
302 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
Diego Novillode5b8012015-05-07 17:22:06 +0000303
304 // If the sum of weights does not fit in 32 bits, scale every weight down
305 // accordingly.
306 uint64_t ScalingFactor =
307 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
308
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000309 if (ScalingFactor > 1) {
310 WeightSum = 0;
311 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
312 Weights[i] /= ScalingFactor;
313 WeightSum += Weights[i];
314 }
Diego Novillode5b8012015-05-07 17:22:06 +0000315 }
Serguei Katkov63c9c812017-05-12 07:50:06 +0000316 assert(WeightSum <= UINT32_MAX &&
317 "Expected weights to scale down to 32 bits");
Cong Hou6a2c71a2015-12-22 23:45:55 +0000318
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000319 if (WeightSum == 0 || ReachableIdxs.size() == 0) {
Cong Hou6a2c71a2015-12-22 23:45:55 +0000320 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000321 Weights[i] = 1;
322 WeightSum = TI->getNumSuccessors();
Cong Hou6a2c71a2015-12-22 23:45:55 +0000323 }
Cong Houe93b8e12015-12-22 18:56:14 +0000324
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000325 // Set the probability.
326 SmallVector<BranchProbability, 2> BP;
327 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
328 BP.push_back({ Weights[i], static_cast<uint32_t>(WeightSum) });
329
330 // Examine the metadata against unreachable heuristic.
331 // If the unreachable heuristic is more strong then we use it for this edge.
332 if (UnreachableIdxs.size() > 0 && ReachableIdxs.size() > 0) {
333 auto ToDistribute = BranchProbability::getZero();
Serguei Katkovba831f72017-05-18 06:11:56 +0000334 auto UnreachableProb = UR_TAKEN_PROB;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000335 for (auto i : UnreachableIdxs)
336 if (UnreachableProb < BP[i]) {
337 ToDistribute += BP[i] - UnreachableProb;
338 BP[i] = UnreachableProb;
339 }
340
341 // If we modified the probability of some edges then we must distribute
342 // the difference between reachable blocks.
343 if (ToDistribute > BranchProbability::getZero()) {
344 BranchProbability PerEdge = ToDistribute / ReachableIdxs.size();
Serguei Katkov63c9c812017-05-12 07:50:06 +0000345 for (auto i : ReachableIdxs)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000346 BP[i] += PerEdge;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000347 }
348 }
349
350 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
351 setEdgeProbability(BB, i, BP[i]);
352
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000353 return true;
354}
355
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000356/// Calculate edge weights for edges leading to cold blocks.
Diego Novilloc6399532013-05-24 12:26:52 +0000357///
358/// A cold block is one post-dominated by a block with a call to a
359/// cold function. Those edges are unlikely to be taken, so we give
360/// them relatively low weight.
361///
362/// Return true if we could compute the weights for cold edges.
363/// Return false, otherwise.
Mehdi Aminia7978772016-04-07 21:59:28 +0000364bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000365 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000366 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000367 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000368 assert(!isa<InvokeInst>(TI) &&
369 "Invokes should have already been handled by calcInvokeHeuristics");
Diego Novilloc6399532013-05-24 12:26:52 +0000370
371 // Determine which successors are post-dominated by a cold block.
372 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000373 SmallVector<unsigned, 4> NormalEdges;
Mehdi Aminia7978772016-04-07 21:59:28 +0000374 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Diego Novilloc6399532013-05-24 12:26:52 +0000375 if (PostDominatedByColdCall.count(*I))
376 ColdEdges.push_back(I.getSuccessorIndex());
377 else
378 NormalEdges.push_back(I.getSuccessorIndex());
379
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000380 // Skip probabilities if no cold edges.
381 if (ColdEdges.empty())
Diego Novilloc6399532013-05-24 12:26:52 +0000382 return false;
383
Cong Houe93b8e12015-12-22 18:56:14 +0000384 if (NormalEdges.empty()) {
385 BranchProbability Prob(1, ColdEdges.size());
386 for (unsigned SuccIdx : ColdEdges)
387 setEdgeProbability(BB, SuccIdx, Prob);
Diego Novilloc6399532013-05-24 12:26:52 +0000388 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000389 }
390
Vedant Kumara4bd1462016-12-17 01:02:08 +0000391 auto ColdProb = BranchProbability::getBranchProbability(
392 CC_TAKEN_WEIGHT,
393 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
394 auto NormalProb = BranchProbability::getBranchProbability(
395 CC_NONTAKEN_WEIGHT,
396 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
Cong Houe93b8e12015-12-22 18:56:14 +0000397
398 for (unsigned SuccIdx : ColdEdges)
399 setEdgeProbability(BB, SuccIdx, ColdProb);
400 for (unsigned SuccIdx : NormalEdges)
401 setEdgeProbability(BB, SuccIdx, NormalProb);
Diego Novilloc6399532013-05-24 12:26:52 +0000402
403 return true;
404}
405
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000406// Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
Andrew Trick49371f32011-06-04 01:16:30 +0000407// between two pointer or pointer and NULL will fail.
Mehdi Aminia7978772016-04-07 21:59:28 +0000408bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
409 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Andrew Trick49371f32011-06-04 01:16:30 +0000410 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000411 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000412
413 Value *Cond = BI->getCondition();
414 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000415 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000416 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000417
418 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000419
420 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000421 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000422
Nick Lewycky75b20532011-06-04 02:07:10 +0000423 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000424
Andrew Trick49371f32011-06-04 01:16:30 +0000425 // p != 0 -> isProb = true
426 // p == 0 -> isProb = false
427 // p != q -> isProb = true
428 // p == q -> isProb = false;
Manman Rencf104462012-08-24 18:14:27 +0000429 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000430 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000431 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000432 std::swap(TakenIdx, NonTakenIdx);
Andrew Trick49371f32011-06-04 01:16:30 +0000433
Cong Houe93b8e12015-12-22 18:56:14 +0000434 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
435 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
436 setEdgeProbability(BB, TakenIdx, TakenProb);
437 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000438 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000439}
440
Geoff Berryeed65312017-11-01 15:16:50 +0000441static int getSCCNum(const BasicBlock *BB,
442 const BranchProbabilityInfo::SccInfo &SccI) {
443 auto SccIt = SccI.SccNums.find(BB);
444 if (SccIt == SccI.SccNums.end())
445 return -1;
446 return SccIt->second;
447}
448
449// Consider any block that is an entry point to the SCC as a header.
450static bool isSCCHeader(const BasicBlock *BB, int SccNum,
451 BranchProbabilityInfo::SccInfo &SccI) {
452 assert(getSCCNum(BB, SccI) == SccNum);
453
454 // Lazily compute the set of headers for a given SCC and cache the results
455 // in the SccHeaderMap.
456 if (SccI.SccHeaders.size() <= static_cast<unsigned>(SccNum))
457 SccI.SccHeaders.resize(SccNum + 1);
458 auto &HeaderMap = SccI.SccHeaders[SccNum];
459 bool Inserted;
460 BranchProbabilityInfo::SccHeaderMap::iterator HeaderMapIt;
461 std::tie(HeaderMapIt, Inserted) = HeaderMap.insert(std::make_pair(BB, false));
462 if (Inserted) {
463 bool IsHeader = llvm::any_of(make_range(pred_begin(BB), pred_end(BB)),
464 [&](const BasicBlock *Pred) {
465 return getSCCNum(Pred, SccI) != SccNum;
466 });
467 HeaderMapIt->second = IsHeader;
468 return IsHeader;
469 } else
470 return HeaderMapIt->second;
471}
472
John Brawn29bbed32018-02-23 17:17:31 +0000473// Compute the unlikely successors to the block BB in the loop L, specifically
474// those that are unlikely because this is a loop, and add them to the
475// UnlikelyBlocks set.
476static void
477computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
478 SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
479 // Sometimes in a loop we have a branch whose condition is made false by
480 // taking it. This is typically something like
481 // int n = 0;
482 // while (...) {
483 // if (++n >= MAX) {
484 // n = 0;
485 // }
486 // }
487 // In this sort of situation taking the branch means that at the very least it
488 // won't be taken again in the next iteration of the loop, so we should
489 // consider it less likely than a typical branch.
490 //
491 // We detect this by looking back through the graph of PHI nodes that sets the
492 // value that the condition depends on, and seeing if we can reach a successor
493 // block which can be determined to make the condition false.
494 //
495 // FIXME: We currently consider unlikely blocks to be half as likely as other
496 // blocks, but if we consider the example above the likelyhood is actually
497 // 1/MAX. We could therefore be more precise in how unlikely we consider
498 // blocks to be, but it would require more careful examination of the form
499 // of the comparison expression.
500 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
501 if (!BI || !BI->isConditional())
502 return;
503
504 // Check if the branch is based on an instruction compared with a constant
505 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
506 if (!CI || !isa<Instruction>(CI->getOperand(0)) ||
507 !isa<Constant>(CI->getOperand(1)))
508 return;
509
510 // Either the instruction must be a PHI, or a chain of operations involving
511 // constants that ends in a PHI which we can then collapse into a single value
512 // if the PHI value is known.
513 Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0));
514 PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
515 Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1));
516 // Collect the instructions until we hit a PHI
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000517 SmallVector<BinaryOperator *, 1> InstChain;
John Brawn29bbed32018-02-23 17:17:31 +0000518 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
519 isa<Constant>(CmpLHS->getOperand(1))) {
520 // Stop if the chain extends outside of the loop
521 if (!L->contains(CmpLHS))
522 return;
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000523 InstChain.push_back(cast<BinaryOperator>(CmpLHS));
John Brawn29bbed32018-02-23 17:17:31 +0000524 CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
525 if (CmpLHS)
526 CmpPHI = dyn_cast<PHINode>(CmpLHS);
527 }
528 if (!CmpPHI || !L->contains(CmpPHI))
529 return;
530
531 // Trace the phi node to find all values that come from successors of BB
532 SmallPtrSet<PHINode*, 8> VisitedInsts;
533 SmallVector<PHINode*, 8> WorkList;
534 WorkList.push_back(CmpPHI);
535 VisitedInsts.insert(CmpPHI);
536 while (!WorkList.empty()) {
537 PHINode *P = WorkList.back();
538 WorkList.pop_back();
539 for (BasicBlock *B : P->blocks()) {
540 // Skip blocks that aren't part of the loop
541 if (!L->contains(B))
542 continue;
543 Value *V = P->getIncomingValueForBlock(B);
544 // If the source is a PHI add it to the work list if we haven't
545 // already visited it.
546 if (PHINode *PN = dyn_cast<PHINode>(V)) {
547 if (VisitedInsts.insert(PN).second)
548 WorkList.push_back(PN);
549 continue;
550 }
551 // If this incoming value is a constant and B is a successor of BB, then
552 // we can constant-evaluate the compare to see if it makes the branch be
553 // taken or not.
554 Constant *CmpLHSConst = dyn_cast<Constant>(V);
555 if (!CmpLHSConst ||
556 std::find(succ_begin(BB), succ_end(BB), B) == succ_end(BB))
557 continue;
558 // First collapse InstChain
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000559 for (Instruction *I : llvm::reverse(InstChain)) {
John Brawn29bbed32018-02-23 17:17:31 +0000560 CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst,
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000561 cast<Constant>(I->getOperand(1)), true);
John Brawn29bbed32018-02-23 17:17:31 +0000562 if (!CmpLHSConst)
563 break;
564 }
565 if (!CmpLHSConst)
566 continue;
567 // Now constant-evaluate the compare
568 Constant *Result = ConstantExpr::getCompare(CI->getPredicate(),
569 CmpLHSConst, CmpConst, true);
570 // If the result means we don't branch to the block then that block is
571 // unlikely.
572 if (Result &&
573 ((Result->isZeroValue() && B == BI->getSuccessor(0)) ||
574 (Result->isOneValue() && B == BI->getSuccessor(1))))
575 UnlikelyBlocks.insert(B);
576 }
577 }
578}
579
Andrew Trick49371f32011-06-04 01:16:30 +0000580// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
581// as taken, exiting edges as not-taken.
Mehdi Aminia7978772016-04-07 21:59:28 +0000582bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
Geoff Berryeed65312017-11-01 15:16:50 +0000583 const LoopInfo &LI,
584 SccInfo &SccI) {
585 int SccNum;
Cong Houab23bfb2015-07-15 22:48:29 +0000586 Loop *L = LI.getLoopFor(BB);
Geoff Berryeed65312017-11-01 15:16:50 +0000587 if (!L) {
588 SccNum = getSCCNum(BB, SccI);
589 if (SccNum < 0)
590 return false;
591 }
Andrew Trick49371f32011-06-04 01:16:30 +0000592
John Brawn29bbed32018-02-23 17:17:31 +0000593 SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks;
594 if (L)
595 computeUnlikelySuccessors(BB, L, UnlikelyBlocks);
596
Manman Rencf104462012-08-24 18:14:27 +0000597 SmallVector<unsigned, 8> BackEdges;
598 SmallVector<unsigned, 8> ExitingEdges;
599 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
John Brawn29bbed32018-02-23 17:17:31 +0000600 SmallVector<unsigned, 8> UnlikelyEdges;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000601
Mehdi Aminia7978772016-04-07 21:59:28 +0000602 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Geoff Berryeed65312017-11-01 15:16:50 +0000603 // Use LoopInfo if we have it, otherwise fall-back to SCC info to catch
604 // irreducible loops.
605 if (L) {
John Brawn29bbed32018-02-23 17:17:31 +0000606 if (UnlikelyBlocks.count(*I) != 0)
607 UnlikelyEdges.push_back(I.getSuccessorIndex());
608 else if (!L->contains(*I))
Geoff Berryeed65312017-11-01 15:16:50 +0000609 ExitingEdges.push_back(I.getSuccessorIndex());
610 else if (L->getHeader() == *I)
611 BackEdges.push_back(I.getSuccessorIndex());
612 else
613 InEdges.push_back(I.getSuccessorIndex());
614 } else {
615 if (getSCCNum(*I, SccI) != SccNum)
616 ExitingEdges.push_back(I.getSuccessorIndex());
617 else if (isSCCHeader(*I, SccNum, SccI))
618 BackEdges.push_back(I.getSuccessorIndex());
619 else
620 InEdges.push_back(I.getSuccessorIndex());
621 }
Andrew Trick49371f32011-06-04 01:16:30 +0000622 }
623
John Brawn29bbed32018-02-23 17:17:31 +0000624 if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty())
Akira Hatanaka5638b892014-04-14 16:56:19 +0000625 return false;
626
Cong Houe93b8e12015-12-22 18:56:14 +0000627 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
628 // normalize them so that they sum up to one.
Cong Houe93b8e12015-12-22 18:56:14 +0000629 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
630 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
John Brawn29bbed32018-02-23 17:17:31 +0000631 (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) +
Cong Houe93b8e12015-12-22 18:56:14 +0000632 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
Andrew Trick49371f32011-06-04 01:16:30 +0000633
Cong Houe93b8e12015-12-22 18:56:14 +0000634 if (uint32_t numBackEdges = BackEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000635 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
636 auto Prob = TakenProb / numBackEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000637 for (unsigned SuccIdx : BackEdges)
638 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000639 }
640
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000641 if (uint32_t numInEdges = InEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000642 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
643 auto Prob = TakenProb / numInEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000644 for (unsigned SuccIdx : InEdges)
645 setEdgeProbability(BB, SuccIdx, Prob);
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000646 }
647
Chandler Carruth32f46e72011-10-25 09:47:41 +0000648 if (uint32_t numExitingEdges = ExitingEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000649 BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT,
650 Denom);
651 auto Prob = NotTakenProb / numExitingEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000652 for (unsigned SuccIdx : ExitingEdges)
653 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000654 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000655
John Brawn29bbed32018-02-23 17:17:31 +0000656 if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) {
657 BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT,
658 Denom);
659 auto Prob = UnlikelyProb / numUnlikelyEdges;
660 for (unsigned SuccIdx : UnlikelyEdges)
661 setEdgeProbability(BB, SuccIdx, Prob);
662 }
663
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000664 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000665}
666
John Brawnda4a68a2017-06-08 09:44:40 +0000667bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
668 const TargetLibraryInfo *TLI) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000669 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000670 if (!BI || !BI->isConditional())
671 return false;
672
673 Value *Cond = BI->getCondition();
674 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
675 if (!CI)
676 return false;
677
Sam Parker0b53e842019-02-15 11:50:21 +0000678 auto GetConstantInt = [](Value *V) {
679 if (auto *I = dyn_cast<BitCastInst>(V))
680 return dyn_cast<ConstantInt>(I->getOperand(0));
681 return dyn_cast<ConstantInt>(V);
682 };
683
Jakub Staszak17af66a2011-07-31 03:27:24 +0000684 Value *RHS = CI->getOperand(1);
Sam Parker0b53e842019-02-15 11:50:21 +0000685 ConstantInt *CV = GetConstantInt(RHS);
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000686 if (!CV)
Jakub Staszak17af66a2011-07-31 03:27:24 +0000687 return false;
688
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000689 // If the LHS is the result of AND'ing a value with a single bit bitmask,
690 // we don't have information about probabilities.
691 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
692 if (LHS->getOpcode() == Instruction::And)
693 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
Craig Topper4e22ee62017-08-04 16:59:29 +0000694 if (AndRHS->getValue().isPowerOf2())
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000695 return false;
696
John Brawnda4a68a2017-06-08 09:44:40 +0000697 // Check if the LHS is the return value of a library function
698 LibFunc Func = NumLibFuncs;
699 if (TLI)
700 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
701 if (Function *CalledFn = Call->getCalledFunction())
702 TLI->getLibFunc(*CalledFn, Func);
703
Jakub Staszak17af66a2011-07-31 03:27:24 +0000704 bool isProb;
John Brawnda4a68a2017-06-08 09:44:40 +0000705 if (Func == LibFunc_strcasecmp ||
706 Func == LibFunc_strcmp ||
707 Func == LibFunc_strncasecmp ||
708 Func == LibFunc_strncmp ||
709 Func == LibFunc_memcmp) {
710 // strcmp and similar functions return zero, negative, or positive, if the
711 // first string is equal, less, or greater than the second. We consider it
712 // likely that the strings are not equal, so a comparison with zero is
713 // probably false, but also a comparison with any other number is also
714 // probably false given that what exactly is returned for nonzero values is
715 // not specified. Any kind of comparison other than equality we know
716 // nothing about.
717 switch (CI->getPredicate()) {
718 case CmpInst::ICMP_EQ:
719 isProb = false;
720 break;
721 case CmpInst::ICMP_NE:
722 isProb = true;
723 break;
724 default:
725 return false;
726 }
727 } else if (CV->isZero()) {
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000728 switch (CI->getPredicate()) {
729 case CmpInst::ICMP_EQ:
730 // X == 0 -> Unlikely
731 isProb = false;
732 break;
733 case CmpInst::ICMP_NE:
734 // X != 0 -> Likely
735 isProb = true;
736 break;
737 case CmpInst::ICMP_SLT:
738 // X < 0 -> Unlikely
739 isProb = false;
740 break;
741 case CmpInst::ICMP_SGT:
742 // X > 0 -> Likely
743 isProb = true;
744 break;
745 default:
746 return false;
747 }
748 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
749 // InstCombine canonicalizes X <= 0 into X < 1.
750 // X <= 0 -> Unlikely
Jakub Staszak17af66a2011-07-31 03:27:24 +0000751 isProb = false;
Craig Topper79ab6432017-07-06 18:39:47 +0000752 } else if (CV->isMinusOne()) {
Hal Finkel4d949302013-11-01 10:58:22 +0000753 switch (CI->getPredicate()) {
754 case CmpInst::ICMP_EQ:
755 // X == -1 -> Unlikely
756 isProb = false;
757 break;
758 case CmpInst::ICMP_NE:
759 // X != -1 -> Likely
760 isProb = true;
761 break;
762 case CmpInst::ICMP_SGT:
763 // InstCombine canonicalizes X >= 0 into X > -1.
764 // X >= 0 -> Likely
765 isProb = true;
766 break;
767 default:
768 return false;
769 }
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000770 } else {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000771 return false;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000772 }
Jakub Staszak17af66a2011-07-31 03:27:24 +0000773
Manman Rencf104462012-08-24 18:14:27 +0000774 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszak17af66a2011-07-31 03:27:24 +0000775
776 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000777 std::swap(TakenIdx, NonTakenIdx);
Jakub Staszak17af66a2011-07-31 03:27:24 +0000778
Cong Houe93b8e12015-12-22 18:56:14 +0000779 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
780 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
781 setEdgeProbability(BB, TakenIdx, TakenProb);
782 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000783 return true;
784}
785
Mehdi Aminia7978772016-04-07 21:59:28 +0000786bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
787 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000788 if (!BI || !BI->isConditional())
789 return false;
790
791 Value *Cond = BI->getCondition();
792 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000793 if (!FCmp)
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000794 return false;
795
Guozhi Weib329e072019-09-10 17:25:11 +0000796 uint32_t TakenWeight = FPH_TAKEN_WEIGHT;
797 uint32_t NontakenWeight = FPH_NONTAKEN_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000798 bool isProb;
799 if (FCmp->isEquality()) {
800 // f1 == f2 -> Unlikely
801 // f1 != f2 -> Likely
802 isProb = !FCmp->isTrueWhenEqual();
803 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
804 // !isnan -> Likely
805 isProb = true;
Guozhi Weib329e072019-09-10 17:25:11 +0000806 TakenWeight = FPH_ORD_WEIGHT;
807 NontakenWeight = FPH_UNO_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000808 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
809 // isnan -> Unlikely
810 isProb = false;
Guozhi Weib329e072019-09-10 17:25:11 +0000811 TakenWeight = FPH_ORD_WEIGHT;
812 NontakenWeight = FPH_UNO_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000813 } else {
814 return false;
815 }
816
Manman Rencf104462012-08-24 18:14:27 +0000817 unsigned TakenIdx = 0, NonTakenIdx = 1;
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000818
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000819 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000820 std::swap(TakenIdx, NonTakenIdx);
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000821
Guozhi Weib329e072019-09-10 17:25:11 +0000822 BranchProbability TakenProb(TakenWeight, TakenWeight + NontakenWeight);
Cong Houe93b8e12015-12-22 18:56:14 +0000823 setEdgeProbability(BB, TakenIdx, TakenProb);
824 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000825 return true;
826}
Jakub Staszak17af66a2011-07-31 03:27:24 +0000827
Mehdi Aminia7978772016-04-07 21:59:28 +0000828bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
829 const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000830 if (!II)
831 return false;
832
Cong Houe93b8e12015-12-22 18:56:14 +0000833 BranchProbability TakenProb(IH_TAKEN_WEIGHT,
834 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
835 setEdgeProbability(BB, 0 /*Index for Normal*/, TakenProb);
836 setEdgeProbability(BB, 1 /*Index for Unwind*/, TakenProb.getCompl());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000837 return true;
838}
839
Pete Cooperb9d2e342015-05-28 19:43:06 +0000840void BranchProbabilityInfo::releaseMemory() {
Cong Houe93b8e12015-12-22 18:56:14 +0000841 Probs.clear();
Pete Cooperb9d2e342015-05-28 19:43:06 +0000842}
843
Cong Houab23bfb2015-07-15 22:48:29 +0000844void BranchProbabilityInfo::print(raw_ostream &OS) const {
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000845 OS << "---- Branch Probabilities ----\n";
846 // We print the probabilities from the last function the analysis ran over,
847 // or the function it is currently running over.
848 assert(LastF && "Cannot print prior to running over a function");
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000849 for (const auto &BI : *LastF) {
850 for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
851 ++SI) {
852 printEdgeProbability(OS << " ", &BI, *SI);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000853 }
854 }
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000855}
856
Jakub Staszakefd94c82011-07-29 19:30:00 +0000857bool BranchProbabilityInfo::
858isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000859 // Hot probability is at least 4/5 = 80%
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000860 // FIXME: Compare against a static "hot" BranchProbability.
861 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick49371f32011-06-04 01:16:30 +0000862}
863
Mehdi Aminia7978772016-04-07 21:59:28 +0000864const BasicBlock *
865BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
Cong Houe93b8e12015-12-22 18:56:14 +0000866 auto MaxProb = BranchProbability::getZero();
Mehdi Aminia7978772016-04-07 21:59:28 +0000867 const BasicBlock *MaxSucc = nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000868
Mehdi Aminia7978772016-04-07 21:59:28 +0000869 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
870 const BasicBlock *Succ = *I;
Cong Houe93b8e12015-12-22 18:56:14 +0000871 auto Prob = getEdgeProbability(BB, Succ);
872 if (Prob > MaxProb) {
873 MaxProb = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000874 MaxSucc = Succ;
875 }
876 }
877
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000878 // Hot probability is at least 4/5 = 80%
Cong Houe93b8e12015-12-22 18:56:14 +0000879 if (MaxProb > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +0000880 return MaxSucc;
881
Craig Topper9f008862014-04-15 04:59:12 +0000882 return nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000883}
884
Cong Houe93b8e12015-12-22 18:56:14 +0000885/// Get the raw edge probability for the edge. If can't find it, return a
886/// default probability 1/N where N is the number of successors. Here an edge is
887/// specified using PredBlock and an
888/// index to the successors.
889BranchProbability
890BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
891 unsigned IndexInSuccessors) const {
892 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick49371f32011-06-04 01:16:30 +0000893
Cong Houe93b8e12015-12-22 18:56:14 +0000894 if (I != Probs.end())
Andrew Trick49371f32011-06-04 01:16:30 +0000895 return I->second;
896
Vedant Kumare0b5f862018-05-10 23:01:54 +0000897 return {1, static_cast<uint32_t>(succ_size(Src))};
Andrew Trick49371f32011-06-04 01:16:30 +0000898}
899
Cong Houd97c1002015-12-01 05:29:22 +0000900BranchProbability
901BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
902 succ_const_iterator Dst) const {
903 return getEdgeProbability(Src, Dst.getSuccessorIndex());
904}
905
Cong Houe93b8e12015-12-22 18:56:14 +0000906/// Get the raw edge probability calculated for the block pair. This returns the
907/// sum of all raw edge probabilities from Src to Dst.
908BranchProbability
909BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
910 const BasicBlock *Dst) const {
911 auto Prob = BranchProbability::getZero();
912 bool FoundProb = false;
913 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
914 if (*I == Dst) {
915 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
916 if (MapI != Probs.end()) {
917 FoundProb = true;
918 Prob += MapI->second;
919 }
920 }
921 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
922 return FoundProb ? Prob : BranchProbability(1, succ_num);
923}
924
925/// Set the edge probability for a given edge specified by PredBlock and an
926/// index to the successors.
927void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
928 unsigned IndexInSuccessors,
929 BranchProbability Prob) {
930 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000931 Handles.insert(BasicBlockCallbackVH(Src, this));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000932 LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
933 << IndexInSuccessors << " successor probability to " << Prob
934 << "\n");
Cong Houe93b8e12015-12-22 18:56:14 +0000935}
936
Andrew Trick49371f32011-06-04 01:16:30 +0000937raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000938BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
939 const BasicBlock *Src,
940 const BasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +0000941 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000942 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000943 << " probability is " << Prob
944 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +0000945
946 return OS;
947}
Cong Houab23bfb2015-07-15 22:48:29 +0000948
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000949void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
950 for (auto I = Probs.begin(), E = Probs.end(); I != E; ++I) {
951 auto Key = I->first;
952 if (Key.first == BB)
953 Probs.erase(Key);
954 }
955}
956
John Brawnda4a68a2017-06-08 09:44:40 +0000957void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
958 const TargetLibraryInfo *TLI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000959 LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
960 << " ----\n\n");
Cong Houab23bfb2015-07-15 22:48:29 +0000961 LastF = &F; // Store the last function we ran on for printing.
962 assert(PostDominatedByUnreachable.empty());
963 assert(PostDominatedByColdCall.empty());
964
Geoff Berryeed65312017-11-01 15:16:50 +0000965 // Record SCC numbers of blocks in the CFG to identify irreducible loops.
966 // FIXME: We could only calculate this if the CFG is known to be irreducible
967 // (perhaps cache this info in LoopInfo if we can easily calculate it there?).
968 int SccNum = 0;
969 SccInfo SccI;
970 for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd();
971 ++It, ++SccNum) {
972 // Ignore single-block SCCs since they either aren't loops or LoopInfo will
973 // catch them.
974 const std::vector<const BasicBlock *> &Scc = *It;
975 if (Scc.size() == 1)
976 continue;
977
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000978 LLVM_DEBUG(dbgs() << "BPI: SCC " << SccNum << ":");
Geoff Berryeed65312017-11-01 15:16:50 +0000979 for (auto *BB : Scc) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000980 LLVM_DEBUG(dbgs() << " " << BB->getName());
Geoff Berryeed65312017-11-01 15:16:50 +0000981 SccI.SccNums[BB] = SccNum;
982 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000983 LLVM_DEBUG(dbgs() << "\n");
Geoff Berryeed65312017-11-01 15:16:50 +0000984 }
985
Cong Houab23bfb2015-07-15 22:48:29 +0000986 // Walk the basic blocks in post-order so that we can build up state about
987 // the successors of a block iteratively.
988 for (auto BB : post_order(&F.getEntryBlock())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000989 LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName()
990 << "\n");
taewookoh5d21f752019-11-27 11:17:10 -0800991 updatePostDominatedByUnreachable(BB);
992 updatePostDominatedByColdCall(BB);
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000993 // If there is no at least two successors, no sense to set probability.
994 if (BB->getTerminator()->getNumSuccessors() < 2)
995 continue;
Cong Houab23bfb2015-07-15 22:48:29 +0000996 if (calcMetadataWeights(BB))
997 continue;
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000998 if (calcInvokeHeuristics(BB))
999 continue;
Serguei Katkov2616bbb2017-04-17 04:33:04 +00001000 if (calcUnreachableHeuristics(BB))
1001 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001002 if (calcColdCallHeuristics(BB))
1003 continue;
Geoff Berryeed65312017-11-01 15:16:50 +00001004 if (calcLoopBranchHeuristics(BB, LI, SccI))
Cong Houab23bfb2015-07-15 22:48:29 +00001005 continue;
1006 if (calcPointerHeuristics(BB))
1007 continue;
John Brawnda4a68a2017-06-08 09:44:40 +00001008 if (calcZeroHeuristics(BB, TLI))
Cong Houab23bfb2015-07-15 22:48:29 +00001009 continue;
1010 if (calcFloatingPointHeuristics(BB))
1011 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001012 }
1013
1014 PostDominatedByUnreachable.clear();
1015 PostDominatedByColdCall.clear();
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +00001016
1017 if (PrintBranchProb &&
1018 (PrintBranchProbFuncName.empty() ||
1019 F.getName().equals(PrintBranchProbFuncName))) {
1020 print(dbgs());
1021 }
Cong Houab23bfb2015-07-15 22:48:29 +00001022}
1023
1024void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
1025 AnalysisUsage &AU) const {
Mikael Holmen2ca16892018-05-17 09:05:40 +00001026 // We require DT so it's available when LI is available. The LI updating code
1027 // asserts that DT is also present so if we don't make sure that we have DT
1028 // here, that assert will trigger.
1029 AU.addRequired<DominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001030 AU.addRequired<LoopInfoWrapperPass>();
John Brawnda4a68a2017-06-08 09:44:40 +00001031 AU.addRequired<TargetLibraryInfoWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001032 AU.setPreservesAll();
1033}
1034
1035bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
1036 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnson9c27b592019-09-07 03:09:36 +00001037 const TargetLibraryInfo &TLI =
1038 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
John Brawnda4a68a2017-06-08 09:44:40 +00001039 BPI.calculate(F, LI, &TLI);
Cong Houab23bfb2015-07-15 22:48:29 +00001040 return false;
1041}
1042
1043void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
1044
1045void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
1046 const Module *) const {
1047 BPI.print(OS);
1048}
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001049
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001050AnalysisKey BranchProbabilityAnalysis::Key;
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001051BranchProbabilityInfo
Sean Silva36e0d012016-08-09 00:28:15 +00001052BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001053 BranchProbabilityInfo BPI;
John Brawnda4a68a2017-06-08 09:44:40 +00001054 BPI.calculate(F, AM.getResult<LoopAnalysis>(F), &AM.getResult<TargetLibraryAnalysis>(F));
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001055 return BPI;
1056}
1057
1058PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +00001059BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001060 OS << "Printing analysis results of BPI for function "
1061 << "'" << F.getName() << "':"
1062 << "\n";
1063 AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
1064 return PreservedAnalyses::all();
1065}