blob: da711c4acaf6eceee2ac146ee008fcc269d9eea6 [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)
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +070064INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Cong Houab23bfb2015-07-15 22:48:29 +000065INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000066 "Branch Probability Analysis", false, true)
67
Reid Kleckner05da2fe2019-11-13 13:15:01 -080068BranchProbabilityInfoWrapperPass::BranchProbabilityInfoWrapperPass()
69 : FunctionPass(ID) {
70 initializeBranchProbabilityInfoWrapperPassPass(
71 *PassRegistry::getPassRegistry());
72}
73
Cong Houab23bfb2015-07-15 22:48:29 +000074char BranchProbabilityInfoWrapperPass::ID = 0;
Andrew Trick49371f32011-06-04 01:16:30 +000075
Chandler Carruth7a0094a2011-10-24 01:40:45 +000076// Weights are for internal use only. They are used by heuristics to help to
77// estimate edges' probability. Example:
78//
79// Using "Loop Branch Heuristics" we predict weights of edges for the
80// block BB2.
81// ...
82// |
83// V
84// BB1<-+
85// | |
86// | | (Weight = 124)
87// V |
88// BB2--+
89// |
90// | (Weight = 4)
91// V
92// BB3
93//
94// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
95// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
96static const uint32_t LBH_TAKEN_WEIGHT = 124;
97static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
John Brawn29bbed32018-02-23 17:17:31 +000098// Unlikely edges within a loop are half as likely as other edges
99static const uint32_t LBH_UNLIKELY_WEIGHT = 62;
Andrew Trick49371f32011-06-04 01:16:30 +0000100
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000101/// Unreachable-terminating branch taken probability.
Chandler Carruth7111f452011-10-24 12:01:08 +0000102///
Serguei Katkovba831f72017-05-18 06:11:56 +0000103/// This is the probability for a branch being taken to a block that terminates
Chandler Carruth7111f452011-10-24 12:01:08 +0000104/// (eventually) in unreachable. These are predicted as unlikely as possible.
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700105/// All reachable probability will proportionally share the remaining part.
Serguei Katkovba831f72017-05-18 06:11:56 +0000106static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000107
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000108/// Weight for a branch taken going into a cold block.
Diego Novilloc6399532013-05-24 12:26:52 +0000109///
110/// This is the weight for a branch taken toward a block marked
111/// cold. A block is marked cold if it's postdominated by a
112/// block containing a call to a cold function. Cold functions
113/// are those marked with attribute 'cold'.
114static const uint32_t CC_TAKEN_WEIGHT = 4;
115
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000116/// Weight for a branch not-taken into a cold block.
Diego Novilloc6399532013-05-24 12:26:52 +0000117///
118/// This is the weight for a branch not taken toward a block marked
119/// cold.
120static const uint32_t CC_NONTAKEN_WEIGHT = 64;
121
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000122static const uint32_t PH_TAKEN_WEIGHT = 20;
123static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000124
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000125static const uint32_t ZH_TAKEN_WEIGHT = 20;
126static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000127
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000128static const uint32_t FPH_TAKEN_WEIGHT = 20;
129static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000130
Guozhi Weib329e072019-09-10 17:25:11 +0000131/// This is the probability for an ordered floating point comparison.
132static const uint32_t FPH_ORD_WEIGHT = 1024 * 1024 - 1;
133/// This is the probability for an unordered floating point comparison, it means
134/// one or two of the operands are NaN. Usually it is used to test for an
135/// exceptional case, so the result is unlikely.
136static const uint32_t FPH_UNO_WEIGHT = 1;
137
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000138/// Invoke-terminating normal branch taken weight
Bill Wendlinge1c54262012-08-15 12:22:35 +0000139///
140/// This is the weight for branching to the normal destination of an invoke
141/// instruction. We expect this to happen most of the time. Set the weight to an
142/// absurdly high value so that nested loops subsume it.
143static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
144
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000145/// Invoke-terminating normal branch not-taken weight.
Bill Wendlinge1c54262012-08-15 12:22:35 +0000146///
147/// This is the weight for branching to the unwind destination of an invoke
148/// instruction. This is essentially never taken.
149static const uint32_t IH_NONTAKEN_WEIGHT = 1;
150
Taewook Oh2da205d2019-12-02 10:15:22 -0800151static void UpdatePDTWorklist(const BasicBlock *BB, PostDominatorTree *PDT,
152 SmallVectorImpl<const BasicBlock *> &WorkList,
153 SmallPtrSetImpl<const BasicBlock *> &TargetSet) {
154 SmallVector<BasicBlock *, 8> Descendants;
155 SmallPtrSet<const BasicBlock *, 16> NewItems;
Chandler Carruth7111f452011-10-24 12:01:08 +0000156
Taewook Oh2da205d2019-12-02 10:15:22 -0800157 PDT->getDescendants(const_cast<BasicBlock *>(BB), Descendants);
158 for (auto *BB : Descendants)
159 if (TargetSet.insert(BB).second)
160 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
161 if (!TargetSet.count(*PI))
162 NewItems.insert(*PI);
163 WorkList.insert(WorkList.end(), NewItems.begin(), NewItems.end());
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000164}
165
Taewook Oh2da205d2019-12-02 10:15:22 -0800166/// Compute a set of basic blocks that are post-dominated by unreachables.
167void BranchProbabilityInfo::computePostDominatedByUnreachable(
168 const Function &F, PostDominatorTree *PDT) {
169 SmallVector<const BasicBlock *, 8> WorkList;
170 for (auto &BB : F) {
171 const Instruction *TI = BB.getTerminator();
172 if (TI->getNumSuccessors() == 0) {
173 if (isa<UnreachableInst>(TI) ||
174 // If this block is terminated by a call to
175 // @llvm.experimental.deoptimize then treat it like an unreachable
176 // since the @llvm.experimental.deoptimize call is expected to
177 // practically never execute.
178 BB.getTerminatingDeoptimizeCall())
179 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByUnreachable);
180 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000181 }
182
Taewook Oh2da205d2019-12-02 10:15:22 -0800183 while (!WorkList.empty()) {
184 const BasicBlock *BB = WorkList.pop_back_val();
185 if (PostDominatedByUnreachable.count(BB))
186 continue;
187 // If the terminator is an InvokeInst, check only the normal destination
188 // block as the unwind edge of InvokeInst is also very unlikely taken.
189 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
190 if (PostDominatedByUnreachable.count(II->getNormalDest()))
191 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000192 }
Taewook Oh2da205d2019-12-02 10:15:22 -0800193 // If all the successors are unreachable, BB is unreachable as well.
194 else if (!successors(BB).empty() &&
195 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
196 return PostDominatedByUnreachable.count(Succ);
197 }))
198 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
199 }
200}
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000201
Taewook Oh2da205d2019-12-02 10:15:22 -0800202/// compute a set of basic blocks that are post-dominated by ColdCalls.
203void BranchProbabilityInfo::computePostDominatedByColdCall(
204 const Function &F, PostDominatorTree *PDT) {
205 SmallVector<const BasicBlock *, 8> WorkList;
206 for (auto &BB : F)
207 for (auto &I : BB)
208 if (const CallInst *CI = dyn_cast<CallInst>(&I))
209 if (CI->hasFnAttr(Attribute::Cold))
210 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByColdCall);
211
212 while (!WorkList.empty()) {
213 const BasicBlock *BB = WorkList.pop_back_val();
214
215 // If the terminator is an InvokeInst, check only the normal destination
216 // block as the unwind edge of InvokeInst is also very unlikely taken.
217 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
218 if (PostDominatedByColdCall.count(II->getNormalDest()))
219 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
220 }
221 // If all of successor are post dominated then BB is also done.
222 else if (!successors(BB).empty() &&
223 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
224 return PostDominatedByColdCall.count(Succ);
225 }))
226 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
227 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000228}
229
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000230/// Calculate edge weights for successors lead to unreachable.
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000231///
232/// Predict that a successor which leads necessarily to an
233/// unreachable-terminated block as extremely unlikely.
234bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000235 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000236 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000237 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000238 assert(!isa<InvokeInst>(TI) &&
239 "Invokes should have already been handled by calcInvokeHeuristics");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000240
Manman Rencf104462012-08-24 18:14:27 +0000241 SmallVector<unsigned, 4> UnreachableEdges;
242 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000243
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700244 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Chandler Carruth7111f452011-10-24 12:01:08 +0000245 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000246 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000247 else
Manman Rencf104462012-08-24 18:14:27 +0000248 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000249
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000250 // Skip probabilities if all were reachable.
251 if (UnreachableEdges.empty())
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000252 return false;
Jun Bum Lima23e5f72015-12-21 22:00:51 +0000253
Yevgeny Rouban81384872020-05-21 11:49:11 +0700254 SmallVector<BranchProbability, 4> EdgeProbabilities(
255 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000256 if (ReachableEdges.empty()) {
257 BranchProbability Prob(1, UnreachableEdges.size());
258 for (unsigned SuccIdx : UnreachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700259 EdgeProbabilities[SuccIdx] = Prob;
260 setEdgeProbability(BB, EdgeProbabilities);
Chandler Carruth7111f452011-10-24 12:01:08 +0000261 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000262 }
263
Serguei Katkovba831f72017-05-18 06:11:56 +0000264 auto UnreachableProb = UR_TAKEN_PROB;
265 auto ReachableProb =
266 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
267 ReachableEdges.size();
Cong Houe93b8e12015-12-22 18:56:14 +0000268
269 for (unsigned SuccIdx : UnreachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700270 EdgeProbabilities[SuccIdx] = UnreachableProb;
Cong Houe93b8e12015-12-22 18:56:14 +0000271 for (unsigned SuccIdx : ReachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700272 EdgeProbabilities[SuccIdx] = ReachableProb;
Chandler Carruth7111f452011-10-24 12:01:08 +0000273
Yevgeny Rouban81384872020-05-21 11:49:11 +0700274 setEdgeProbability(BB, EdgeProbabilities);
Chandler Carruth7111f452011-10-24 12:01:08 +0000275 return true;
276}
277
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000278// Propagate existing explicit probabilities from either profile data or
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000279// 'expect' intrinsic processing. Examine metadata against unreachable
280// heuristic. The probability of the edge coming to unreachable block is
281// set to min of metadata and unreachable heuristic.
Mehdi Aminia7978772016-04-07 21:59:28 +0000282bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000283 const Instruction *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000284 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Yevgeny Roubandcfa78a2020-06-04 15:34:14 +0700285 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI) ||
286 isa<InvokeInst>(TI)))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000287 return false;
288
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000289 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000290 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000291 return false;
292
Diego Novillode5b8012015-05-07 17:22:06 +0000293 // Check that the number of successors is manageable.
294 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
295
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000296 // Ensure there are weights for all of the successors. Note that the first
297 // operand to the metadata node is a name, not a weight.
298 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000299 return false;
300
Diego Novillode5b8012015-05-07 17:22:06 +0000301 // Build up the final weights that will be used in a temporary buffer.
302 // Compute the sum of all weights to later decide whether they need to
303 // be scaled to fit in 32 bits.
304 uint64_t WeightSum = 0;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000305 SmallVector<uint32_t, 2> Weights;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000306 SmallVector<unsigned, 2> UnreachableIdxs;
307 SmallVector<unsigned, 2> ReachableIdxs;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000308 Weights.reserve(TI->getNumSuccessors());
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700309 for (unsigned I = 1, E = WeightsNode->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000310 ConstantInt *Weight =
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700311 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(I));
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000312 if (!Weight)
313 return false;
Diego Novillode5b8012015-05-07 17:22:06 +0000314 assert(Weight->getValue().getActiveBits() <= 32 &&
315 "Too many bits for uint32_t");
316 Weights.push_back(Weight->getZExtValue());
317 WeightSum += Weights.back();
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700318 if (PostDominatedByUnreachable.count(TI->getSuccessor(I - 1)))
319 UnreachableIdxs.push_back(I - 1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000320 else
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700321 ReachableIdxs.push_back(I - 1);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000322 }
323 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
Diego Novillode5b8012015-05-07 17:22:06 +0000324
325 // If the sum of weights does not fit in 32 bits, scale every weight down
326 // accordingly.
327 uint64_t ScalingFactor =
328 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
329
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000330 if (ScalingFactor > 1) {
331 WeightSum = 0;
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700332 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
333 Weights[I] /= ScalingFactor;
334 WeightSum += Weights[I];
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000335 }
Diego Novillode5b8012015-05-07 17:22:06 +0000336 }
Serguei Katkov63c9c812017-05-12 07:50:06 +0000337 assert(WeightSum <= UINT32_MAX &&
338 "Expected weights to scale down to 32 bits");
Cong Hou6a2c71a2015-12-22 23:45:55 +0000339
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000340 if (WeightSum == 0 || ReachableIdxs.size() == 0) {
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700341 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I)
342 Weights[I] = 1;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000343 WeightSum = TI->getNumSuccessors();
Cong Hou6a2c71a2015-12-22 23:45:55 +0000344 }
Cong Houe93b8e12015-12-22 18:56:14 +0000345
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000346 // Set the probability.
347 SmallVector<BranchProbability, 2> BP;
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700348 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I)
349 BP.push_back({ Weights[I], static_cast<uint32_t>(WeightSum) });
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000350
351 // Examine the metadata against unreachable heuristic.
352 // If the unreachable heuristic is more strong then we use it for this edge.
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700353 if (UnreachableIdxs.size() == 0 || ReachableIdxs.size() == 0) {
354 setEdgeProbability(BB, BP);
355 return true;
356 }
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000357
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700358 auto UnreachableProb = UR_TAKEN_PROB;
359 for (auto I : UnreachableIdxs)
360 if (UnreachableProb < BP[I]) {
361 BP[I] = UnreachableProb;
362 }
Yevgeny Rouban81384872020-05-21 11:49:11 +0700363
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700364 // Sum of all edge probabilities must be 1.0. If we modified the probability
365 // of some edges then we must distribute the introduced difference over the
366 // reachable blocks.
367 //
368 // Proportional distribution: the relation between probabilities of the
369 // reachable edges is kept unchanged. That is for any reachable edges i and j:
370 // newBP[i] / newBP[j] == oldBP[i] / oldBP[j] =>
371 // newBP[i] / oldBP[i] == newBP[j] / oldBP[j] == K
372 // Where K is independent of i,j.
373 // newBP[i] == oldBP[i] * K
374 // We need to find K.
375 // Make sum of all reachables of the left and right parts:
376 // sum_of_reachable(newBP) == K * sum_of_reachable(oldBP)
377 // Sum of newBP must be equal to 1.0:
378 // sum_of_reachable(newBP) + sum_of_unreachable(newBP) == 1.0 =>
379 // sum_of_reachable(newBP) = 1.0 - sum_of_unreachable(newBP)
380 // Where sum_of_unreachable(newBP) is what has been just changed.
381 // Finally:
382 // K == sum_of_reachable(newBP) / sum_of_reachable(oldBP) =>
383 // K == (1.0 - sum_of_unreachable(newBP)) / sum_of_reachable(oldBP)
384 BranchProbability NewUnreachableSum = BranchProbability::getZero();
385 for (auto I : UnreachableIdxs)
386 NewUnreachableSum += BP[I];
387
388 BranchProbability NewReachableSum =
389 BranchProbability::getOne() - NewUnreachableSum;
390
391 BranchProbability OldReachableSum = BranchProbability::getZero();
392 for (auto I : ReachableIdxs)
393 OldReachableSum += BP[I];
394
395 if (OldReachableSum != NewReachableSum) { // Anything to dsitribute?
396 if (OldReachableSum.isZero()) {
397 // If all oldBP[i] are zeroes then the proportional distribution results
398 // in all zero probabilities and the error stays big. In this case we
399 // evenly spread NewReachableSum over the reachable edges.
400 BranchProbability PerEdge = NewReachableSum / ReachableIdxs.size();
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700401 for (auto I : ReachableIdxs)
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700402 BP[I] = PerEdge;
403 } else {
404 for (auto I : ReachableIdxs) {
405 // We use uint64_t to avoid double rounding error of the following
406 // calculation: BP[i] = BP[i] * NewReachableSum / OldReachableSum
407 // The formula is taken from the private constructor
408 // BranchProbability(uint32_t Numerator, uint32_t Denominator)
409 uint64_t Mul = static_cast<uint64_t>(NewReachableSum.getNumerator()) *
410 BP[I].getNumerator();
411 uint32_t Div = static_cast<uint32_t>(
412 divideNearest(Mul, OldReachableSum.getNumerator()));
413 BP[I] = BranchProbability::getRaw(Div);
414 }
415 }
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000416 }
417
Yevgeny Rouban81384872020-05-21 11:49:11 +0700418 setEdgeProbability(BB, BP);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000419
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000420 return true;
421}
422
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000423/// Calculate edge weights for edges leading to cold blocks.
Diego Novilloc6399532013-05-24 12:26:52 +0000424///
425/// A cold block is one post-dominated by a block with a call to a
426/// cold function. Those edges are unlikely to be taken, so we give
427/// them relatively low weight.
428///
429/// Return true if we could compute the weights for cold edges.
430/// Return false, otherwise.
Mehdi Aminia7978772016-04-07 21:59:28 +0000431bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000432 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000433 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000434 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000435 assert(!isa<InvokeInst>(TI) &&
436 "Invokes should have already been handled by calcInvokeHeuristics");
Diego Novilloc6399532013-05-24 12:26:52 +0000437
438 // Determine which successors are post-dominated by a cold block.
439 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000440 SmallVector<unsigned, 4> NormalEdges;
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700441 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Diego Novilloc6399532013-05-24 12:26:52 +0000442 if (PostDominatedByColdCall.count(*I))
443 ColdEdges.push_back(I.getSuccessorIndex());
444 else
445 NormalEdges.push_back(I.getSuccessorIndex());
446
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000447 // Skip probabilities if no cold edges.
448 if (ColdEdges.empty())
Diego Novilloc6399532013-05-24 12:26:52 +0000449 return false;
450
Yevgeny Rouban81384872020-05-21 11:49:11 +0700451 SmallVector<BranchProbability, 4> EdgeProbabilities(
452 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000453 if (NormalEdges.empty()) {
454 BranchProbability Prob(1, ColdEdges.size());
455 for (unsigned SuccIdx : ColdEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700456 EdgeProbabilities[SuccIdx] = Prob;
457 setEdgeProbability(BB, EdgeProbabilities);
Diego Novilloc6399532013-05-24 12:26:52 +0000458 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000459 }
460
Vedant Kumara4bd1462016-12-17 01:02:08 +0000461 auto ColdProb = BranchProbability::getBranchProbability(
462 CC_TAKEN_WEIGHT,
463 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
464 auto NormalProb = BranchProbability::getBranchProbability(
465 CC_NONTAKEN_WEIGHT,
466 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
Cong Houe93b8e12015-12-22 18:56:14 +0000467
468 for (unsigned SuccIdx : ColdEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700469 EdgeProbabilities[SuccIdx] = ColdProb;
Cong Houe93b8e12015-12-22 18:56:14 +0000470 for (unsigned SuccIdx : NormalEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700471 EdgeProbabilities[SuccIdx] = NormalProb;
Diego Novilloc6399532013-05-24 12:26:52 +0000472
Yevgeny Rouban81384872020-05-21 11:49:11 +0700473 setEdgeProbability(BB, EdgeProbabilities);
Diego Novilloc6399532013-05-24 12:26:52 +0000474 return true;
475}
476
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000477// Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
Andrew Trick49371f32011-06-04 01:16:30 +0000478// between two pointer or pointer and NULL will fail.
Mehdi Aminia7978772016-04-07 21:59:28 +0000479bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
480 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Andrew Trick49371f32011-06-04 01:16:30 +0000481 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000482 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000483
484 Value *Cond = BI->getCondition();
485 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000486 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000487 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000488
489 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000490
491 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000492 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000493
Nick Lewycky75b20532011-06-04 02:07:10 +0000494 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000495
Yevgeny Rouban81384872020-05-21 11:49:11 +0700496 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
497 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
498 BranchProbability UntakenProb(PH_NONTAKEN_WEIGHT,
499 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
500
Andrew Trick49371f32011-06-04 01:16:30 +0000501 // p != 0 -> isProb = true
502 // p == 0 -> isProb = false
503 // p != q -> isProb = true
504 // p == q -> isProb = false;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000505 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000506 if (!isProb)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700507 std::swap(TakenProb, UntakenProb);
Andrew Trick49371f32011-06-04 01:16:30 +0000508
Yevgeny Rouban81384872020-05-21 11:49:11 +0700509 setEdgeProbability(
510 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb}));
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000511 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000512}
513
Geoff Berryeed65312017-11-01 15:16:50 +0000514static int getSCCNum(const BasicBlock *BB,
515 const BranchProbabilityInfo::SccInfo &SccI) {
516 auto SccIt = SccI.SccNums.find(BB);
517 if (SccIt == SccI.SccNums.end())
518 return -1;
519 return SccIt->second;
520}
521
522// Consider any block that is an entry point to the SCC as a header.
523static bool isSCCHeader(const BasicBlock *BB, int SccNum,
524 BranchProbabilityInfo::SccInfo &SccI) {
525 assert(getSCCNum(BB, SccI) == SccNum);
526
527 // Lazily compute the set of headers for a given SCC and cache the results
528 // in the SccHeaderMap.
529 if (SccI.SccHeaders.size() <= static_cast<unsigned>(SccNum))
530 SccI.SccHeaders.resize(SccNum + 1);
531 auto &HeaderMap = SccI.SccHeaders[SccNum];
532 bool Inserted;
533 BranchProbabilityInfo::SccHeaderMap::iterator HeaderMapIt;
534 std::tie(HeaderMapIt, Inserted) = HeaderMap.insert(std::make_pair(BB, false));
535 if (Inserted) {
536 bool IsHeader = llvm::any_of(make_range(pred_begin(BB), pred_end(BB)),
537 [&](const BasicBlock *Pred) {
538 return getSCCNum(Pred, SccI) != SccNum;
539 });
540 HeaderMapIt->second = IsHeader;
541 return IsHeader;
542 } else
543 return HeaderMapIt->second;
544}
545
John Brawn29bbed32018-02-23 17:17:31 +0000546// Compute the unlikely successors to the block BB in the loop L, specifically
547// those that are unlikely because this is a loop, and add them to the
548// UnlikelyBlocks set.
549static void
550computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
551 SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
552 // Sometimes in a loop we have a branch whose condition is made false by
553 // taking it. This is typically something like
554 // int n = 0;
555 // while (...) {
556 // if (++n >= MAX) {
557 // n = 0;
558 // }
559 // }
560 // In this sort of situation taking the branch means that at the very least it
561 // won't be taken again in the next iteration of the loop, so we should
562 // consider it less likely than a typical branch.
563 //
564 // We detect this by looking back through the graph of PHI nodes that sets the
565 // value that the condition depends on, and seeing if we can reach a successor
566 // block which can be determined to make the condition false.
567 //
568 // FIXME: We currently consider unlikely blocks to be half as likely as other
569 // blocks, but if we consider the example above the likelyhood is actually
570 // 1/MAX. We could therefore be more precise in how unlikely we consider
571 // blocks to be, but it would require more careful examination of the form
572 // of the comparison expression.
573 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
574 if (!BI || !BI->isConditional())
575 return;
576
577 // Check if the branch is based on an instruction compared with a constant
578 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
579 if (!CI || !isa<Instruction>(CI->getOperand(0)) ||
580 !isa<Constant>(CI->getOperand(1)))
581 return;
582
583 // Either the instruction must be a PHI, or a chain of operations involving
584 // constants that ends in a PHI which we can then collapse into a single value
585 // if the PHI value is known.
586 Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0));
587 PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
588 Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1));
589 // Collect the instructions until we hit a PHI
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000590 SmallVector<BinaryOperator *, 1> InstChain;
John Brawn29bbed32018-02-23 17:17:31 +0000591 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
592 isa<Constant>(CmpLHS->getOperand(1))) {
593 // Stop if the chain extends outside of the loop
594 if (!L->contains(CmpLHS))
595 return;
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000596 InstChain.push_back(cast<BinaryOperator>(CmpLHS));
John Brawn29bbed32018-02-23 17:17:31 +0000597 CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
598 if (CmpLHS)
599 CmpPHI = dyn_cast<PHINode>(CmpLHS);
600 }
601 if (!CmpPHI || !L->contains(CmpPHI))
602 return;
603
604 // Trace the phi node to find all values that come from successors of BB
605 SmallPtrSet<PHINode*, 8> VisitedInsts;
606 SmallVector<PHINode*, 8> WorkList;
607 WorkList.push_back(CmpPHI);
608 VisitedInsts.insert(CmpPHI);
609 while (!WorkList.empty()) {
610 PHINode *P = WorkList.back();
611 WorkList.pop_back();
612 for (BasicBlock *B : P->blocks()) {
613 // Skip blocks that aren't part of the loop
614 if (!L->contains(B))
615 continue;
616 Value *V = P->getIncomingValueForBlock(B);
617 // If the source is a PHI add it to the work list if we haven't
618 // already visited it.
619 if (PHINode *PN = dyn_cast<PHINode>(V)) {
620 if (VisitedInsts.insert(PN).second)
621 WorkList.push_back(PN);
622 continue;
623 }
624 // If this incoming value is a constant and B is a successor of BB, then
625 // we can constant-evaluate the compare to see if it makes the branch be
626 // taken or not.
627 Constant *CmpLHSConst = dyn_cast<Constant>(V);
628 if (!CmpLHSConst ||
629 std::find(succ_begin(BB), succ_end(BB), B) == succ_end(BB))
630 continue;
631 // First collapse InstChain
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000632 for (Instruction *I : llvm::reverse(InstChain)) {
John Brawn29bbed32018-02-23 17:17:31 +0000633 CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst,
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000634 cast<Constant>(I->getOperand(1)), true);
John Brawn29bbed32018-02-23 17:17:31 +0000635 if (!CmpLHSConst)
636 break;
637 }
638 if (!CmpLHSConst)
639 continue;
640 // Now constant-evaluate the compare
641 Constant *Result = ConstantExpr::getCompare(CI->getPredicate(),
642 CmpLHSConst, CmpConst, true);
643 // If the result means we don't branch to the block then that block is
644 // unlikely.
645 if (Result &&
646 ((Result->isZeroValue() && B == BI->getSuccessor(0)) ||
647 (Result->isOneValue() && B == BI->getSuccessor(1))))
648 UnlikelyBlocks.insert(B);
649 }
650 }
651}
652
Andrew Trick49371f32011-06-04 01:16:30 +0000653// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
654// as taken, exiting edges as not-taken.
Mehdi Aminia7978772016-04-07 21:59:28 +0000655bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
Geoff Berryeed65312017-11-01 15:16:50 +0000656 const LoopInfo &LI,
657 SccInfo &SccI) {
658 int SccNum;
Cong Houab23bfb2015-07-15 22:48:29 +0000659 Loop *L = LI.getLoopFor(BB);
Geoff Berryeed65312017-11-01 15:16:50 +0000660 if (!L) {
661 SccNum = getSCCNum(BB, SccI);
662 if (SccNum < 0)
663 return false;
664 }
Andrew Trick49371f32011-06-04 01:16:30 +0000665
John Brawn29bbed32018-02-23 17:17:31 +0000666 SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks;
667 if (L)
668 computeUnlikelySuccessors(BB, L, UnlikelyBlocks);
669
Manman Rencf104462012-08-24 18:14:27 +0000670 SmallVector<unsigned, 8> BackEdges;
671 SmallVector<unsigned, 8> ExitingEdges;
672 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
John Brawn29bbed32018-02-23 17:17:31 +0000673 SmallVector<unsigned, 8> UnlikelyEdges;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000674
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700675 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Geoff Berryeed65312017-11-01 15:16:50 +0000676 // Use LoopInfo if we have it, otherwise fall-back to SCC info to catch
677 // irreducible loops.
678 if (L) {
John Brawn29bbed32018-02-23 17:17:31 +0000679 if (UnlikelyBlocks.count(*I) != 0)
680 UnlikelyEdges.push_back(I.getSuccessorIndex());
681 else if (!L->contains(*I))
Geoff Berryeed65312017-11-01 15:16:50 +0000682 ExitingEdges.push_back(I.getSuccessorIndex());
683 else if (L->getHeader() == *I)
684 BackEdges.push_back(I.getSuccessorIndex());
685 else
686 InEdges.push_back(I.getSuccessorIndex());
687 } else {
688 if (getSCCNum(*I, SccI) != SccNum)
689 ExitingEdges.push_back(I.getSuccessorIndex());
690 else if (isSCCHeader(*I, SccNum, SccI))
691 BackEdges.push_back(I.getSuccessorIndex());
692 else
693 InEdges.push_back(I.getSuccessorIndex());
694 }
Andrew Trick49371f32011-06-04 01:16:30 +0000695 }
696
John Brawn29bbed32018-02-23 17:17:31 +0000697 if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty())
Akira Hatanaka5638b892014-04-14 16:56:19 +0000698 return false;
699
Cong Houe93b8e12015-12-22 18:56:14 +0000700 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
701 // normalize them so that they sum up to one.
Cong Houe93b8e12015-12-22 18:56:14 +0000702 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
703 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
John Brawn29bbed32018-02-23 17:17:31 +0000704 (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) +
Cong Houe93b8e12015-12-22 18:56:14 +0000705 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
Andrew Trick49371f32011-06-04 01:16:30 +0000706
Yevgeny Rouban81384872020-05-21 11:49:11 +0700707 SmallVector<BranchProbability, 4> EdgeProbabilities(
708 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000709 if (uint32_t numBackEdges = BackEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000710 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
711 auto Prob = TakenProb / numBackEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000712 for (unsigned SuccIdx : BackEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700713 EdgeProbabilities[SuccIdx] = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000714 }
715
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000716 if (uint32_t numInEdges = InEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000717 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
718 auto Prob = TakenProb / numInEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000719 for (unsigned SuccIdx : InEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700720 EdgeProbabilities[SuccIdx] = Prob;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000721 }
722
Chandler Carruth32f46e72011-10-25 09:47:41 +0000723 if (uint32_t numExitingEdges = ExitingEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000724 BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT,
725 Denom);
726 auto Prob = NotTakenProb / numExitingEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000727 for (unsigned SuccIdx : ExitingEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700728 EdgeProbabilities[SuccIdx] = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000729 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000730
John Brawn29bbed32018-02-23 17:17:31 +0000731 if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) {
732 BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT,
733 Denom);
734 auto Prob = UnlikelyProb / numUnlikelyEdges;
735 for (unsigned SuccIdx : UnlikelyEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700736 EdgeProbabilities[SuccIdx] = Prob;
John Brawn29bbed32018-02-23 17:17:31 +0000737 }
738
Yevgeny Rouban81384872020-05-21 11:49:11 +0700739 setEdgeProbability(BB, EdgeProbabilities);
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000740 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000741}
742
John Brawnda4a68a2017-06-08 09:44:40 +0000743bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
744 const TargetLibraryInfo *TLI) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000745 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000746 if (!BI || !BI->isConditional())
747 return false;
748
749 Value *Cond = BI->getCondition();
750 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
751 if (!CI)
752 return false;
753
Sam Parker0b53e842019-02-15 11:50:21 +0000754 auto GetConstantInt = [](Value *V) {
755 if (auto *I = dyn_cast<BitCastInst>(V))
756 return dyn_cast<ConstantInt>(I->getOperand(0));
757 return dyn_cast<ConstantInt>(V);
758 };
759
Jakub Staszak17af66a2011-07-31 03:27:24 +0000760 Value *RHS = CI->getOperand(1);
Sam Parker0b53e842019-02-15 11:50:21 +0000761 ConstantInt *CV = GetConstantInt(RHS);
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000762 if (!CV)
Jakub Staszak17af66a2011-07-31 03:27:24 +0000763 return false;
764
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000765 // If the LHS is the result of AND'ing a value with a single bit bitmask,
766 // we don't have information about probabilities.
767 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
768 if (LHS->getOpcode() == Instruction::And)
769 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
Craig Topper4e22ee62017-08-04 16:59:29 +0000770 if (AndRHS->getValue().isPowerOf2())
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000771 return false;
772
John Brawnda4a68a2017-06-08 09:44:40 +0000773 // Check if the LHS is the return value of a library function
774 LibFunc Func = NumLibFuncs;
775 if (TLI)
776 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
777 if (Function *CalledFn = Call->getCalledFunction())
778 TLI->getLibFunc(*CalledFn, Func);
779
Jakub Staszak17af66a2011-07-31 03:27:24 +0000780 bool isProb;
John Brawnda4a68a2017-06-08 09:44:40 +0000781 if (Func == LibFunc_strcasecmp ||
782 Func == LibFunc_strcmp ||
783 Func == LibFunc_strncasecmp ||
784 Func == LibFunc_strncmp ||
785 Func == LibFunc_memcmp) {
786 // strcmp and similar functions return zero, negative, or positive, if the
787 // first string is equal, less, or greater than the second. We consider it
788 // likely that the strings are not equal, so a comparison with zero is
789 // probably false, but also a comparison with any other number is also
790 // probably false given that what exactly is returned for nonzero values is
791 // not specified. Any kind of comparison other than equality we know
792 // nothing about.
793 switch (CI->getPredicate()) {
794 case CmpInst::ICMP_EQ:
795 isProb = false;
796 break;
797 case CmpInst::ICMP_NE:
798 isProb = true;
799 break;
800 default:
801 return false;
802 }
803 } else if (CV->isZero()) {
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000804 switch (CI->getPredicate()) {
805 case CmpInst::ICMP_EQ:
806 // X == 0 -> Unlikely
807 isProb = false;
808 break;
809 case CmpInst::ICMP_NE:
810 // X != 0 -> Likely
811 isProb = true;
812 break;
813 case CmpInst::ICMP_SLT:
814 // X < 0 -> Unlikely
815 isProb = false;
816 break;
817 case CmpInst::ICMP_SGT:
818 // X > 0 -> Likely
819 isProb = true;
820 break;
821 default:
822 return false;
823 }
824 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
825 // InstCombine canonicalizes X <= 0 into X < 1.
826 // X <= 0 -> Unlikely
Jakub Staszak17af66a2011-07-31 03:27:24 +0000827 isProb = false;
Craig Topper79ab6432017-07-06 18:39:47 +0000828 } else if (CV->isMinusOne()) {
Hal Finkel4d949302013-11-01 10:58:22 +0000829 switch (CI->getPredicate()) {
830 case CmpInst::ICMP_EQ:
831 // X == -1 -> Unlikely
832 isProb = false;
833 break;
834 case CmpInst::ICMP_NE:
835 // X != -1 -> Likely
836 isProb = true;
837 break;
838 case CmpInst::ICMP_SGT:
839 // InstCombine canonicalizes X >= 0 into X > -1.
840 // X >= 0 -> Likely
841 isProb = true;
842 break;
843 default:
844 return false;
845 }
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000846 } else {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000847 return false;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000848 }
Jakub Staszak17af66a2011-07-31 03:27:24 +0000849
Cong Houe93b8e12015-12-22 18:56:14 +0000850 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
851 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
Yevgeny Rouban81384872020-05-21 11:49:11 +0700852 BranchProbability UntakenProb(ZH_NONTAKEN_WEIGHT,
853 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
854 if (!isProb)
855 std::swap(TakenProb, UntakenProb);
856
857 setEdgeProbability(
858 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb}));
Jakub Staszak17af66a2011-07-31 03:27:24 +0000859 return true;
860}
861
Mehdi Aminia7978772016-04-07 21:59:28 +0000862bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
863 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000864 if (!BI || !BI->isConditional())
865 return false;
866
867 Value *Cond = BI->getCondition();
868 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000869 if (!FCmp)
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000870 return false;
871
Guozhi Weib329e072019-09-10 17:25:11 +0000872 uint32_t TakenWeight = FPH_TAKEN_WEIGHT;
873 uint32_t NontakenWeight = FPH_NONTAKEN_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000874 bool isProb;
875 if (FCmp->isEquality()) {
876 // f1 == f2 -> Unlikely
877 // f1 != f2 -> Likely
878 isProb = !FCmp->isTrueWhenEqual();
879 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
880 // !isnan -> Likely
881 isProb = true;
Guozhi Weib329e072019-09-10 17:25:11 +0000882 TakenWeight = FPH_ORD_WEIGHT;
883 NontakenWeight = FPH_UNO_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000884 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
885 // isnan -> Unlikely
886 isProb = false;
Guozhi Weib329e072019-09-10 17:25:11 +0000887 TakenWeight = FPH_ORD_WEIGHT;
888 NontakenWeight = FPH_UNO_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000889 } else {
890 return false;
891 }
892
Reid Kleckner13707572020-05-13 08:23:09 -0700893 BranchProbability TakenProb(TakenWeight, TakenWeight + NontakenWeight);
Yevgeny Rouban81384872020-05-21 11:49:11 +0700894 BranchProbability UntakenProb(NontakenWeight, TakenWeight + NontakenWeight);
895 if (!isProb)
896 std::swap(TakenProb, UntakenProb);
897
898 setEdgeProbability(
899 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb}));
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000900 return true;
901}
Jakub Staszak17af66a2011-07-31 03:27:24 +0000902
Mehdi Aminia7978772016-04-07 21:59:28 +0000903bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
904 const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000905 if (!II)
906 return false;
907
Cong Houe93b8e12015-12-22 18:56:14 +0000908 BranchProbability TakenProb(IH_TAKEN_WEIGHT,
909 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
Yevgeny Rouban81384872020-05-21 11:49:11 +0700910 setEdgeProbability(
911 BB, SmallVector<BranchProbability, 2>({TakenProb, TakenProb.getCompl()}));
Bill Wendlinge1c54262012-08-15 12:22:35 +0000912 return true;
913}
914
Pete Cooperb9d2e342015-05-28 19:43:06 +0000915void BranchProbabilityInfo::releaseMemory() {
Cong Houe93b8e12015-12-22 18:56:14 +0000916 Probs.clear();
Nikita Popovfe8abbf2020-04-07 21:21:30 +0200917 Handles.clear();
Pete Cooperb9d2e342015-05-28 19:43:06 +0000918}
919
Alina Sbirlea62a50a92020-01-15 14:02:33 -0800920bool BranchProbabilityInfo::invalidate(Function &, const PreservedAnalyses &PA,
921 FunctionAnalysisManager::Invalidator &) {
922 // Check whether the analysis, all analyses on functions, or the function's
923 // CFG have been preserved.
924 auto PAC = PA.getChecker<BranchProbabilityAnalysis>();
925 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
926 PAC.preservedSet<CFGAnalyses>());
927}
928
Cong Houab23bfb2015-07-15 22:48:29 +0000929void BranchProbabilityInfo::print(raw_ostream &OS) const {
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000930 OS << "---- Branch Probabilities ----\n";
931 // We print the probabilities from the last function the analysis ran over,
932 // or the function it is currently running over.
933 assert(LastF && "Cannot print prior to running over a function");
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000934 for (const auto &BI : *LastF) {
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700935 for (const_succ_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000936 ++SI) {
937 printEdgeProbability(OS << " ", &BI, *SI);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000938 }
939 }
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000940}
941
Jakub Staszakefd94c82011-07-29 19:30:00 +0000942bool BranchProbabilityInfo::
943isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000944 // Hot probability is at least 4/5 = 80%
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000945 // FIXME: Compare against a static "hot" BranchProbability.
946 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick49371f32011-06-04 01:16:30 +0000947}
948
Mehdi Aminia7978772016-04-07 21:59:28 +0000949const BasicBlock *
950BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
Cong Houe93b8e12015-12-22 18:56:14 +0000951 auto MaxProb = BranchProbability::getZero();
Mehdi Aminia7978772016-04-07 21:59:28 +0000952 const BasicBlock *MaxSucc = nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000953
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700954 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000955 const BasicBlock *Succ = *I;
Cong Houe93b8e12015-12-22 18:56:14 +0000956 auto Prob = getEdgeProbability(BB, Succ);
957 if (Prob > MaxProb) {
958 MaxProb = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000959 MaxSucc = Succ;
960 }
961 }
962
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000963 // Hot probability is at least 4/5 = 80%
Cong Houe93b8e12015-12-22 18:56:14 +0000964 if (MaxProb > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +0000965 return MaxSucc;
966
Craig Topper9f008862014-04-15 04:59:12 +0000967 return nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000968}
969
Cong Houe93b8e12015-12-22 18:56:14 +0000970/// Get the raw edge probability for the edge. If can't find it, return a
971/// default probability 1/N where N is the number of successors. Here an edge is
972/// specified using PredBlock and an
973/// index to the successors.
974BranchProbability
975BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
976 unsigned IndexInSuccessors) const {
977 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick49371f32011-06-04 01:16:30 +0000978
Cong Houe93b8e12015-12-22 18:56:14 +0000979 if (I != Probs.end())
Andrew Trick49371f32011-06-04 01:16:30 +0000980 return I->second;
981
Vedant Kumare0b5f862018-05-10 23:01:54 +0000982 return {1, static_cast<uint32_t>(succ_size(Src))};
Andrew Trick49371f32011-06-04 01:16:30 +0000983}
984
Cong Houd97c1002015-12-01 05:29:22 +0000985BranchProbability
986BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700987 const_succ_iterator Dst) const {
Cong Houd97c1002015-12-01 05:29:22 +0000988 return getEdgeProbability(Src, Dst.getSuccessorIndex());
989}
990
Cong Houe93b8e12015-12-22 18:56:14 +0000991/// Get the raw edge probability calculated for the block pair. This returns the
992/// sum of all raw edge probabilities from Src to Dst.
993BranchProbability
994BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
995 const BasicBlock *Dst) const {
996 auto Prob = BranchProbability::getZero();
997 bool FoundProb = false;
Evgeniy Brevnovbb0842a2020-04-29 14:08:01 +0700998 uint32_t EdgeCount = 0;
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700999 for (const_succ_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
Cong Houe93b8e12015-12-22 18:56:14 +00001000 if (*I == Dst) {
Evgeniy Brevnovbb0842a2020-04-29 14:08:01 +07001001 ++EdgeCount;
Cong Houe93b8e12015-12-22 18:56:14 +00001002 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
1003 if (MapI != Probs.end()) {
1004 FoundProb = true;
1005 Prob += MapI->second;
1006 }
1007 }
1008 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
Evgeniy Brevnovbb0842a2020-04-29 14:08:01 +07001009 return FoundProb ? Prob : BranchProbability(EdgeCount, succ_num);
Cong Houe93b8e12015-12-22 18:56:14 +00001010}
1011
1012/// Set the edge probability for a given edge specified by PredBlock and an
1013/// index to the successors.
1014void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
1015 unsigned IndexInSuccessors,
1016 BranchProbability Prob) {
1017 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001018 Handles.insert(BasicBlockCallbackVH(Src, this));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001019 LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
1020 << IndexInSuccessors << " successor probability to " << Prob
1021 << "\n");
Cong Houe93b8e12015-12-22 18:56:14 +00001022}
1023
Yevgeny Rouban81384872020-05-21 11:49:11 +07001024/// Set the edge probability for all edges at once.
1025void BranchProbabilityInfo::setEdgeProbability(
1026 const BasicBlock *Src, const SmallVectorImpl<BranchProbability> &Probs) {
1027 assert(Src->getTerminator()->getNumSuccessors() == Probs.size());
1028 if (Probs.size() == 0)
1029 return; // Nothing to set.
1030
1031 uint64_t TotalNumerator = 0;
1032 for (unsigned SuccIdx = 0; SuccIdx < Probs.size(); ++SuccIdx) {
1033 setEdgeProbability(Src, SuccIdx, Probs[SuccIdx]);
1034 TotalNumerator += Probs[SuccIdx].getNumerator();
1035 }
1036
1037 // Because of rounding errors the total probability cannot be checked to be
1038 // 1.0 exactly. That is TotalNumerator == BranchProbability::getDenominator.
1039 // Instead, every single probability in Probs must be as accurate as possible.
1040 // This results in error 1/denominator at most, thus the total absolute error
1041 // should be within Probs.size / BranchProbability::getDenominator.
1042 assert(TotalNumerator <= BranchProbability::getDenominator() + Probs.size());
1043 assert(TotalNumerator >= BranchProbability::getDenominator() - Probs.size());
1044}
1045
Andrew Trick49371f32011-06-04 01:16:30 +00001046raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +00001047BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
1048 const BasicBlock *Src,
1049 const BasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001050 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +00001051 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +00001052 << " probability is " << Prob
1053 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +00001054
1055 return OS;
1056}
Cong Houab23bfb2015-07-15 22:48:29 +00001057
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001058void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
1059 for (auto I = Probs.begin(), E = Probs.end(); I != E; ++I) {
1060 auto Key = I->first;
1061 if (Key.first == BB)
1062 Probs.erase(Key);
1063 }
1064}
1065
John Brawnda4a68a2017-06-08 09:44:40 +00001066void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001067 const TargetLibraryInfo *TLI,
1068 PostDominatorTree *PDT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001069 LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
1070 << " ----\n\n");
Cong Houab23bfb2015-07-15 22:48:29 +00001071 LastF = &F; // Store the last function we ran on for printing.
1072 assert(PostDominatedByUnreachable.empty());
1073 assert(PostDominatedByColdCall.empty());
1074
Geoff Berryeed65312017-11-01 15:16:50 +00001075 // Record SCC numbers of blocks in the CFG to identify irreducible loops.
1076 // FIXME: We could only calculate this if the CFG is known to be irreducible
1077 // (perhaps cache this info in LoopInfo if we can easily calculate it there?).
1078 int SccNum = 0;
1079 SccInfo SccI;
1080 for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd();
1081 ++It, ++SccNum) {
1082 // Ignore single-block SCCs since they either aren't loops or LoopInfo will
1083 // catch them.
1084 const std::vector<const BasicBlock *> &Scc = *It;
1085 if (Scc.size() == 1)
1086 continue;
1087
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001088 LLVM_DEBUG(dbgs() << "BPI: SCC " << SccNum << ":");
Geoff Berryeed65312017-11-01 15:16:50 +00001089 for (auto *BB : Scc) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001090 LLVM_DEBUG(dbgs() << " " << BB->getName());
Geoff Berryeed65312017-11-01 15:16:50 +00001091 SccI.SccNums[BB] = SccNum;
1092 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001093 LLVM_DEBUG(dbgs() << "\n");
Geoff Berryeed65312017-11-01 15:16:50 +00001094 }
1095
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001096 std::unique_ptr<PostDominatorTree> PDTPtr;
1097
1098 if (!PDT) {
1099 PDTPtr = std::make_unique<PostDominatorTree>(const_cast<Function &>(F));
1100 PDT = PDTPtr.get();
1101 }
1102
1103 computePostDominatedByUnreachable(F, PDT);
1104 computePostDominatedByColdCall(F, PDT);
Taewook Oh2da205d2019-12-02 10:15:22 -08001105
Cong Houab23bfb2015-07-15 22:48:29 +00001106 // Walk the basic blocks in post-order so that we can build up state about
1107 // the successors of a block iteratively.
1108 for (auto BB : post_order(&F.getEntryBlock())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001109 LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName()
1110 << "\n");
Serguei Katkov11d9c4f2017-04-17 06:39:47 +00001111 // If there is no at least two successors, no sense to set probability.
1112 if (BB->getTerminator()->getNumSuccessors() < 2)
1113 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001114 if (calcMetadataWeights(BB))
1115 continue;
Artur Pilipenko4d063e72018-06-08 13:03:21 +00001116 if (calcInvokeHeuristics(BB))
1117 continue;
Serguei Katkov2616bbb2017-04-17 04:33:04 +00001118 if (calcUnreachableHeuristics(BB))
1119 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001120 if (calcColdCallHeuristics(BB))
1121 continue;
Geoff Berryeed65312017-11-01 15:16:50 +00001122 if (calcLoopBranchHeuristics(BB, LI, SccI))
Cong Houab23bfb2015-07-15 22:48:29 +00001123 continue;
1124 if (calcPointerHeuristics(BB))
1125 continue;
John Brawnda4a68a2017-06-08 09:44:40 +00001126 if (calcZeroHeuristics(BB, TLI))
Cong Houab23bfb2015-07-15 22:48:29 +00001127 continue;
1128 if (calcFloatingPointHeuristics(BB))
1129 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001130 }
1131
1132 PostDominatedByUnreachable.clear();
1133 PostDominatedByColdCall.clear();
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +00001134
1135 if (PrintBranchProb &&
1136 (PrintBranchProbFuncName.empty() ||
1137 F.getName().equals(PrintBranchProbFuncName))) {
1138 print(dbgs());
1139 }
Cong Houab23bfb2015-07-15 22:48:29 +00001140}
1141
1142void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
1143 AnalysisUsage &AU) const {
Mikael Holmen2ca16892018-05-17 09:05:40 +00001144 // We require DT so it's available when LI is available. The LI updating code
1145 // asserts that DT is also present so if we don't make sure that we have DT
1146 // here, that assert will trigger.
1147 AU.addRequired<DominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001148 AU.addRequired<LoopInfoWrapperPass>();
John Brawnda4a68a2017-06-08 09:44:40 +00001149 AU.addRequired<TargetLibraryInfoWrapperPass>();
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001150 AU.addRequired<PostDominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001151 AU.setPreservesAll();
1152}
1153
1154bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
1155 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnson9c27b592019-09-07 03:09:36 +00001156 const TargetLibraryInfo &TLI =
1157 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001158 PostDominatorTree &PDT =
1159 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
1160 BPI.calculate(F, LI, &TLI, &PDT);
Cong Houab23bfb2015-07-15 22:48:29 +00001161 return false;
1162}
1163
1164void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
1165
1166void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
1167 const Module *) const {
1168 BPI.print(OS);
1169}
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001170
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001171AnalysisKey BranchProbabilityAnalysis::Key;
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001172BranchProbabilityInfo
Sean Silva36e0d012016-08-09 00:28:15 +00001173BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001174 BranchProbabilityInfo BPI;
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001175 BPI.calculate(F, AM.getResult<LoopAnalysis>(F),
1176 &AM.getResult<TargetLibraryAnalysis>(F),
1177 &AM.getResult<PostDominatorTreeAnalysis>(F));
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001178 return BPI;
1179}
1180
1181PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +00001182BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001183 OS << "Printing analysis results of BPI for function "
1184 << "'" << F.getName() << "':"
1185 << "\n";
1186 AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
1187 return PreservedAnalyses::all();
1188}