blob: c69993877a10848786058c69384b5180eb4b527d [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"
Taewook Oh2da205d2019-12-02 10:15:22 -080019#include "llvm/Analysis/PostDominators.h"
John Brawnda4a68a2017-06-08 09:44:40 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000021#include "llvm/IR/Attributes.h"
22#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000023#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
Mikael Holmen2ca16892018-05-17 09:05:40 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Function.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000027#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Metadata.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000032#include "llvm/IR/PassManager.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/Value.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080035#include "llvm/InitializePasses.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000036#include "llvm/Pass.h"
37#include "llvm/Support/BranchProbability.h"
38#include "llvm/Support/Casting.h"
Reid Kleckner4c1a1d32019-11-14 15:15:48 -080039#include "llvm/Support/CommandLine.h"
Andrew Trick3d4e64b2011-06-11 01:05:22 +000040#include "llvm/Support/Debug.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000041#include "llvm/Support/raw_ostream.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000042#include <cassert>
43#include <cstdint>
44#include <iterator>
45#include <utility>
Andrew Trick49371f32011-06-04 01:16:30 +000046
47using namespace llvm;
48
Chandler Carruthf1221bd2014-04-22 02:48:03 +000049#define DEBUG_TYPE "branch-prob"
50
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +000051static cl::opt<bool> PrintBranchProb(
52 "print-bpi", cl::init(false), cl::Hidden,
53 cl::desc("Print the branch probability info."));
54
55cl::opt<std::string> PrintBranchProbFuncName(
56 "print-bpi-func-name", cl::Hidden,
57 cl::desc("The option to specify the name of the function "
58 "whose branch probability info is printed."));
59
Cong Houab23bfb2015-07-15 22:48:29 +000060INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000061 "Branch Probability Analysis", false, true)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000062INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
John Brawnda4a68a2017-06-08 09:44:40 +000063INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Cong Houab23bfb2015-07-15 22:48:29 +000064INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000065 "Branch Probability Analysis", false, true)
66
Reid Kleckner05da2fe2019-11-13 13:15:01 -080067BranchProbabilityInfoWrapperPass::BranchProbabilityInfoWrapperPass()
68 : FunctionPass(ID) {
69 initializeBranchProbabilityInfoWrapperPassPass(
70 *PassRegistry::getPassRegistry());
71}
72
Cong Houab23bfb2015-07-15 22:48:29 +000073char BranchProbabilityInfoWrapperPass::ID = 0;
Andrew Trick49371f32011-06-04 01:16:30 +000074
Chandler Carruth7a0094a2011-10-24 01:40:45 +000075// Weights are for internal use only. They are used by heuristics to help to
76// estimate edges' probability. Example:
77//
78// Using "Loop Branch Heuristics" we predict weights of edges for the
79// block BB2.
80// ...
81// |
82// V
83// BB1<-+
84// | |
85// | | (Weight = 124)
86// V |
87// BB2--+
88// |
89// | (Weight = 4)
90// V
91// BB3
92//
93// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
94// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
95static const uint32_t LBH_TAKEN_WEIGHT = 124;
96static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
John Brawn29bbed32018-02-23 17:17:31 +000097// Unlikely edges within a loop are half as likely as other edges
98static const uint32_t LBH_UNLIKELY_WEIGHT = 62;
Andrew Trick49371f32011-06-04 01:16:30 +000099
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000100/// Unreachable-terminating branch taken probability.
Chandler Carruth7111f452011-10-24 12:01:08 +0000101///
Serguei Katkovba831f72017-05-18 06:11:56 +0000102/// This is the probability for a branch being taken to a block that terminates
Chandler Carruth7111f452011-10-24 12:01:08 +0000103/// (eventually) in unreachable. These are predicted as unlikely as possible.
Serguei Katkovba831f72017-05-18 06:11:56 +0000104/// All reachable probability will equally share the remaining part.
105static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000106
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000107/// Weight for a branch taken going into a cold block.
Diego Novilloc6399532013-05-24 12:26:52 +0000108///
109/// This is the weight for a branch taken toward a block marked
110/// cold. A block is marked cold if it's postdominated by a
111/// block containing a call to a cold function. Cold functions
112/// are those marked with attribute 'cold'.
113static const uint32_t CC_TAKEN_WEIGHT = 4;
114
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000115/// Weight for a branch not-taken into a cold block.
Diego Novilloc6399532013-05-24 12:26:52 +0000116///
117/// This is the weight for a branch not taken toward a block marked
118/// cold.
119static const uint32_t CC_NONTAKEN_WEIGHT = 64;
120
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000121static const uint32_t PH_TAKEN_WEIGHT = 20;
122static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000123
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000124static const uint32_t ZH_TAKEN_WEIGHT = 20;
125static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000126
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000127static const uint32_t FPH_TAKEN_WEIGHT = 20;
128static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000129
Guozhi Weib329e072019-09-10 17:25:11 +0000130/// This is the probability for an ordered floating point comparison.
131static const uint32_t FPH_ORD_WEIGHT = 1024 * 1024 - 1;
132/// This is the probability for an unordered floating point comparison, it means
133/// one or two of the operands are NaN. Usually it is used to test for an
134/// exceptional case, so the result is unlikely.
135static const uint32_t FPH_UNO_WEIGHT = 1;
136
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000137/// Invoke-terminating normal branch taken weight
Bill Wendlinge1c54262012-08-15 12:22:35 +0000138///
139/// This is the weight for branching to the normal destination of an invoke
140/// instruction. We expect this to happen most of the time. Set the weight to an
141/// absurdly high value so that nested loops subsume it.
142static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
143
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000144/// Invoke-terminating normal branch not-taken weight.
Bill Wendlinge1c54262012-08-15 12:22:35 +0000145///
146/// This is the weight for branching to the unwind destination of an invoke
147/// instruction. This is essentially never taken.
148static const uint32_t IH_NONTAKEN_WEIGHT = 1;
149
Taewook Oh2da205d2019-12-02 10:15:22 -0800150static void UpdatePDTWorklist(const BasicBlock *BB, PostDominatorTree *PDT,
151 SmallVectorImpl<const BasicBlock *> &WorkList,
152 SmallPtrSetImpl<const BasicBlock *> &TargetSet) {
153 SmallVector<BasicBlock *, 8> Descendants;
154 SmallPtrSet<const BasicBlock *, 16> NewItems;
Chandler Carruth7111f452011-10-24 12:01:08 +0000155
Taewook Oh2da205d2019-12-02 10:15:22 -0800156 PDT->getDescendants(const_cast<BasicBlock *>(BB), Descendants);
157 for (auto *BB : Descendants)
158 if (TargetSet.insert(BB).second)
159 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
160 if (!TargetSet.count(*PI))
161 NewItems.insert(*PI);
162 WorkList.insert(WorkList.end(), NewItems.begin(), NewItems.end());
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000163}
164
Taewook Oh2da205d2019-12-02 10:15:22 -0800165/// Compute a set of basic blocks that are post-dominated by unreachables.
166void BranchProbabilityInfo::computePostDominatedByUnreachable(
167 const Function &F, PostDominatorTree *PDT) {
168 SmallVector<const BasicBlock *, 8> WorkList;
169 for (auto &BB : F) {
170 const Instruction *TI = BB.getTerminator();
171 if (TI->getNumSuccessors() == 0) {
172 if (isa<UnreachableInst>(TI) ||
173 // If this block is terminated by a call to
174 // @llvm.experimental.deoptimize then treat it like an unreachable
175 // since the @llvm.experimental.deoptimize call is expected to
176 // practically never execute.
177 BB.getTerminatingDeoptimizeCall())
178 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByUnreachable);
179 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000180 }
181
Taewook Oh2da205d2019-12-02 10:15:22 -0800182 while (!WorkList.empty()) {
183 const BasicBlock *BB = WorkList.pop_back_val();
184 if (PostDominatedByUnreachable.count(BB))
185 continue;
186 // If the terminator is an InvokeInst, check only the normal destination
187 // block as the unwind edge of InvokeInst is also very unlikely taken.
188 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
189 if (PostDominatedByUnreachable.count(II->getNormalDest()))
190 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000191 }
Taewook Oh2da205d2019-12-02 10:15:22 -0800192 // If all the successors are unreachable, BB is unreachable as well.
193 else if (!successors(BB).empty() &&
194 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
195 return PostDominatedByUnreachable.count(Succ);
196 }))
197 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
198 }
199}
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000200
Taewook Oh2da205d2019-12-02 10:15:22 -0800201/// compute a set of basic blocks that are post-dominated by ColdCalls.
202void BranchProbabilityInfo::computePostDominatedByColdCall(
203 const Function &F, PostDominatorTree *PDT) {
204 SmallVector<const BasicBlock *, 8> WorkList;
205 for (auto &BB : F)
206 for (auto &I : BB)
207 if (const CallInst *CI = dyn_cast<CallInst>(&I))
208 if (CI->hasFnAttr(Attribute::Cold))
209 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByColdCall);
210
211 while (!WorkList.empty()) {
212 const BasicBlock *BB = WorkList.pop_back_val();
213
214 // If the terminator is an InvokeInst, check only the normal destination
215 // block as the unwind edge of InvokeInst is also very unlikely taken.
216 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
217 if (PostDominatedByColdCall.count(II->getNormalDest()))
218 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
219 }
220 // If all of successor are post dominated then BB is also done.
221 else if (!successors(BB).empty() &&
222 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
223 return PostDominatedByColdCall.count(Succ);
224 }))
225 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
226 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000227}
228
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000229/// Calculate edge weights for successors lead to unreachable.
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000230///
231/// Predict that a successor which leads necessarily to an
232/// unreachable-terminated block as extremely unlikely.
233bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000234 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000235 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000236 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000237 assert(!isa<InvokeInst>(TI) &&
238 "Invokes should have already been handled by calcInvokeHeuristics");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000239
Manman Rencf104462012-08-24 18:14:27 +0000240 SmallVector<unsigned, 4> UnreachableEdges;
241 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000242
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000243 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Chandler Carruth7111f452011-10-24 12:01:08 +0000244 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000245 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000246 else
Manman Rencf104462012-08-24 18:14:27 +0000247 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000248
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000249 // Skip probabilities if all were reachable.
250 if (UnreachableEdges.empty())
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000251 return false;
Jun Bum Lima23e5f72015-12-21 22:00:51 +0000252
Cong Houe93b8e12015-12-22 18:56:14 +0000253 if (ReachableEdges.empty()) {
254 BranchProbability Prob(1, UnreachableEdges.size());
255 for (unsigned SuccIdx : UnreachableEdges)
256 setEdgeProbability(BB, SuccIdx, Prob);
Chandler Carruth7111f452011-10-24 12:01:08 +0000257 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000258 }
259
Serguei Katkovba831f72017-05-18 06:11:56 +0000260 auto UnreachableProb = UR_TAKEN_PROB;
261 auto ReachableProb =
262 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
263 ReachableEdges.size();
Cong Houe93b8e12015-12-22 18:56:14 +0000264
265 for (unsigned SuccIdx : UnreachableEdges)
266 setEdgeProbability(BB, SuccIdx, UnreachableProb);
267 for (unsigned SuccIdx : ReachableEdges)
268 setEdgeProbability(BB, SuccIdx, ReachableProb);
Chandler Carruth7111f452011-10-24 12:01:08 +0000269
270 return true;
271}
272
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000273// Propagate existing explicit probabilities from either profile data or
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000274// 'expect' intrinsic processing. Examine metadata against unreachable
275// heuristic. The probability of the edge coming to unreachable block is
276// set to min of metadata and unreachable heuristic.
Mehdi Aminia7978772016-04-07 21:59:28 +0000277bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000278 const Instruction *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000279 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Rong Xu15848e52017-08-23 21:36:02 +0000280 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI)))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000281 return false;
282
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000283 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000284 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000285 return false;
286
Diego Novillode5b8012015-05-07 17:22:06 +0000287 // Check that the number of successors is manageable.
288 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
289
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000290 // Ensure there are weights for all of the successors. Note that the first
291 // operand to the metadata node is a name, not a weight.
292 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000293 return false;
294
Diego Novillode5b8012015-05-07 17:22:06 +0000295 // Build up the final weights that will be used in a temporary buffer.
296 // Compute the sum of all weights to later decide whether they need to
297 // be scaled to fit in 32 bits.
298 uint64_t WeightSum = 0;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000299 SmallVector<uint32_t, 2> Weights;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000300 SmallVector<unsigned, 2> UnreachableIdxs;
301 SmallVector<unsigned, 2> ReachableIdxs;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000302 Weights.reserve(TI->getNumSuccessors());
303 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000304 ConstantInt *Weight =
305 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i));
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000306 if (!Weight)
307 return false;
Diego Novillode5b8012015-05-07 17:22:06 +0000308 assert(Weight->getValue().getActiveBits() <= 32 &&
309 "Too many bits for uint32_t");
310 Weights.push_back(Weight->getZExtValue());
311 WeightSum += Weights.back();
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000312 if (PostDominatedByUnreachable.count(TI->getSuccessor(i - 1)))
313 UnreachableIdxs.push_back(i - 1);
314 else
315 ReachableIdxs.push_back(i - 1);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000316 }
317 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
Diego Novillode5b8012015-05-07 17:22:06 +0000318
319 // If the sum of weights does not fit in 32 bits, scale every weight down
320 // accordingly.
321 uint64_t ScalingFactor =
322 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
323
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000324 if (ScalingFactor > 1) {
325 WeightSum = 0;
326 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
327 Weights[i] /= ScalingFactor;
328 WeightSum += Weights[i];
329 }
Diego Novillode5b8012015-05-07 17:22:06 +0000330 }
Serguei Katkov63c9c812017-05-12 07:50:06 +0000331 assert(WeightSum <= UINT32_MAX &&
332 "Expected weights to scale down to 32 bits");
Cong Hou6a2c71a2015-12-22 23:45:55 +0000333
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000334 if (WeightSum == 0 || ReachableIdxs.size() == 0) {
Cong Hou6a2c71a2015-12-22 23:45:55 +0000335 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000336 Weights[i] = 1;
337 WeightSum = TI->getNumSuccessors();
Cong Hou6a2c71a2015-12-22 23:45:55 +0000338 }
Cong Houe93b8e12015-12-22 18:56:14 +0000339
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000340 // Set the probability.
341 SmallVector<BranchProbability, 2> BP;
342 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
343 BP.push_back({ Weights[i], static_cast<uint32_t>(WeightSum) });
344
345 // Examine the metadata against unreachable heuristic.
346 // If the unreachable heuristic is more strong then we use it for this edge.
347 if (UnreachableIdxs.size() > 0 && ReachableIdxs.size() > 0) {
348 auto ToDistribute = BranchProbability::getZero();
Serguei Katkovba831f72017-05-18 06:11:56 +0000349 auto UnreachableProb = UR_TAKEN_PROB;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000350 for (auto i : UnreachableIdxs)
351 if (UnreachableProb < BP[i]) {
352 ToDistribute += BP[i] - UnreachableProb;
353 BP[i] = UnreachableProb;
354 }
355
356 // If we modified the probability of some edges then we must distribute
357 // the difference between reachable blocks.
358 if (ToDistribute > BranchProbability::getZero()) {
359 BranchProbability PerEdge = ToDistribute / ReachableIdxs.size();
Serguei Katkov63c9c812017-05-12 07:50:06 +0000360 for (auto i : ReachableIdxs)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000361 BP[i] += PerEdge;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000362 }
363 }
364
365 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
366 setEdgeProbability(BB, i, BP[i]);
367
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000368 return true;
369}
370
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000371/// Calculate edge weights for edges leading to cold blocks.
Diego Novilloc6399532013-05-24 12:26:52 +0000372///
373/// A cold block is one post-dominated by a block with a call to a
374/// cold function. Those edges are unlikely to be taken, so we give
375/// them relatively low weight.
376///
377/// Return true if we could compute the weights for cold edges.
378/// Return false, otherwise.
Mehdi Aminia7978772016-04-07 21:59:28 +0000379bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000380 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000381 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000382 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000383 assert(!isa<InvokeInst>(TI) &&
384 "Invokes should have already been handled by calcInvokeHeuristics");
Diego Novilloc6399532013-05-24 12:26:52 +0000385
386 // Determine which successors are post-dominated by a cold block.
387 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000388 SmallVector<unsigned, 4> NormalEdges;
Mehdi Aminia7978772016-04-07 21:59:28 +0000389 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Diego Novilloc6399532013-05-24 12:26:52 +0000390 if (PostDominatedByColdCall.count(*I))
391 ColdEdges.push_back(I.getSuccessorIndex());
392 else
393 NormalEdges.push_back(I.getSuccessorIndex());
394
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000395 // Skip probabilities if no cold edges.
396 if (ColdEdges.empty())
Diego Novilloc6399532013-05-24 12:26:52 +0000397 return false;
398
Cong Houe93b8e12015-12-22 18:56:14 +0000399 if (NormalEdges.empty()) {
400 BranchProbability Prob(1, ColdEdges.size());
401 for (unsigned SuccIdx : ColdEdges)
402 setEdgeProbability(BB, SuccIdx, Prob);
Diego Novilloc6399532013-05-24 12:26:52 +0000403 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000404 }
405
Vedant Kumara4bd1462016-12-17 01:02:08 +0000406 auto ColdProb = BranchProbability::getBranchProbability(
407 CC_TAKEN_WEIGHT,
408 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
409 auto NormalProb = BranchProbability::getBranchProbability(
410 CC_NONTAKEN_WEIGHT,
411 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
Cong Houe93b8e12015-12-22 18:56:14 +0000412
413 for (unsigned SuccIdx : ColdEdges)
414 setEdgeProbability(BB, SuccIdx, ColdProb);
415 for (unsigned SuccIdx : NormalEdges)
416 setEdgeProbability(BB, SuccIdx, NormalProb);
Diego Novilloc6399532013-05-24 12:26:52 +0000417
418 return true;
419}
420
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000421// Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
Andrew Trick49371f32011-06-04 01:16:30 +0000422// between two pointer or pointer and NULL will fail.
Mehdi Aminia7978772016-04-07 21:59:28 +0000423bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
424 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Andrew Trick49371f32011-06-04 01:16:30 +0000425 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000426 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000427
428 Value *Cond = BI->getCondition();
429 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000430 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000431 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000432
433 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000434
435 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000436 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000437
Nick Lewycky75b20532011-06-04 02:07:10 +0000438 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000439
Andrew Trick49371f32011-06-04 01:16:30 +0000440 // p != 0 -> isProb = true
441 // p == 0 -> isProb = false
442 // p != q -> isProb = true
443 // p == q -> isProb = false;
Manman Rencf104462012-08-24 18:14:27 +0000444 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000445 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000446 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000447 std::swap(TakenIdx, NonTakenIdx);
Andrew Trick49371f32011-06-04 01:16:30 +0000448
Cong Houe93b8e12015-12-22 18:56:14 +0000449 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
450 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
451 setEdgeProbability(BB, TakenIdx, TakenProb);
452 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000453 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000454}
455
Geoff Berryeed65312017-11-01 15:16:50 +0000456static int getSCCNum(const BasicBlock *BB,
457 const BranchProbabilityInfo::SccInfo &SccI) {
458 auto SccIt = SccI.SccNums.find(BB);
459 if (SccIt == SccI.SccNums.end())
460 return -1;
461 return SccIt->second;
462}
463
464// Consider any block that is an entry point to the SCC as a header.
465static bool isSCCHeader(const BasicBlock *BB, int SccNum,
466 BranchProbabilityInfo::SccInfo &SccI) {
467 assert(getSCCNum(BB, SccI) == SccNum);
468
469 // Lazily compute the set of headers for a given SCC and cache the results
470 // in the SccHeaderMap.
471 if (SccI.SccHeaders.size() <= static_cast<unsigned>(SccNum))
472 SccI.SccHeaders.resize(SccNum + 1);
473 auto &HeaderMap = SccI.SccHeaders[SccNum];
474 bool Inserted;
475 BranchProbabilityInfo::SccHeaderMap::iterator HeaderMapIt;
476 std::tie(HeaderMapIt, Inserted) = HeaderMap.insert(std::make_pair(BB, false));
477 if (Inserted) {
478 bool IsHeader = llvm::any_of(make_range(pred_begin(BB), pred_end(BB)),
479 [&](const BasicBlock *Pred) {
480 return getSCCNum(Pred, SccI) != SccNum;
481 });
482 HeaderMapIt->second = IsHeader;
483 return IsHeader;
484 } else
485 return HeaderMapIt->second;
486}
487
John Brawn29bbed32018-02-23 17:17:31 +0000488// Compute the unlikely successors to the block BB in the loop L, specifically
489// those that are unlikely because this is a loop, and add them to the
490// UnlikelyBlocks set.
491static void
492computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
493 SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
494 // Sometimes in a loop we have a branch whose condition is made false by
495 // taking it. This is typically something like
496 // int n = 0;
497 // while (...) {
498 // if (++n >= MAX) {
499 // n = 0;
500 // }
501 // }
502 // In this sort of situation taking the branch means that at the very least it
503 // won't be taken again in the next iteration of the loop, so we should
504 // consider it less likely than a typical branch.
505 //
506 // We detect this by looking back through the graph of PHI nodes that sets the
507 // value that the condition depends on, and seeing if we can reach a successor
508 // block which can be determined to make the condition false.
509 //
510 // FIXME: We currently consider unlikely blocks to be half as likely as other
511 // blocks, but if we consider the example above the likelyhood is actually
512 // 1/MAX. We could therefore be more precise in how unlikely we consider
513 // blocks to be, but it would require more careful examination of the form
514 // of the comparison expression.
515 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
516 if (!BI || !BI->isConditional())
517 return;
518
519 // Check if the branch is based on an instruction compared with a constant
520 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
521 if (!CI || !isa<Instruction>(CI->getOperand(0)) ||
522 !isa<Constant>(CI->getOperand(1)))
523 return;
524
525 // Either the instruction must be a PHI, or a chain of operations involving
526 // constants that ends in a PHI which we can then collapse into a single value
527 // if the PHI value is known.
528 Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0));
529 PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
530 Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1));
531 // Collect the instructions until we hit a PHI
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000532 SmallVector<BinaryOperator *, 1> InstChain;
John Brawn29bbed32018-02-23 17:17:31 +0000533 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
534 isa<Constant>(CmpLHS->getOperand(1))) {
535 // Stop if the chain extends outside of the loop
536 if (!L->contains(CmpLHS))
537 return;
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000538 InstChain.push_back(cast<BinaryOperator>(CmpLHS));
John Brawn29bbed32018-02-23 17:17:31 +0000539 CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
540 if (CmpLHS)
541 CmpPHI = dyn_cast<PHINode>(CmpLHS);
542 }
543 if (!CmpPHI || !L->contains(CmpPHI))
544 return;
545
546 // Trace the phi node to find all values that come from successors of BB
547 SmallPtrSet<PHINode*, 8> VisitedInsts;
548 SmallVector<PHINode*, 8> WorkList;
549 WorkList.push_back(CmpPHI);
550 VisitedInsts.insert(CmpPHI);
551 while (!WorkList.empty()) {
552 PHINode *P = WorkList.back();
553 WorkList.pop_back();
554 for (BasicBlock *B : P->blocks()) {
555 // Skip blocks that aren't part of the loop
556 if (!L->contains(B))
557 continue;
558 Value *V = P->getIncomingValueForBlock(B);
559 // If the source is a PHI add it to the work list if we haven't
560 // already visited it.
561 if (PHINode *PN = dyn_cast<PHINode>(V)) {
562 if (VisitedInsts.insert(PN).second)
563 WorkList.push_back(PN);
564 continue;
565 }
566 // If this incoming value is a constant and B is a successor of BB, then
567 // we can constant-evaluate the compare to see if it makes the branch be
568 // taken or not.
569 Constant *CmpLHSConst = dyn_cast<Constant>(V);
570 if (!CmpLHSConst ||
571 std::find(succ_begin(BB), succ_end(BB), B) == succ_end(BB))
572 continue;
573 // First collapse InstChain
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000574 for (Instruction *I : llvm::reverse(InstChain)) {
John Brawn29bbed32018-02-23 17:17:31 +0000575 CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst,
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000576 cast<Constant>(I->getOperand(1)), true);
John Brawn29bbed32018-02-23 17:17:31 +0000577 if (!CmpLHSConst)
578 break;
579 }
580 if (!CmpLHSConst)
581 continue;
582 // Now constant-evaluate the compare
583 Constant *Result = ConstantExpr::getCompare(CI->getPredicate(),
584 CmpLHSConst, CmpConst, true);
585 // If the result means we don't branch to the block then that block is
586 // unlikely.
587 if (Result &&
588 ((Result->isZeroValue() && B == BI->getSuccessor(0)) ||
589 (Result->isOneValue() && B == BI->getSuccessor(1))))
590 UnlikelyBlocks.insert(B);
591 }
592 }
593}
594
Andrew Trick49371f32011-06-04 01:16:30 +0000595// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
596// as taken, exiting edges as not-taken.
Mehdi Aminia7978772016-04-07 21:59:28 +0000597bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
Geoff Berryeed65312017-11-01 15:16:50 +0000598 const LoopInfo &LI,
599 SccInfo &SccI) {
600 int SccNum;
Cong Houab23bfb2015-07-15 22:48:29 +0000601 Loop *L = LI.getLoopFor(BB);
Geoff Berryeed65312017-11-01 15:16:50 +0000602 if (!L) {
603 SccNum = getSCCNum(BB, SccI);
604 if (SccNum < 0)
605 return false;
606 }
Andrew Trick49371f32011-06-04 01:16:30 +0000607
John Brawn29bbed32018-02-23 17:17:31 +0000608 SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks;
609 if (L)
610 computeUnlikelySuccessors(BB, L, UnlikelyBlocks);
611
Manman Rencf104462012-08-24 18:14:27 +0000612 SmallVector<unsigned, 8> BackEdges;
613 SmallVector<unsigned, 8> ExitingEdges;
614 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
John Brawn29bbed32018-02-23 17:17:31 +0000615 SmallVector<unsigned, 8> UnlikelyEdges;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000616
Mehdi Aminia7978772016-04-07 21:59:28 +0000617 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Geoff Berryeed65312017-11-01 15:16:50 +0000618 // Use LoopInfo if we have it, otherwise fall-back to SCC info to catch
619 // irreducible loops.
620 if (L) {
John Brawn29bbed32018-02-23 17:17:31 +0000621 if (UnlikelyBlocks.count(*I) != 0)
622 UnlikelyEdges.push_back(I.getSuccessorIndex());
623 else if (!L->contains(*I))
Geoff Berryeed65312017-11-01 15:16:50 +0000624 ExitingEdges.push_back(I.getSuccessorIndex());
625 else if (L->getHeader() == *I)
626 BackEdges.push_back(I.getSuccessorIndex());
627 else
628 InEdges.push_back(I.getSuccessorIndex());
629 } else {
630 if (getSCCNum(*I, SccI) != SccNum)
631 ExitingEdges.push_back(I.getSuccessorIndex());
632 else if (isSCCHeader(*I, SccNum, SccI))
633 BackEdges.push_back(I.getSuccessorIndex());
634 else
635 InEdges.push_back(I.getSuccessorIndex());
636 }
Andrew Trick49371f32011-06-04 01:16:30 +0000637 }
638
John Brawn29bbed32018-02-23 17:17:31 +0000639 if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty())
Akira Hatanaka5638b892014-04-14 16:56:19 +0000640 return false;
641
Cong Houe93b8e12015-12-22 18:56:14 +0000642 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
643 // normalize them so that they sum up to one.
Cong Houe93b8e12015-12-22 18:56:14 +0000644 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
645 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
John Brawn29bbed32018-02-23 17:17:31 +0000646 (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) +
Cong Houe93b8e12015-12-22 18:56:14 +0000647 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
Andrew Trick49371f32011-06-04 01:16:30 +0000648
Cong Houe93b8e12015-12-22 18:56:14 +0000649 if (uint32_t numBackEdges = BackEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000650 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
651 auto Prob = TakenProb / numBackEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000652 for (unsigned SuccIdx : BackEdges)
653 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000654 }
655
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000656 if (uint32_t numInEdges = InEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000657 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
658 auto Prob = TakenProb / numInEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000659 for (unsigned SuccIdx : InEdges)
660 setEdgeProbability(BB, SuccIdx, Prob);
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000661 }
662
Chandler Carruth32f46e72011-10-25 09:47:41 +0000663 if (uint32_t numExitingEdges = ExitingEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000664 BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT,
665 Denom);
666 auto Prob = NotTakenProb / numExitingEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000667 for (unsigned SuccIdx : ExitingEdges)
668 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000669 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000670
John Brawn29bbed32018-02-23 17:17:31 +0000671 if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) {
672 BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT,
673 Denom);
674 auto Prob = UnlikelyProb / numUnlikelyEdges;
675 for (unsigned SuccIdx : UnlikelyEdges)
676 setEdgeProbability(BB, SuccIdx, Prob);
677 }
678
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000679 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000680}
681
John Brawnda4a68a2017-06-08 09:44:40 +0000682bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
683 const TargetLibraryInfo *TLI) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000684 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000685 if (!BI || !BI->isConditional())
686 return false;
687
688 Value *Cond = BI->getCondition();
689 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
690 if (!CI)
691 return false;
692
Sam Parker0b53e842019-02-15 11:50:21 +0000693 auto GetConstantInt = [](Value *V) {
694 if (auto *I = dyn_cast<BitCastInst>(V))
695 return dyn_cast<ConstantInt>(I->getOperand(0));
696 return dyn_cast<ConstantInt>(V);
697 };
698
Jakub Staszak17af66a2011-07-31 03:27:24 +0000699 Value *RHS = CI->getOperand(1);
Sam Parker0b53e842019-02-15 11:50:21 +0000700 ConstantInt *CV = GetConstantInt(RHS);
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000701 if (!CV)
Jakub Staszak17af66a2011-07-31 03:27:24 +0000702 return false;
703
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000704 // If the LHS is the result of AND'ing a value with a single bit bitmask,
705 // we don't have information about probabilities.
706 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
707 if (LHS->getOpcode() == Instruction::And)
708 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
Craig Topper4e22ee62017-08-04 16:59:29 +0000709 if (AndRHS->getValue().isPowerOf2())
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000710 return false;
711
John Brawnda4a68a2017-06-08 09:44:40 +0000712 // Check if the LHS is the return value of a library function
713 LibFunc Func = NumLibFuncs;
714 if (TLI)
715 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
716 if (Function *CalledFn = Call->getCalledFunction())
717 TLI->getLibFunc(*CalledFn, Func);
718
Jakub Staszak17af66a2011-07-31 03:27:24 +0000719 bool isProb;
John Brawnda4a68a2017-06-08 09:44:40 +0000720 if (Func == LibFunc_strcasecmp ||
721 Func == LibFunc_strcmp ||
722 Func == LibFunc_strncasecmp ||
723 Func == LibFunc_strncmp ||
724 Func == LibFunc_memcmp) {
725 // strcmp and similar functions return zero, negative, or positive, if the
726 // first string is equal, less, or greater than the second. We consider it
727 // likely that the strings are not equal, so a comparison with zero is
728 // probably false, but also a comparison with any other number is also
729 // probably false given that what exactly is returned for nonzero values is
730 // not specified. Any kind of comparison other than equality we know
731 // nothing about.
732 switch (CI->getPredicate()) {
733 case CmpInst::ICMP_EQ:
734 isProb = false;
735 break;
736 case CmpInst::ICMP_NE:
737 isProb = true;
738 break;
739 default:
740 return false;
741 }
742 } else if (CV->isZero()) {
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000743 switch (CI->getPredicate()) {
744 case CmpInst::ICMP_EQ:
745 // X == 0 -> Unlikely
746 isProb = false;
747 break;
748 case CmpInst::ICMP_NE:
749 // X != 0 -> Likely
750 isProb = true;
751 break;
752 case CmpInst::ICMP_SLT:
753 // X < 0 -> Unlikely
754 isProb = false;
755 break;
756 case CmpInst::ICMP_SGT:
757 // X > 0 -> Likely
758 isProb = true;
759 break;
760 default:
761 return false;
762 }
763 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
764 // InstCombine canonicalizes X <= 0 into X < 1.
765 // X <= 0 -> Unlikely
Jakub Staszak17af66a2011-07-31 03:27:24 +0000766 isProb = false;
Craig Topper79ab6432017-07-06 18:39:47 +0000767 } else if (CV->isMinusOne()) {
Hal Finkel4d949302013-11-01 10:58:22 +0000768 switch (CI->getPredicate()) {
769 case CmpInst::ICMP_EQ:
770 // X == -1 -> Unlikely
771 isProb = false;
772 break;
773 case CmpInst::ICMP_NE:
774 // X != -1 -> Likely
775 isProb = true;
776 break;
777 case CmpInst::ICMP_SGT:
778 // InstCombine canonicalizes X >= 0 into X > -1.
779 // X >= 0 -> Likely
780 isProb = true;
781 break;
782 default:
783 return false;
784 }
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000785 } else {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000786 return false;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000787 }
Jakub Staszak17af66a2011-07-31 03:27:24 +0000788
Manman Rencf104462012-08-24 18:14:27 +0000789 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszak17af66a2011-07-31 03:27:24 +0000790
791 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000792 std::swap(TakenIdx, NonTakenIdx);
Jakub Staszak17af66a2011-07-31 03:27:24 +0000793
Cong Houe93b8e12015-12-22 18:56:14 +0000794 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
795 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
796 setEdgeProbability(BB, TakenIdx, TakenProb);
797 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000798 return true;
799}
800
Mehdi Aminia7978772016-04-07 21:59:28 +0000801bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
802 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000803 if (!BI || !BI->isConditional())
804 return false;
805
806 Value *Cond = BI->getCondition();
807 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000808 if (!FCmp)
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000809 return false;
810
Guozhi Weib329e072019-09-10 17:25:11 +0000811 uint32_t TakenWeight = FPH_TAKEN_WEIGHT;
812 uint32_t NontakenWeight = FPH_NONTAKEN_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000813 bool isProb;
814 if (FCmp->isEquality()) {
815 // f1 == f2 -> Unlikely
816 // f1 != f2 -> Likely
817 isProb = !FCmp->isTrueWhenEqual();
818 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
819 // !isnan -> Likely
820 isProb = true;
Guozhi Weib329e072019-09-10 17:25:11 +0000821 TakenWeight = FPH_ORD_WEIGHT;
822 NontakenWeight = FPH_UNO_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000823 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
824 // isnan -> Unlikely
825 isProb = false;
Guozhi Weib329e072019-09-10 17:25:11 +0000826 TakenWeight = FPH_ORD_WEIGHT;
827 NontakenWeight = FPH_UNO_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000828 } else {
829 return false;
830 }
831
Manman Rencf104462012-08-24 18:14:27 +0000832 unsigned TakenIdx = 0, NonTakenIdx = 1;
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000833
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000834 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000835 std::swap(TakenIdx, NonTakenIdx);
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000836
Guozhi Weib329e072019-09-10 17:25:11 +0000837 BranchProbability TakenProb(TakenWeight, TakenWeight + NontakenWeight);
Cong Houe93b8e12015-12-22 18:56:14 +0000838 setEdgeProbability(BB, TakenIdx, TakenProb);
839 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000840 return true;
841}
Jakub Staszak17af66a2011-07-31 03:27:24 +0000842
Mehdi Aminia7978772016-04-07 21:59:28 +0000843bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
844 const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000845 if (!II)
846 return false;
847
Cong Houe93b8e12015-12-22 18:56:14 +0000848 BranchProbability TakenProb(IH_TAKEN_WEIGHT,
849 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
850 setEdgeProbability(BB, 0 /*Index for Normal*/, TakenProb);
851 setEdgeProbability(BB, 1 /*Index for Unwind*/, TakenProb.getCompl());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000852 return true;
853}
854
Pete Cooperb9d2e342015-05-28 19:43:06 +0000855void BranchProbabilityInfo::releaseMemory() {
Cong Houe93b8e12015-12-22 18:56:14 +0000856 Probs.clear();
Pete Cooperb9d2e342015-05-28 19:43:06 +0000857}
858
Alina Sbirlea62a50a92020-01-15 14:02:33 -0800859bool BranchProbabilityInfo::invalidate(Function &, const PreservedAnalyses &PA,
860 FunctionAnalysisManager::Invalidator &) {
861 // Check whether the analysis, all analyses on functions, or the function's
862 // CFG have been preserved.
863 auto PAC = PA.getChecker<BranchProbabilityAnalysis>();
864 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
865 PAC.preservedSet<CFGAnalyses>());
866}
867
Cong Houab23bfb2015-07-15 22:48:29 +0000868void BranchProbabilityInfo::print(raw_ostream &OS) const {
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000869 OS << "---- Branch Probabilities ----\n";
870 // We print the probabilities from the last function the analysis ran over,
871 // or the function it is currently running over.
872 assert(LastF && "Cannot print prior to running over a function");
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000873 for (const auto &BI : *LastF) {
874 for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
875 ++SI) {
876 printEdgeProbability(OS << " ", &BI, *SI);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000877 }
878 }
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000879}
880
Jakub Staszakefd94c82011-07-29 19:30:00 +0000881bool BranchProbabilityInfo::
882isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000883 // Hot probability is at least 4/5 = 80%
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000884 // FIXME: Compare against a static "hot" BranchProbability.
885 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick49371f32011-06-04 01:16:30 +0000886}
887
Mehdi Aminia7978772016-04-07 21:59:28 +0000888const BasicBlock *
889BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
Cong Houe93b8e12015-12-22 18:56:14 +0000890 auto MaxProb = BranchProbability::getZero();
Mehdi Aminia7978772016-04-07 21:59:28 +0000891 const BasicBlock *MaxSucc = nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000892
Mehdi Aminia7978772016-04-07 21:59:28 +0000893 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
894 const BasicBlock *Succ = *I;
Cong Houe93b8e12015-12-22 18:56:14 +0000895 auto Prob = getEdgeProbability(BB, Succ);
896 if (Prob > MaxProb) {
897 MaxProb = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000898 MaxSucc = Succ;
899 }
900 }
901
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000902 // Hot probability is at least 4/5 = 80%
Cong Houe93b8e12015-12-22 18:56:14 +0000903 if (MaxProb > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +0000904 return MaxSucc;
905
Craig Topper9f008862014-04-15 04:59:12 +0000906 return nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000907}
908
Cong Houe93b8e12015-12-22 18:56:14 +0000909/// Get the raw edge probability for the edge. If can't find it, return a
910/// default probability 1/N where N is the number of successors. Here an edge is
911/// specified using PredBlock and an
912/// index to the successors.
913BranchProbability
914BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
915 unsigned IndexInSuccessors) const {
916 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick49371f32011-06-04 01:16:30 +0000917
Cong Houe93b8e12015-12-22 18:56:14 +0000918 if (I != Probs.end())
Andrew Trick49371f32011-06-04 01:16:30 +0000919 return I->second;
920
Vedant Kumare0b5f862018-05-10 23:01:54 +0000921 return {1, static_cast<uint32_t>(succ_size(Src))};
Andrew Trick49371f32011-06-04 01:16:30 +0000922}
923
Cong Houd97c1002015-12-01 05:29:22 +0000924BranchProbability
925BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
926 succ_const_iterator Dst) const {
927 return getEdgeProbability(Src, Dst.getSuccessorIndex());
928}
929
Cong Houe93b8e12015-12-22 18:56:14 +0000930/// Get the raw edge probability calculated for the block pair. This returns the
931/// sum of all raw edge probabilities from Src to Dst.
932BranchProbability
933BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
934 const BasicBlock *Dst) const {
935 auto Prob = BranchProbability::getZero();
936 bool FoundProb = false;
937 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
938 if (*I == Dst) {
939 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
940 if (MapI != Probs.end()) {
941 FoundProb = true;
942 Prob += MapI->second;
943 }
944 }
945 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
946 return FoundProb ? Prob : BranchProbability(1, succ_num);
947}
948
949/// Set the edge probability for a given edge specified by PredBlock and an
950/// index to the successors.
951void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
952 unsigned IndexInSuccessors,
953 BranchProbability Prob) {
954 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000955 Handles.insert(BasicBlockCallbackVH(Src, this));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000956 LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
957 << IndexInSuccessors << " successor probability to " << Prob
958 << "\n");
Cong Houe93b8e12015-12-22 18:56:14 +0000959}
960
Andrew Trick49371f32011-06-04 01:16:30 +0000961raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000962BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
963 const BasicBlock *Src,
964 const BasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +0000965 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000966 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000967 << " probability is " << Prob
968 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +0000969
970 return OS;
971}
Cong Houab23bfb2015-07-15 22:48:29 +0000972
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000973void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
974 for (auto I = Probs.begin(), E = Probs.end(); I != E; ++I) {
975 auto Key = I->first;
976 if (Key.first == BB)
977 Probs.erase(Key);
978 }
979}
980
John Brawnda4a68a2017-06-08 09:44:40 +0000981void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
982 const TargetLibraryInfo *TLI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000983 LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
984 << " ----\n\n");
Cong Houab23bfb2015-07-15 22:48:29 +0000985 LastF = &F; // Store the last function we ran on for printing.
986 assert(PostDominatedByUnreachable.empty());
987 assert(PostDominatedByColdCall.empty());
988
Geoff Berryeed65312017-11-01 15:16:50 +0000989 // Record SCC numbers of blocks in the CFG to identify irreducible loops.
990 // FIXME: We could only calculate this if the CFG is known to be irreducible
991 // (perhaps cache this info in LoopInfo if we can easily calculate it there?).
992 int SccNum = 0;
993 SccInfo SccI;
994 for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd();
995 ++It, ++SccNum) {
996 // Ignore single-block SCCs since they either aren't loops or LoopInfo will
997 // catch them.
998 const std::vector<const BasicBlock *> &Scc = *It;
999 if (Scc.size() == 1)
1000 continue;
1001
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001002 LLVM_DEBUG(dbgs() << "BPI: SCC " << SccNum << ":");
Geoff Berryeed65312017-11-01 15:16:50 +00001003 for (auto *BB : Scc) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001004 LLVM_DEBUG(dbgs() << " " << BB->getName());
Geoff Berryeed65312017-11-01 15:16:50 +00001005 SccI.SccNums[BB] = SccNum;
1006 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001007 LLVM_DEBUG(dbgs() << "\n");
Geoff Berryeed65312017-11-01 15:16:50 +00001008 }
1009
Taewook Oh2da205d2019-12-02 10:15:22 -08001010 std::unique_ptr<PostDominatorTree> PDT =
1011 std::make_unique<PostDominatorTree>(const_cast<Function &>(F));
1012 computePostDominatedByUnreachable(F, PDT.get());
1013 computePostDominatedByColdCall(F, PDT.get());
1014
Cong Houab23bfb2015-07-15 22:48:29 +00001015 // Walk the basic blocks in post-order so that we can build up state about
1016 // the successors of a block iteratively.
1017 for (auto BB : post_order(&F.getEntryBlock())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001018 LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName()
1019 << "\n");
Serguei Katkov11d9c4f2017-04-17 06:39:47 +00001020 // If there is no at least two successors, no sense to set probability.
1021 if (BB->getTerminator()->getNumSuccessors() < 2)
1022 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001023 if (calcMetadataWeights(BB))
1024 continue;
Artur Pilipenko4d063e72018-06-08 13:03:21 +00001025 if (calcInvokeHeuristics(BB))
1026 continue;
Serguei Katkov2616bbb2017-04-17 04:33:04 +00001027 if (calcUnreachableHeuristics(BB))
1028 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001029 if (calcColdCallHeuristics(BB))
1030 continue;
Geoff Berryeed65312017-11-01 15:16:50 +00001031 if (calcLoopBranchHeuristics(BB, LI, SccI))
Cong Houab23bfb2015-07-15 22:48:29 +00001032 continue;
1033 if (calcPointerHeuristics(BB))
1034 continue;
John Brawnda4a68a2017-06-08 09:44:40 +00001035 if (calcZeroHeuristics(BB, TLI))
Cong Houab23bfb2015-07-15 22:48:29 +00001036 continue;
1037 if (calcFloatingPointHeuristics(BB))
1038 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001039 }
1040
1041 PostDominatedByUnreachable.clear();
1042 PostDominatedByColdCall.clear();
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +00001043
1044 if (PrintBranchProb &&
1045 (PrintBranchProbFuncName.empty() ||
1046 F.getName().equals(PrintBranchProbFuncName))) {
1047 print(dbgs());
1048 }
Cong Houab23bfb2015-07-15 22:48:29 +00001049}
1050
1051void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
1052 AnalysisUsage &AU) const {
Mikael Holmen2ca16892018-05-17 09:05:40 +00001053 // We require DT so it's available when LI is available. The LI updating code
1054 // asserts that DT is also present so if we don't make sure that we have DT
1055 // here, that assert will trigger.
1056 AU.addRequired<DominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001057 AU.addRequired<LoopInfoWrapperPass>();
John Brawnda4a68a2017-06-08 09:44:40 +00001058 AU.addRequired<TargetLibraryInfoWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001059 AU.setPreservesAll();
1060}
1061
1062bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
1063 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnson9c27b592019-09-07 03:09:36 +00001064 const TargetLibraryInfo &TLI =
1065 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
John Brawnda4a68a2017-06-08 09:44:40 +00001066 BPI.calculate(F, LI, &TLI);
Cong Houab23bfb2015-07-15 22:48:29 +00001067 return false;
1068}
1069
1070void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
1071
1072void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
1073 const Module *) const {
1074 BPI.print(OS);
1075}
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001076
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001077AnalysisKey BranchProbabilityAnalysis::Key;
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001078BranchProbabilityInfo
Sean Silva36e0d012016-08-09 00:28:15 +00001079BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001080 BranchProbabilityInfo BPI;
John Brawnda4a68a2017-06-08 09:44:40 +00001081 BPI.calculate(F, AM.getResult<LoopAnalysis>(F), &AM.getResult<TargetLibraryAnalysis>(F));
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001082 return BPI;
1083}
1084
1085PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +00001086BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001087 OS << "Printing analysis results of BPI for function "
1088 << "'" << F.getName() << "':"
1089 << "\n";
1090 AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
1091 return PreservedAnalyses::all();
1092}