blob: ac5dbe1ce6e94fe371f6e3381b0040467f292915 [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
Dávid Bolvanský0f14b2e2020-08-17 20:42:57 +0200125static 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
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +0700151BranchProbabilityInfo::SccInfo::SccInfo(const Function &F) {
152 // Record SCC numbers of blocks in the CFG to identify irreducible loops.
153 // FIXME: We could only calculate this if the CFG is known to be irreducible
154 // (perhaps cache this info in LoopInfo if we can easily calculate it there?).
155 int SccNum = 0;
156 for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd();
157 ++It, ++SccNum) {
158 // Ignore single-block SCCs since they either aren't loops or LoopInfo will
159 // catch them.
160 const std::vector<const BasicBlock *> &Scc = *It;
161 if (Scc.size() == 1)
162 continue;
163
164 LLVM_DEBUG(dbgs() << "BPI: SCC " << SccNum << ":");
165 for (const auto *BB : Scc) {
166 LLVM_DEBUG(dbgs() << " " << BB->getName());
167 SccNums[BB] = SccNum;
168 calculateSccBlockType(BB, SccNum);
169 }
170 LLVM_DEBUG(dbgs() << "\n");
171 }
172}
173
174int BranchProbabilityInfo::SccInfo::getSCCNum(const BasicBlock *BB) const {
175 auto SccIt = SccNums.find(BB);
176 if (SccIt == SccNums.end())
177 return -1;
178 return SccIt->second;
179}
180
181void BranchProbabilityInfo::SccInfo::getSccEnterBlocks(
182 int SccNum, SmallVectorImpl<BasicBlock *> &Enters) const {
183
184 for (auto MapIt : SccBlocks[SccNum]) {
185 const auto *BB = MapIt.first;
186 if (isSCCHeader(BB, SccNum))
187 for (const auto *Pred : predecessors(BB))
188 if (getSCCNum(Pred) != SccNum)
189 Enters.push_back(const_cast<BasicBlock *>(BB));
190 }
191}
192
193void BranchProbabilityInfo::SccInfo::getSccExitBlocks(
194 int SccNum, SmallVectorImpl<BasicBlock *> &Exits) const {
195 for (auto MapIt : SccBlocks[SccNum]) {
196 const auto *BB = MapIt.first;
197 if (isSCCExitingBlock(BB, SccNum))
198 for (const auto *Succ : successors(BB))
199 if (getSCCNum(Succ) != SccNum)
200 Exits.push_back(const_cast<BasicBlock *>(BB));
201 }
202}
203
204uint32_t BranchProbabilityInfo::SccInfo::getSccBlockType(const BasicBlock *BB,
205 int SccNum) const {
206 assert(getSCCNum(BB) == SccNum);
207
208 assert(SccBlocks.size() > static_cast<unsigned>(SccNum) && "Unknown SCC");
209 const auto &SccBlockTypes = SccBlocks[SccNum];
210
211 auto It = SccBlockTypes.find(BB);
212 if (It != SccBlockTypes.end()) {
213 return It->second;
214 }
215 return Inner;
216}
217
218void BranchProbabilityInfo::SccInfo::calculateSccBlockType(const BasicBlock *BB,
219 int SccNum) {
220 assert(getSCCNum(BB) == SccNum);
221 uint32_t BlockType = Inner;
222
Kazu Hiratac5cc2d82020-11-15 19:26:38 -0800223 if (llvm::any_of(predecessors(BB), [&](const BasicBlock *Pred) {
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +0700224 // Consider any block that is an entry point to the SCC as
225 // a header.
226 return getSCCNum(Pred) != SccNum;
227 }))
228 BlockType |= Header;
229
Kazu Hiratac5cc2d82020-11-15 19:26:38 -0800230 if (llvm::any_of(successors(BB), [&](const BasicBlock *Succ) {
231 return getSCCNum(Succ) != SccNum;
232 }))
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +0700233 BlockType |= Exiting;
234
235 // Lazily compute the set of headers for a given SCC and cache the results
236 // in the SccHeaderMap.
237 if (SccBlocks.size() <= static_cast<unsigned>(SccNum))
238 SccBlocks.resize(SccNum + 1);
239 auto &SccBlockTypes = SccBlocks[SccNum];
240
241 if (BlockType != Inner) {
242 bool IsInserted;
243 std::tie(std::ignore, IsInserted) =
244 SccBlockTypes.insert(std::make_pair(BB, BlockType));
245 assert(IsInserted && "Duplicated block in SCC");
246 }
247}
248
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700249BranchProbabilityInfo::LoopBlock::LoopBlock(const BasicBlock *BB,
250 const LoopInfo &LI,
251 const SccInfo &SccI)
252 : BB(BB) {
253 LD.first = LI.getLoopFor(BB);
254 if (!LD.first) {
255 LD.second = SccI.getSCCNum(BB);
256 }
257}
258
259bool BranchProbabilityInfo::isLoopEnteringEdge(const LoopEdge &Edge) const {
260 const auto &SrcBlock = Edge.first;
261 const auto &DstBlock = Edge.second;
262 return (DstBlock.getLoop() &&
263 !DstBlock.getLoop()->contains(SrcBlock.getLoop())) ||
264 // Assume that SCCs can't be nested.
265 (DstBlock.getSccNum() != -1 &&
266 SrcBlock.getSccNum() != DstBlock.getSccNum());
267}
268
269bool BranchProbabilityInfo::isLoopExitingEdge(const LoopEdge &Edge) const {
270 return isLoopEnteringEdge({Edge.second, Edge.first});
271}
272
273bool BranchProbabilityInfo::isLoopEnteringExitingEdge(
274 const LoopEdge &Edge) const {
275 return isLoopEnteringEdge(Edge) || isLoopExitingEdge(Edge);
276}
277
278bool BranchProbabilityInfo::isLoopBackEdge(const LoopEdge &Edge) const {
279 const auto &SrcBlock = Edge.first;
280 const auto &DstBlock = Edge.second;
281 return SrcBlock.belongsToSameLoop(DstBlock) &&
282 ((DstBlock.getLoop() &&
283 DstBlock.getLoop()->getHeader() == DstBlock.getBlock()) ||
284 (DstBlock.getSccNum() != -1 &&
285 SccI->isSCCHeader(DstBlock.getBlock(), DstBlock.getSccNum())));
286}
287
288void BranchProbabilityInfo::getLoopEnterBlocks(
289 const LoopBlock &LB, SmallVectorImpl<BasicBlock *> &Enters) const {
290 if (LB.getLoop()) {
291 auto *Header = LB.getLoop()->getHeader();
292 Enters.append(pred_begin(Header), pred_end(Header));
293 } else {
294 assert(LB.getSccNum() != -1 && "LB doesn't belong to any loop?");
295 SccI->getSccEnterBlocks(LB.getSccNum(), Enters);
296 }
297}
298
299void BranchProbabilityInfo::getLoopExitBlocks(
300 const LoopBlock &LB, SmallVectorImpl<BasicBlock *> &Exits) const {
301 if (LB.getLoop()) {
302 LB.getLoop()->getExitBlocks(Exits);
303 } else {
304 assert(LB.getSccNum() != -1 && "LB doesn't belong to any loop?");
305 SccI->getSccExitBlocks(LB.getSccNum(), Exits);
306 }
307}
308
Taewook Oh2da205d2019-12-02 10:15:22 -0800309static void UpdatePDTWorklist(const BasicBlock *BB, PostDominatorTree *PDT,
310 SmallVectorImpl<const BasicBlock *> &WorkList,
311 SmallPtrSetImpl<const BasicBlock *> &TargetSet) {
312 SmallVector<BasicBlock *, 8> Descendants;
313 SmallPtrSet<const BasicBlock *, 16> NewItems;
Chandler Carruth7111f452011-10-24 12:01:08 +0000314
Taewook Oh2da205d2019-12-02 10:15:22 -0800315 PDT->getDescendants(const_cast<BasicBlock *>(BB), Descendants);
316 for (auto *BB : Descendants)
317 if (TargetSet.insert(BB).second)
318 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
319 if (!TargetSet.count(*PI))
320 NewItems.insert(*PI);
321 WorkList.insert(WorkList.end(), NewItems.begin(), NewItems.end());
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000322}
323
Taewook Oh2da205d2019-12-02 10:15:22 -0800324/// Compute a set of basic blocks that are post-dominated by unreachables.
325void BranchProbabilityInfo::computePostDominatedByUnreachable(
326 const Function &F, PostDominatorTree *PDT) {
327 SmallVector<const BasicBlock *, 8> WorkList;
328 for (auto &BB : F) {
329 const Instruction *TI = BB.getTerminator();
330 if (TI->getNumSuccessors() == 0) {
331 if (isa<UnreachableInst>(TI) ||
332 // If this block is terminated by a call to
333 // @llvm.experimental.deoptimize then treat it like an unreachable
334 // since the @llvm.experimental.deoptimize call is expected to
335 // practically never execute.
336 BB.getTerminatingDeoptimizeCall())
337 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByUnreachable);
338 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000339 }
340
Taewook Oh2da205d2019-12-02 10:15:22 -0800341 while (!WorkList.empty()) {
342 const BasicBlock *BB = WorkList.pop_back_val();
343 if (PostDominatedByUnreachable.count(BB))
344 continue;
345 // If the terminator is an InvokeInst, check only the normal destination
346 // block as the unwind edge of InvokeInst is also very unlikely taken.
347 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
348 if (PostDominatedByUnreachable.count(II->getNormalDest()))
349 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000350 }
Taewook Oh2da205d2019-12-02 10:15:22 -0800351 // If all the successors are unreachable, BB is unreachable as well.
352 else if (!successors(BB).empty() &&
353 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
354 return PostDominatedByUnreachable.count(Succ);
355 }))
356 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
357 }
358}
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000359
Taewook Oh2da205d2019-12-02 10:15:22 -0800360/// compute a set of basic blocks that are post-dominated by ColdCalls.
361void BranchProbabilityInfo::computePostDominatedByColdCall(
362 const Function &F, PostDominatorTree *PDT) {
363 SmallVector<const BasicBlock *, 8> WorkList;
364 for (auto &BB : F)
365 for (auto &I : BB)
366 if (const CallInst *CI = dyn_cast<CallInst>(&I))
367 if (CI->hasFnAttr(Attribute::Cold))
368 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByColdCall);
369
370 while (!WorkList.empty()) {
371 const BasicBlock *BB = WorkList.pop_back_val();
372
373 // If the terminator is an InvokeInst, check only the normal destination
374 // block as the unwind edge of InvokeInst is also very unlikely taken.
375 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
376 if (PostDominatedByColdCall.count(II->getNormalDest()))
377 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
378 }
379 // If all of successor are post dominated then BB is also done.
380 else if (!successors(BB).empty() &&
381 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
382 return PostDominatedByColdCall.count(Succ);
383 }))
384 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
385 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000386}
387
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000388/// Calculate edge weights for successors lead to unreachable.
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000389///
390/// Predict that a successor which leads necessarily to an
391/// unreachable-terminated block as extremely unlikely.
392bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000393 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000394 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000395 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000396 assert(!isa<InvokeInst>(TI) &&
397 "Invokes should have already been handled by calcInvokeHeuristics");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000398
Manman Rencf104462012-08-24 18:14:27 +0000399 SmallVector<unsigned, 4> UnreachableEdges;
400 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000401
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700402 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Chandler Carruth7111f452011-10-24 12:01:08 +0000403 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000404 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000405 else
Manman Rencf104462012-08-24 18:14:27 +0000406 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000407
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000408 // Skip probabilities if all were reachable.
409 if (UnreachableEdges.empty())
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000410 return false;
Jun Bum Lima23e5f72015-12-21 22:00:51 +0000411
Yevgeny Rouban81384872020-05-21 11:49:11 +0700412 SmallVector<BranchProbability, 4> EdgeProbabilities(
413 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000414 if (ReachableEdges.empty()) {
415 BranchProbability Prob(1, UnreachableEdges.size());
416 for (unsigned SuccIdx : UnreachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700417 EdgeProbabilities[SuccIdx] = Prob;
418 setEdgeProbability(BB, EdgeProbabilities);
Chandler Carruth7111f452011-10-24 12:01:08 +0000419 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000420 }
421
Serguei Katkovba831f72017-05-18 06:11:56 +0000422 auto UnreachableProb = UR_TAKEN_PROB;
423 auto ReachableProb =
424 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
425 ReachableEdges.size();
Cong Houe93b8e12015-12-22 18:56:14 +0000426
427 for (unsigned SuccIdx : UnreachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700428 EdgeProbabilities[SuccIdx] = UnreachableProb;
Cong Houe93b8e12015-12-22 18:56:14 +0000429 for (unsigned SuccIdx : ReachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700430 EdgeProbabilities[SuccIdx] = ReachableProb;
Chandler Carruth7111f452011-10-24 12:01:08 +0000431
Yevgeny Rouban81384872020-05-21 11:49:11 +0700432 setEdgeProbability(BB, EdgeProbabilities);
Chandler Carruth7111f452011-10-24 12:01:08 +0000433 return true;
434}
435
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000436// Propagate existing explicit probabilities from either profile data or
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000437// 'expect' intrinsic processing. Examine metadata against unreachable
438// heuristic. The probability of the edge coming to unreachable block is
439// set to min of metadata and unreachable heuristic.
Mehdi Aminia7978772016-04-07 21:59:28 +0000440bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000441 const Instruction *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000442 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Yevgeny Roubandcfa78a2020-06-04 15:34:14 +0700443 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI) ||
444 isa<InvokeInst>(TI)))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000445 return false;
446
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000447 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000448 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000449 return false;
450
Diego Novillode5b8012015-05-07 17:22:06 +0000451 // Check that the number of successors is manageable.
452 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
453
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000454 // Ensure there are weights for all of the successors. Note that the first
455 // operand to the metadata node is a name, not a weight.
456 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000457 return false;
458
Diego Novillode5b8012015-05-07 17:22:06 +0000459 // Build up the final weights that will be used in a temporary buffer.
Arthur Eubanks5c31b8b2020-10-31 00:15:46 -0700460 // Compute the sum of all weights to later decide whether they need to
461 // be scaled to fit in 32 bits.
462 uint64_t WeightSum = 0;
463 SmallVector<uint32_t, 2> Weights;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000464 SmallVector<unsigned, 2> UnreachableIdxs;
465 SmallVector<unsigned, 2> ReachableIdxs;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000466 Weights.reserve(TI->getNumSuccessors());
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700467 for (unsigned I = 1, E = WeightsNode->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000468 ConstantInt *Weight =
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700469 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(I));
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000470 if (!Weight)
471 return false;
Arthur Eubanks5c31b8b2020-10-31 00:15:46 -0700472 assert(Weight->getValue().getActiveBits() <= 32 &&
473 "Too many bits for uint32_t");
474 Weights.push_back(Weight->getZExtValue());
475 WeightSum += Weights.back();
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700476 if (PostDominatedByUnreachable.count(TI->getSuccessor(I - 1)))
477 UnreachableIdxs.push_back(I - 1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000478 else
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700479 ReachableIdxs.push_back(I - 1);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000480 }
481 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
Diego Novillode5b8012015-05-07 17:22:06 +0000482
Arthur Eubanks5c31b8b2020-10-31 00:15:46 -0700483 // If the sum of weights does not fit in 32 bits, scale every weight down
484 // accordingly.
485 uint64_t ScalingFactor =
486 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
487
488 if (ScalingFactor > 1) {
489 WeightSum = 0;
490 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
491 Weights[I] /= ScalingFactor;
492 WeightSum += Weights[I];
493 }
494 }
495 assert(WeightSum <= UINT32_MAX &&
496 "Expected weights to scale down to 32 bits");
Cong Hou6a2c71a2015-12-22 23:45:55 +0000497
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000498 if (WeightSum == 0 || ReachableIdxs.size() == 0) {
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700499 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I)
500 Weights[I] = 1;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000501 WeightSum = TI->getNumSuccessors();
Cong Hou6a2c71a2015-12-22 23:45:55 +0000502 }
Cong Houe93b8e12015-12-22 18:56:14 +0000503
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000504 // Set the probability.
505 SmallVector<BranchProbability, 2> BP;
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700506 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I)
Arthur Eubanks5c31b8b2020-10-31 00:15:46 -0700507 BP.push_back({ Weights[I], static_cast<uint32_t>(WeightSum) });
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000508
509 // Examine the metadata against unreachable heuristic.
510 // If the unreachable heuristic is more strong then we use it for this edge.
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700511 if (UnreachableIdxs.size() == 0 || ReachableIdxs.size() == 0) {
512 setEdgeProbability(BB, BP);
513 return true;
514 }
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000515
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700516 auto UnreachableProb = UR_TAKEN_PROB;
517 for (auto I : UnreachableIdxs)
518 if (UnreachableProb < BP[I]) {
519 BP[I] = UnreachableProb;
520 }
Yevgeny Rouban81384872020-05-21 11:49:11 +0700521
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700522 // Sum of all edge probabilities must be 1.0. If we modified the probability
523 // of some edges then we must distribute the introduced difference over the
524 // reachable blocks.
525 //
526 // Proportional distribution: the relation between probabilities of the
527 // reachable edges is kept unchanged. That is for any reachable edges i and j:
528 // newBP[i] / newBP[j] == oldBP[i] / oldBP[j] =>
529 // newBP[i] / oldBP[i] == newBP[j] / oldBP[j] == K
530 // Where K is independent of i,j.
531 // newBP[i] == oldBP[i] * K
532 // We need to find K.
533 // Make sum of all reachables of the left and right parts:
534 // sum_of_reachable(newBP) == K * sum_of_reachable(oldBP)
535 // Sum of newBP must be equal to 1.0:
536 // sum_of_reachable(newBP) + sum_of_unreachable(newBP) == 1.0 =>
537 // sum_of_reachable(newBP) = 1.0 - sum_of_unreachable(newBP)
538 // Where sum_of_unreachable(newBP) is what has been just changed.
539 // Finally:
540 // K == sum_of_reachable(newBP) / sum_of_reachable(oldBP) =>
541 // K == (1.0 - sum_of_unreachable(newBP)) / sum_of_reachable(oldBP)
542 BranchProbability NewUnreachableSum = BranchProbability::getZero();
543 for (auto I : UnreachableIdxs)
544 NewUnreachableSum += BP[I];
545
546 BranchProbability NewReachableSum =
547 BranchProbability::getOne() - NewUnreachableSum;
548
549 BranchProbability OldReachableSum = BranchProbability::getZero();
550 for (auto I : ReachableIdxs)
551 OldReachableSum += BP[I];
552
553 if (OldReachableSum != NewReachableSum) { // Anything to dsitribute?
554 if (OldReachableSum.isZero()) {
555 // If all oldBP[i] are zeroes then the proportional distribution results
556 // in all zero probabilities and the error stays big. In this case we
557 // evenly spread NewReachableSum over the reachable edges.
558 BranchProbability PerEdge = NewReachableSum / ReachableIdxs.size();
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700559 for (auto I : ReachableIdxs)
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700560 BP[I] = PerEdge;
561 } else {
562 for (auto I : ReachableIdxs) {
563 // We use uint64_t to avoid double rounding error of the following
564 // calculation: BP[i] = BP[i] * NewReachableSum / OldReachableSum
565 // The formula is taken from the private constructor
566 // BranchProbability(uint32_t Numerator, uint32_t Denominator)
567 uint64_t Mul = static_cast<uint64_t>(NewReachableSum.getNumerator()) *
568 BP[I].getNumerator();
569 uint32_t Div = static_cast<uint32_t>(
570 divideNearest(Mul, OldReachableSum.getNumerator()));
571 BP[I] = BranchProbability::getRaw(Div);
572 }
573 }
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000574 }
575
Yevgeny Rouban81384872020-05-21 11:49:11 +0700576 setEdgeProbability(BB, BP);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000577
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000578 return true;
579}
580
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000581/// Calculate edge weights for edges leading to cold blocks.
Diego Novilloc6399532013-05-24 12:26:52 +0000582///
583/// A cold block is one post-dominated by a block with a call to a
584/// cold function. Those edges are unlikely to be taken, so we give
585/// them relatively low weight.
586///
587/// Return true if we could compute the weights for cold edges.
588/// Return false, otherwise.
Mehdi Aminia7978772016-04-07 21:59:28 +0000589bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000590 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000591 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000592 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000593 assert(!isa<InvokeInst>(TI) &&
594 "Invokes should have already been handled by calcInvokeHeuristics");
Diego Novilloc6399532013-05-24 12:26:52 +0000595
596 // Determine which successors are post-dominated by a cold block.
597 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000598 SmallVector<unsigned, 4> NormalEdges;
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700599 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Diego Novilloc6399532013-05-24 12:26:52 +0000600 if (PostDominatedByColdCall.count(*I))
601 ColdEdges.push_back(I.getSuccessorIndex());
602 else
603 NormalEdges.push_back(I.getSuccessorIndex());
604
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000605 // Skip probabilities if no cold edges.
606 if (ColdEdges.empty())
Diego Novilloc6399532013-05-24 12:26:52 +0000607 return false;
608
Yevgeny Rouban81384872020-05-21 11:49:11 +0700609 SmallVector<BranchProbability, 4> EdgeProbabilities(
610 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000611 if (NormalEdges.empty()) {
612 BranchProbability Prob(1, ColdEdges.size());
613 for (unsigned SuccIdx : ColdEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700614 EdgeProbabilities[SuccIdx] = Prob;
615 setEdgeProbability(BB, EdgeProbabilities);
Diego Novilloc6399532013-05-24 12:26:52 +0000616 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000617 }
618
Vedant Kumara4bd1462016-12-17 01:02:08 +0000619 auto ColdProb = BranchProbability::getBranchProbability(
620 CC_TAKEN_WEIGHT,
621 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
622 auto NormalProb = BranchProbability::getBranchProbability(
623 CC_NONTAKEN_WEIGHT,
624 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
Cong Houe93b8e12015-12-22 18:56:14 +0000625
626 for (unsigned SuccIdx : ColdEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700627 EdgeProbabilities[SuccIdx] = ColdProb;
Cong Houe93b8e12015-12-22 18:56:14 +0000628 for (unsigned SuccIdx : NormalEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700629 EdgeProbabilities[SuccIdx] = NormalProb;
Diego Novilloc6399532013-05-24 12:26:52 +0000630
Yevgeny Rouban81384872020-05-21 11:49:11 +0700631 setEdgeProbability(BB, EdgeProbabilities);
Diego Novilloc6399532013-05-24 12:26:52 +0000632 return true;
633}
634
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000635// Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
Andrew Trick49371f32011-06-04 01:16:30 +0000636// between two pointer or pointer and NULL will fail.
Mehdi Aminia7978772016-04-07 21:59:28 +0000637bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
638 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Andrew Trick49371f32011-06-04 01:16:30 +0000639 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000640 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000641
642 Value *Cond = BI->getCondition();
643 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000644 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000645 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000646
647 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000648
649 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000650 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000651
Nick Lewycky75b20532011-06-04 02:07:10 +0000652 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000653
Yevgeny Rouban81384872020-05-21 11:49:11 +0700654 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
655 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
656 BranchProbability UntakenProb(PH_NONTAKEN_WEIGHT,
657 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
658
Andrew Trick49371f32011-06-04 01:16:30 +0000659 // p != 0 -> isProb = true
660 // p == 0 -> isProb = false
661 // p != q -> isProb = true
662 // p == q -> isProb = false;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000663 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000664 if (!isProb)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700665 std::swap(TakenProb, UntakenProb);
Andrew Trick49371f32011-06-04 01:16:30 +0000666
Yevgeny Rouban81384872020-05-21 11:49:11 +0700667 setEdgeProbability(
668 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb}));
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000669 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000670}
671
John Brawn29bbed32018-02-23 17:17:31 +0000672// Compute the unlikely successors to the block BB in the loop L, specifically
673// those that are unlikely because this is a loop, and add them to the
674// UnlikelyBlocks set.
675static void
676computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
677 SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
678 // Sometimes in a loop we have a branch whose condition is made false by
679 // taking it. This is typically something like
680 // int n = 0;
681 // while (...) {
682 // if (++n >= MAX) {
683 // n = 0;
684 // }
685 // }
686 // In this sort of situation taking the branch means that at the very least it
687 // won't be taken again in the next iteration of the loop, so we should
688 // consider it less likely than a typical branch.
689 //
690 // We detect this by looking back through the graph of PHI nodes that sets the
691 // value that the condition depends on, and seeing if we can reach a successor
692 // block which can be determined to make the condition false.
693 //
694 // FIXME: We currently consider unlikely blocks to be half as likely as other
695 // blocks, but if we consider the example above the likelyhood is actually
696 // 1/MAX. We could therefore be more precise in how unlikely we consider
697 // blocks to be, but it would require more careful examination of the form
698 // of the comparison expression.
699 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
700 if (!BI || !BI->isConditional())
701 return;
702
703 // Check if the branch is based on an instruction compared with a constant
704 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
705 if (!CI || !isa<Instruction>(CI->getOperand(0)) ||
706 !isa<Constant>(CI->getOperand(1)))
707 return;
708
709 // Either the instruction must be a PHI, or a chain of operations involving
710 // constants that ends in a PHI which we can then collapse into a single value
711 // if the PHI value is known.
712 Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0));
713 PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
714 Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1));
715 // Collect the instructions until we hit a PHI
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000716 SmallVector<BinaryOperator *, 1> InstChain;
John Brawn29bbed32018-02-23 17:17:31 +0000717 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
718 isa<Constant>(CmpLHS->getOperand(1))) {
719 // Stop if the chain extends outside of the loop
720 if (!L->contains(CmpLHS))
721 return;
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000722 InstChain.push_back(cast<BinaryOperator>(CmpLHS));
John Brawn29bbed32018-02-23 17:17:31 +0000723 CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
724 if (CmpLHS)
725 CmpPHI = dyn_cast<PHINode>(CmpLHS);
726 }
727 if (!CmpPHI || !L->contains(CmpPHI))
728 return;
729
730 // Trace the phi node to find all values that come from successors of BB
731 SmallPtrSet<PHINode*, 8> VisitedInsts;
732 SmallVector<PHINode*, 8> WorkList;
733 WorkList.push_back(CmpPHI);
734 VisitedInsts.insert(CmpPHI);
735 while (!WorkList.empty()) {
736 PHINode *P = WorkList.back();
737 WorkList.pop_back();
738 for (BasicBlock *B : P->blocks()) {
739 // Skip blocks that aren't part of the loop
740 if (!L->contains(B))
741 continue;
742 Value *V = P->getIncomingValueForBlock(B);
743 // If the source is a PHI add it to the work list if we haven't
744 // already visited it.
745 if (PHINode *PN = dyn_cast<PHINode>(V)) {
746 if (VisitedInsts.insert(PN).second)
747 WorkList.push_back(PN);
748 continue;
749 }
750 // If this incoming value is a constant and B is a successor of BB, then
751 // we can constant-evaluate the compare to see if it makes the branch be
752 // taken or not.
753 Constant *CmpLHSConst = dyn_cast<Constant>(V);
Kazu Hirata60434982020-08-01 21:49:38 -0700754 if (!CmpLHSConst || !llvm::is_contained(successors(BB), B))
John Brawn29bbed32018-02-23 17:17:31 +0000755 continue;
756 // First collapse InstChain
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000757 for (Instruction *I : llvm::reverse(InstChain)) {
John Brawn29bbed32018-02-23 17:17:31 +0000758 CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst,
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000759 cast<Constant>(I->getOperand(1)), true);
John Brawn29bbed32018-02-23 17:17:31 +0000760 if (!CmpLHSConst)
761 break;
762 }
763 if (!CmpLHSConst)
764 continue;
765 // Now constant-evaluate the compare
766 Constant *Result = ConstantExpr::getCompare(CI->getPredicate(),
767 CmpLHSConst, CmpConst, true);
768 // If the result means we don't branch to the block then that block is
769 // unlikely.
770 if (Result &&
771 ((Result->isZeroValue() && B == BI->getSuccessor(0)) ||
772 (Result->isOneValue() && B == BI->getSuccessor(1))))
773 UnlikelyBlocks.insert(B);
774 }
775 }
776}
777
Andrew Trick49371f32011-06-04 01:16:30 +0000778// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
779// as taken, exiting edges as not-taken.
Mehdi Aminia7978772016-04-07 21:59:28 +0000780bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +0700781 const LoopInfo &LI) {
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700782 LoopBlock LB(BB, LI, *SccI.get());
783 if (!LB.belongsToLoop())
784 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000785
John Brawn29bbed32018-02-23 17:17:31 +0000786 SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks;
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700787 if (LB.getLoop())
788 computeUnlikelySuccessors(BB, LB.getLoop(), UnlikelyBlocks);
John Brawn29bbed32018-02-23 17:17:31 +0000789
Manman Rencf104462012-08-24 18:14:27 +0000790 SmallVector<unsigned, 8> BackEdges;
791 SmallVector<unsigned, 8> ExitingEdges;
792 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
John Brawn29bbed32018-02-23 17:17:31 +0000793 SmallVector<unsigned, 8> UnlikelyEdges;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000794
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700795 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700796 LoopBlock SuccLB(*I, LI, *SccI.get());
797 LoopEdge Edge(LB, SuccLB);
798 bool IsUnlikelyEdge =
799 LB.getLoop() && (UnlikelyBlocks.find(*I) != UnlikelyBlocks.end());
800
801 if (IsUnlikelyEdge)
802 UnlikelyEdges.push_back(I.getSuccessorIndex());
803 else if (isLoopExitingEdge(Edge))
804 ExitingEdges.push_back(I.getSuccessorIndex());
805 else if (isLoopBackEdge(Edge))
806 BackEdges.push_back(I.getSuccessorIndex());
807 else {
808 InEdges.push_back(I.getSuccessorIndex());
Geoff Berryeed65312017-11-01 15:16:50 +0000809 }
Andrew Trick49371f32011-06-04 01:16:30 +0000810 }
811
John Brawn29bbed32018-02-23 17:17:31 +0000812 if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty())
Akira Hatanaka5638b892014-04-14 16:56:19 +0000813 return false;
814
Cong Houe93b8e12015-12-22 18:56:14 +0000815 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
816 // normalize them so that they sum up to one.
Cong Houe93b8e12015-12-22 18:56:14 +0000817 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
818 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
John Brawn29bbed32018-02-23 17:17:31 +0000819 (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) +
Cong Houe93b8e12015-12-22 18:56:14 +0000820 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
Andrew Trick49371f32011-06-04 01:16:30 +0000821
Yevgeny Rouban81384872020-05-21 11:49:11 +0700822 SmallVector<BranchProbability, 4> EdgeProbabilities(
823 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000824 if (uint32_t numBackEdges = BackEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000825 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
826 auto Prob = TakenProb / numBackEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000827 for (unsigned SuccIdx : BackEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700828 EdgeProbabilities[SuccIdx] = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000829 }
830
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000831 if (uint32_t numInEdges = InEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000832 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
833 auto Prob = TakenProb / numInEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000834 for (unsigned SuccIdx : InEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700835 EdgeProbabilities[SuccIdx] = Prob;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000836 }
837
Chandler Carruth32f46e72011-10-25 09:47:41 +0000838 if (uint32_t numExitingEdges = ExitingEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000839 BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT,
840 Denom);
841 auto Prob = NotTakenProb / numExitingEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000842 for (unsigned SuccIdx : ExitingEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700843 EdgeProbabilities[SuccIdx] = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000844 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000845
John Brawn29bbed32018-02-23 17:17:31 +0000846 if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) {
847 BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT,
848 Denom);
849 auto Prob = UnlikelyProb / numUnlikelyEdges;
850 for (unsigned SuccIdx : UnlikelyEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700851 EdgeProbabilities[SuccIdx] = Prob;
John Brawn29bbed32018-02-23 17:17:31 +0000852 }
853
Yevgeny Rouban81384872020-05-21 11:49:11 +0700854 setEdgeProbability(BB, EdgeProbabilities);
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000855 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000856}
857
Dávid Bolvanský0f14b2e2020-08-17 20:42:57 +0200858bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
John Brawnda4a68a2017-06-08 09:44:40 +0000859 const TargetLibraryInfo *TLI) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000860 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000861 if (!BI || !BI->isConditional())
862 return false;
863
864 Value *Cond = BI->getCondition();
865 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
866 if (!CI)
867 return false;
868
Sam Parker0b53e842019-02-15 11:50:21 +0000869 auto GetConstantInt = [](Value *V) {
870 if (auto *I = dyn_cast<BitCastInst>(V))
871 return dyn_cast<ConstantInt>(I->getOperand(0));
872 return dyn_cast<ConstantInt>(V);
873 };
874
Jakub Staszak17af66a2011-07-31 03:27:24 +0000875 Value *RHS = CI->getOperand(1);
Sam Parker0b53e842019-02-15 11:50:21 +0000876 ConstantInt *CV = GetConstantInt(RHS);
Dávid Bolvanský0f14b2e2020-08-17 20:42:57 +0200877 if (!CV)
878 return false;
Jakub Staszak17af66a2011-07-31 03:27:24 +0000879
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000880 // If the LHS is the result of AND'ing a value with a single bit bitmask,
881 // we don't have information about probabilities.
882 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
883 if (LHS->getOpcode() == Instruction::And)
Wei Wang32793472020-11-13 11:17:47 -0800884 if (ConstantInt *AndRHS = GetConstantInt(LHS->getOperand(1)))
Craig Topper4e22ee62017-08-04 16:59:29 +0000885 if (AndRHS->getValue().isPowerOf2())
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000886 return false;
887
John Brawnda4a68a2017-06-08 09:44:40 +0000888 // Check if the LHS is the return value of a library function
889 LibFunc Func = NumLibFuncs;
890 if (TLI)
891 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
892 if (Function *CalledFn = Call->getCalledFunction())
893 TLI->getLibFunc(*CalledFn, Func);
894
Jakub Staszak17af66a2011-07-31 03:27:24 +0000895 bool isProb;
John Brawnda4a68a2017-06-08 09:44:40 +0000896 if (Func == LibFunc_strcasecmp ||
897 Func == LibFunc_strcmp ||
898 Func == LibFunc_strncasecmp ||
899 Func == LibFunc_strncmp ||
Dávid Bolvanskýd68a2852020-08-11 20:42:58 +0200900 Func == LibFunc_memcmp ||
901 Func == LibFunc_bcmp) {
John Brawnda4a68a2017-06-08 09:44:40 +0000902 // strcmp and similar functions return zero, negative, or positive, if the
903 // first string is equal, less, or greater than the second. We consider it
904 // likely that the strings are not equal, so a comparison with zero is
905 // probably false, but also a comparison with any other number is also
906 // probably false given that what exactly is returned for nonzero values is
907 // not specified. Any kind of comparison other than equality we know
908 // nothing about.
909 switch (CI->getPredicate()) {
910 case CmpInst::ICMP_EQ:
911 isProb = false;
912 break;
913 case CmpInst::ICMP_NE:
914 isProb = true;
915 break;
916 default:
917 return false;
918 }
919 } else if (CV->isZero()) {
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000920 switch (CI->getPredicate()) {
921 case CmpInst::ICMP_EQ:
922 // X == 0 -> Unlikely
923 isProb = false;
924 break;
925 case CmpInst::ICMP_NE:
926 // X != 0 -> Likely
927 isProb = true;
928 break;
929 case CmpInst::ICMP_SLT:
930 // X < 0 -> Unlikely
931 isProb = false;
932 break;
933 case CmpInst::ICMP_SGT:
934 // X > 0 -> Likely
935 isProb = true;
936 break;
937 default:
938 return false;
939 }
940 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
941 // InstCombine canonicalizes X <= 0 into X < 1.
942 // X <= 0 -> Unlikely
Jakub Staszak17af66a2011-07-31 03:27:24 +0000943 isProb = false;
Craig Topper79ab6432017-07-06 18:39:47 +0000944 } else if (CV->isMinusOne()) {
Hal Finkel4d949302013-11-01 10:58:22 +0000945 switch (CI->getPredicate()) {
946 case CmpInst::ICMP_EQ:
947 // X == -1 -> Unlikely
948 isProb = false;
949 break;
950 case CmpInst::ICMP_NE:
951 // X != -1 -> Likely
952 isProb = true;
953 break;
954 case CmpInst::ICMP_SGT:
955 // InstCombine canonicalizes X >= 0 into X > -1.
956 // X >= 0 -> Likely
957 isProb = true;
958 break;
959 default:
960 return false;
961 }
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000962 } else {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000963 return false;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000964 }
Jakub Staszak17af66a2011-07-31 03:27:24 +0000965
Dávid Bolvanský0f14b2e2020-08-17 20:42:57 +0200966 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
967 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
968 BranchProbability UntakenProb(ZH_NONTAKEN_WEIGHT,
969 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
Yevgeny Rouban81384872020-05-21 11:49:11 +0700970 if (!isProb)
971 std::swap(TakenProb, UntakenProb);
972
973 setEdgeProbability(
974 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb}));
Jakub Staszak17af66a2011-07-31 03:27:24 +0000975 return true;
976}
977
Mehdi Aminia7978772016-04-07 21:59:28 +0000978bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
979 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000980 if (!BI || !BI->isConditional())
981 return false;
982
983 Value *Cond = BI->getCondition();
984 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000985 if (!FCmp)
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000986 return false;
987
Guozhi Weib329e072019-09-10 17:25:11 +0000988 uint32_t TakenWeight = FPH_TAKEN_WEIGHT;
989 uint32_t NontakenWeight = FPH_NONTAKEN_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000990 bool isProb;
991 if (FCmp->isEquality()) {
992 // f1 == f2 -> Unlikely
993 // f1 != f2 -> Likely
994 isProb = !FCmp->isTrueWhenEqual();
995 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
996 // !isnan -> Likely
997 isProb = true;
Guozhi Weib329e072019-09-10 17:25:11 +0000998 TakenWeight = FPH_ORD_WEIGHT;
999 NontakenWeight = FPH_UNO_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +00001000 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
1001 // isnan -> Unlikely
1002 isProb = false;
Guozhi Weib329e072019-09-10 17:25:11 +00001003 TakenWeight = FPH_ORD_WEIGHT;
1004 NontakenWeight = FPH_UNO_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +00001005 } else {
1006 return false;
1007 }
1008
Reid Kleckner13707572020-05-13 08:23:09 -07001009 BranchProbability TakenProb(TakenWeight, TakenWeight + NontakenWeight);
Yevgeny Rouban81384872020-05-21 11:49:11 +07001010 BranchProbability UntakenProb(NontakenWeight, TakenWeight + NontakenWeight);
1011 if (!isProb)
1012 std::swap(TakenProb, UntakenProb);
1013
1014 setEdgeProbability(
1015 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb}));
Benjamin Kramer1e731a12011-10-21 20:12:47 +00001016 return true;
1017}
Jakub Staszak17af66a2011-07-31 03:27:24 +00001018
Mehdi Aminia7978772016-04-07 21:59:28 +00001019bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
1020 const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
Bill Wendlinge1c54262012-08-15 12:22:35 +00001021 if (!II)
1022 return false;
1023
Cong Houe93b8e12015-12-22 18:56:14 +00001024 BranchProbability TakenProb(IH_TAKEN_WEIGHT,
1025 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
Yevgeny Rouban81384872020-05-21 11:49:11 +07001026 setEdgeProbability(
1027 BB, SmallVector<BranchProbability, 2>({TakenProb, TakenProb.getCompl()}));
Bill Wendlinge1c54262012-08-15 12:22:35 +00001028 return true;
1029}
1030
Pete Cooperb9d2e342015-05-28 19:43:06 +00001031void BranchProbabilityInfo::releaseMemory() {
Cong Houe93b8e12015-12-22 18:56:14 +00001032 Probs.clear();
Nikita Popovfe8abbf2020-04-07 21:21:30 +02001033 Handles.clear();
Pete Cooperb9d2e342015-05-28 19:43:06 +00001034}
1035
Alina Sbirlea62a50a92020-01-15 14:02:33 -08001036bool BranchProbabilityInfo::invalidate(Function &, const PreservedAnalyses &PA,
1037 FunctionAnalysisManager::Invalidator &) {
1038 // Check whether the analysis, all analyses on functions, or the function's
1039 // CFG have been preserved.
1040 auto PAC = PA.getChecker<BranchProbabilityAnalysis>();
1041 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
1042 PAC.preservedSet<CFGAnalyses>());
1043}
1044
Cong Houab23bfb2015-07-15 22:48:29 +00001045void BranchProbabilityInfo::print(raw_ostream &OS) const {
Chandler Carruth1c8ace02011-10-23 21:21:50 +00001046 OS << "---- Branch Probabilities ----\n";
1047 // We print the probabilities from the last function the analysis ran over,
1048 // or the function it is currently running over.
1049 assert(LastF && "Cannot print prior to running over a function");
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001050 for (const auto &BI : *LastF) {
Alina Sbirlea3abcbf92020-03-10 11:33:02 -07001051 for (const_succ_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001052 ++SI) {
1053 printEdgeProbability(OS << " ", &BI, *SI);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001054 }
1055 }
Chandler Carruth1c8ace02011-10-23 21:21:50 +00001056}
1057
Jakub Staszakefd94c82011-07-29 19:30:00 +00001058bool BranchProbabilityInfo::
1059isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +00001060 // Hot probability is at least 4/5 = 80%
Benjamin Kramer929f53f2011-10-23 11:19:14 +00001061 // FIXME: Compare against a static "hot" BranchProbability.
1062 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick49371f32011-06-04 01:16:30 +00001063}
1064
Mehdi Aminia7978772016-04-07 21:59:28 +00001065const BasicBlock *
1066BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
Cong Houe93b8e12015-12-22 18:56:14 +00001067 auto MaxProb = BranchProbability::getZero();
Mehdi Aminia7978772016-04-07 21:59:28 +00001068 const BasicBlock *MaxSucc = nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +00001069
Kazu Hirata85cd7ff2020-11-10 09:00:17 -08001070 for (const auto *Succ : successors(BB)) {
Cong Houe93b8e12015-12-22 18:56:14 +00001071 auto Prob = getEdgeProbability(BB, Succ);
1072 if (Prob > MaxProb) {
1073 MaxProb = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +00001074 MaxSucc = Succ;
1075 }
1076 }
1077
Benjamin Kramer929f53f2011-10-23 11:19:14 +00001078 // Hot probability is at least 4/5 = 80%
Cong Houe93b8e12015-12-22 18:56:14 +00001079 if (MaxProb > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +00001080 return MaxSucc;
1081
Craig Topper9f008862014-04-15 04:59:12 +00001082 return nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +00001083}
1084
Cong Houe93b8e12015-12-22 18:56:14 +00001085/// Get the raw edge probability for the edge. If can't find it, return a
1086/// default probability 1/N where N is the number of successors. Here an edge is
1087/// specified using PredBlock and an
1088/// index to the successors.
1089BranchProbability
1090BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
1091 unsigned IndexInSuccessors) const {
Kazu Hirata21fbe2e2020-11-10 19:17:13 -08001092 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
1093 assert((Probs.end() == Probs.find(std::make_pair(Src, 0))) ==
1094 (Probs.end() == I) &&
1095 "Probability for I-th successor must always be defined along with the "
1096 "probability for the first successor");
Andrew Trick49371f32011-06-04 01:16:30 +00001097
Kazu Hirata21fbe2e2020-11-10 19:17:13 -08001098 if (I != Probs.end())
1099 return I->second;
1100
1101 return {1, static_cast<uint32_t>(succ_size(Src))};
Andrew Trick49371f32011-06-04 01:16:30 +00001102}
1103
Cong Houd97c1002015-12-01 05:29:22 +00001104BranchProbability
1105BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
Alina Sbirlea3abcbf92020-03-10 11:33:02 -07001106 const_succ_iterator Dst) const {
Cong Houd97c1002015-12-01 05:29:22 +00001107 return getEdgeProbability(Src, Dst.getSuccessorIndex());
1108}
1109
Cong Houe93b8e12015-12-22 18:56:14 +00001110/// Get the raw edge probability calculated for the block pair. This returns the
1111/// sum of all raw edge probabilities from Src to Dst.
1112BranchProbability
1113BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
1114 const BasicBlock *Dst) const {
Kazu Hirata21fbe2e2020-11-10 19:17:13 -08001115 if (!Probs.count(std::make_pair(Src, 0)))
Kazu Hirata118c3f32020-11-06 22:47:22 -08001116 return BranchProbability(llvm::count(successors(Src), Dst), succ_size(Src));
1117
Cong Houe93b8e12015-12-22 18:56:14 +00001118 auto Prob = BranchProbability::getZero();
Alina Sbirlea3abcbf92020-03-10 11:33:02 -07001119 for (const_succ_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
Kazu Hirata118c3f32020-11-06 22:47:22 -08001120 if (*I == Dst)
Kazu Hirata21fbe2e2020-11-10 19:17:13 -08001121 Prob += Probs.find(std::make_pair(Src, I.getSuccessorIndex()))->second;
Kazu Hirata118c3f32020-11-06 22:47:22 -08001122
1123 return Prob;
Cong Houe93b8e12015-12-22 18:56:14 +00001124}
1125
Yevgeny Rouban81384872020-05-21 11:49:11 +07001126/// Set the edge probability for all edges at once.
1127void BranchProbabilityInfo::setEdgeProbability(
1128 const BasicBlock *Src, const SmallVectorImpl<BranchProbability> &Probs) {
1129 assert(Src->getTerminator()->getNumSuccessors() == Probs.size());
Yevgeny Rouban49311582020-11-06 12:16:19 +07001130 eraseBlock(Src); // Erase stale data if any.
Yevgeny Rouban81384872020-05-21 11:49:11 +07001131 if (Probs.size() == 0)
1132 return; // Nothing to set.
1133
Yevgeny Roubane38c8e72020-11-06 13:11:08 +07001134 Handles.insert(BasicBlockCallbackVH(Src, this));
Yevgeny Rouban81384872020-05-21 11:49:11 +07001135 uint64_t TotalNumerator = 0;
1136 for (unsigned SuccIdx = 0; SuccIdx < Probs.size(); ++SuccIdx) {
Kazu Hirata21fbe2e2020-11-10 19:17:13 -08001137 this->Probs[std::make_pair(Src, SuccIdx)] = Probs[SuccIdx];
Yevgeny Rouban49311582020-11-06 12:16:19 +07001138 LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> " << SuccIdx
1139 << " successor probability to " << Probs[SuccIdx]
1140 << "\n");
Yevgeny Rouban81384872020-05-21 11:49:11 +07001141 TotalNumerator += Probs[SuccIdx].getNumerator();
1142 }
1143
1144 // Because of rounding errors the total probability cannot be checked to be
1145 // 1.0 exactly. That is TotalNumerator == BranchProbability::getDenominator.
1146 // Instead, every single probability in Probs must be as accurate as possible.
1147 // This results in error 1/denominator at most, thus the total absolute error
1148 // should be within Probs.size / BranchProbability::getDenominator.
1149 assert(TotalNumerator <= BranchProbability::getDenominator() + Probs.size());
1150 assert(TotalNumerator >= BranchProbability::getDenominator() - Probs.size());
1151}
1152
Yevgeny Rouban681d6c72020-11-06 14:46:34 +07001153void BranchProbabilityInfo::copyEdgeProbabilities(BasicBlock *Src,
1154 BasicBlock *Dst) {
1155 eraseBlock(Dst); // Erase stale data if any.
1156 unsigned NumSuccessors = Src->getTerminator()->getNumSuccessors();
1157 assert(NumSuccessors == Dst->getTerminator()->getNumSuccessors());
1158 if (NumSuccessors == 0)
1159 return; // Nothing to set.
Kazu Hirata21fbe2e2020-11-10 19:17:13 -08001160 if (this->Probs.find(std::make_pair(Src, 0)) == this->Probs.end())
Yevgeny Rouban681d6c72020-11-06 14:46:34 +07001161 return; // No probability is set for edges from Src. Keep the same for Dst.
1162
1163 Handles.insert(BasicBlockCallbackVH(Dst, this));
Kazu Hirata21fbe2e2020-11-10 19:17:13 -08001164 for (unsigned SuccIdx = 0; SuccIdx < NumSuccessors; ++SuccIdx) {
1165 auto Prob = this->Probs[std::make_pair(Src, SuccIdx)];
1166 this->Probs[std::make_pair(Dst, SuccIdx)] = Prob;
Yevgeny Rouban681d6c72020-11-06 14:46:34 +07001167 LLVM_DEBUG(dbgs() << "set edge " << Dst->getName() << " -> " << SuccIdx
Kazu Hirata21fbe2e2020-11-10 19:17:13 -08001168 << " successor probability to " << Prob << "\n");
1169 }
Yevgeny Rouban681d6c72020-11-06 14:46:34 +07001170}
1171
Andrew Trick49371f32011-06-04 01:16:30 +00001172raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +00001173BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
1174 const BasicBlock *Src,
1175 const BasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001176 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +00001177 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +00001178 << " probability is " << Prob
1179 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +00001180
1181 return OS;
1182}
Cong Houab23bfb2015-07-15 22:48:29 +00001183
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001184void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
Kazu Hirata147ccc82020-11-15 22:29:30 -08001185 LLVM_DEBUG(dbgs() << "eraseBlock " << BB->getName() << "\n");
1186
Kazu Hirata21fbe2e2020-11-10 19:17:13 -08001187 // Note that we cannot use successors of BB because the terminator of BB may
1188 // have changed when eraseBlock is called as a BasicBlockCallbackVH callback.
1189 // Instead we remove prob data for the block by iterating successors by their
1190 // indices from 0 till the last which exists. There could not be prob data for
1191 // a pair (BB, N) if there is no data for (BB, N-1) because the data is always
1192 // set for all successors from 0 to M at once by the method
1193 // setEdgeProbability().
Yevgeny Roubane38c8e72020-11-06 13:11:08 +07001194 Handles.erase(BasicBlockCallbackVH(BB, this));
Kazu Hirata21fbe2e2020-11-10 19:17:13 -08001195 for (unsigned I = 0;; ++I) {
1196 auto MapI = Probs.find(std::make_pair(BB, I));
1197 if (MapI == Probs.end()) {
1198 assert(Probs.count(std::make_pair(BB, I + 1)) == 0 &&
1199 "Must be no more successors");
1200 return;
1201 }
1202 Probs.erase(MapI);
1203 }
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001204}
1205
John Brawnda4a68a2017-06-08 09:44:40 +00001206void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001207 const TargetLibraryInfo *TLI,
1208 PostDominatorTree *PDT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001209 LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
1210 << " ----\n\n");
Cong Houab23bfb2015-07-15 22:48:29 +00001211 LastF = &F; // Store the last function we ran on for printing.
1212 assert(PostDominatedByUnreachable.empty());
1213 assert(PostDominatedByColdCall.empty());
1214
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +07001215 SccI = std::make_unique<SccInfo>(F);
Geoff Berryeed65312017-11-01 15:16:50 +00001216
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001217 std::unique_ptr<PostDominatorTree> PDTPtr;
1218
1219 if (!PDT) {
1220 PDTPtr = std::make_unique<PostDominatorTree>(const_cast<Function &>(F));
1221 PDT = PDTPtr.get();
1222 }
1223
1224 computePostDominatedByUnreachable(F, PDT);
1225 computePostDominatedByColdCall(F, PDT);
Taewook Oh2da205d2019-12-02 10:15:22 -08001226
Cong Houab23bfb2015-07-15 22:48:29 +00001227 // Walk the basic blocks in post-order so that we can build up state about
1228 // the successors of a block iteratively.
1229 for (auto BB : post_order(&F.getEntryBlock())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001230 LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName()
1231 << "\n");
Serguei Katkov11d9c4f2017-04-17 06:39:47 +00001232 // If there is no at least two successors, no sense to set probability.
1233 if (BB->getTerminator()->getNumSuccessors() < 2)
1234 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001235 if (calcMetadataWeights(BB))
1236 continue;
Artur Pilipenko4d063e72018-06-08 13:03:21 +00001237 if (calcInvokeHeuristics(BB))
1238 continue;
Serguei Katkov2616bbb2017-04-17 04:33:04 +00001239 if (calcUnreachableHeuristics(BB))
1240 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001241 if (calcColdCallHeuristics(BB))
1242 continue;
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +07001243 if (calcLoopBranchHeuristics(BB, LI))
Cong Houab23bfb2015-07-15 22:48:29 +00001244 continue;
1245 if (calcPointerHeuristics(BB))
1246 continue;
Dávid Bolvanský0f14b2e2020-08-17 20:42:57 +02001247 if (calcZeroHeuristics(BB, TLI))
Cong Houab23bfb2015-07-15 22:48:29 +00001248 continue;
1249 if (calcFloatingPointHeuristics(BB))
1250 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001251 }
1252
1253 PostDominatedByUnreachable.clear();
1254 PostDominatedByColdCall.clear();
Evgeniy Brevnov412b3932020-07-28 19:50:40 +07001255 SccI.reset();
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +00001256
1257 if (PrintBranchProb &&
1258 (PrintBranchProbFuncName.empty() ||
1259 F.getName().equals(PrintBranchProbFuncName))) {
1260 print(dbgs());
1261 }
Cong Houab23bfb2015-07-15 22:48:29 +00001262}
1263
1264void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
1265 AnalysisUsage &AU) const {
Mikael Holmen2ca16892018-05-17 09:05:40 +00001266 // We require DT so it's available when LI is available. The LI updating code
1267 // asserts that DT is also present so if we don't make sure that we have DT
1268 // here, that assert will trigger.
1269 AU.addRequired<DominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001270 AU.addRequired<LoopInfoWrapperPass>();
John Brawnda4a68a2017-06-08 09:44:40 +00001271 AU.addRequired<TargetLibraryInfoWrapperPass>();
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001272 AU.addRequired<PostDominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001273 AU.setPreservesAll();
1274}
1275
1276bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
1277 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnson9c27b592019-09-07 03:09:36 +00001278 const TargetLibraryInfo &TLI =
1279 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001280 PostDominatorTree &PDT =
1281 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
1282 BPI.calculate(F, LI, &TLI, &PDT);
Cong Houab23bfb2015-07-15 22:48:29 +00001283 return false;
1284}
1285
1286void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
1287
1288void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
1289 const Module *) const {
1290 BPI.print(OS);
1291}
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001292
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001293AnalysisKey BranchProbabilityAnalysis::Key;
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001294BranchProbabilityInfo
Sean Silva36e0d012016-08-09 00:28:15 +00001295BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001296 BranchProbabilityInfo BPI;
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001297 BPI.calculate(F, AM.getResult<LoopAnalysis>(F),
1298 &AM.getResult<TargetLibraryAnalysis>(F),
1299 &AM.getResult<PostDominatorTreeAnalysis>(F));
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001300 return BPI;
1301}
1302
1303PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +00001304BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001305 OS << "Printing analysis results of BPI for function "
1306 << "'" << F.getName() << "':"
1307 << "\n";
1308 AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
1309 return PreservedAnalyses::all();
1310}