blob: 0a14c8c2bc44f96dfc921ab35b61c7422ce849f5 [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
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
223 if (llvm::any_of(make_range(pred_begin(BB), pred_end(BB)),
224 [&](const BasicBlock *Pred) {
225 // Consider any block that is an entry point to the SCC as
226 // a header.
227 return getSCCNum(Pred) != SccNum;
228 }))
229 BlockType |= Header;
230
231 if (llvm::any_of(
232 make_range(succ_begin(BB), succ_end(BB)),
233 [&](const BasicBlock *Succ) { return getSCCNum(Succ) != SccNum; }))
234 BlockType |= Exiting;
235
236 // Lazily compute the set of headers for a given SCC and cache the results
237 // in the SccHeaderMap.
238 if (SccBlocks.size() <= static_cast<unsigned>(SccNum))
239 SccBlocks.resize(SccNum + 1);
240 auto &SccBlockTypes = SccBlocks[SccNum];
241
242 if (BlockType != Inner) {
243 bool IsInserted;
244 std::tie(std::ignore, IsInserted) =
245 SccBlockTypes.insert(std::make_pair(BB, BlockType));
246 assert(IsInserted && "Duplicated block in SCC");
247 }
248}
249
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700250BranchProbabilityInfo::LoopBlock::LoopBlock(const BasicBlock *BB,
251 const LoopInfo &LI,
252 const SccInfo &SccI)
253 : BB(BB) {
254 LD.first = LI.getLoopFor(BB);
255 if (!LD.first) {
256 LD.second = SccI.getSCCNum(BB);
257 }
258}
259
260bool BranchProbabilityInfo::isLoopEnteringEdge(const LoopEdge &Edge) const {
261 const auto &SrcBlock = Edge.first;
262 const auto &DstBlock = Edge.second;
263 return (DstBlock.getLoop() &&
264 !DstBlock.getLoop()->contains(SrcBlock.getLoop())) ||
265 // Assume that SCCs can't be nested.
266 (DstBlock.getSccNum() != -1 &&
267 SrcBlock.getSccNum() != DstBlock.getSccNum());
268}
269
270bool BranchProbabilityInfo::isLoopExitingEdge(const LoopEdge &Edge) const {
271 return isLoopEnteringEdge({Edge.second, Edge.first});
272}
273
274bool BranchProbabilityInfo::isLoopEnteringExitingEdge(
275 const LoopEdge &Edge) const {
276 return isLoopEnteringEdge(Edge) || isLoopExitingEdge(Edge);
277}
278
279bool BranchProbabilityInfo::isLoopBackEdge(const LoopEdge &Edge) const {
280 const auto &SrcBlock = Edge.first;
281 const auto &DstBlock = Edge.second;
282 return SrcBlock.belongsToSameLoop(DstBlock) &&
283 ((DstBlock.getLoop() &&
284 DstBlock.getLoop()->getHeader() == DstBlock.getBlock()) ||
285 (DstBlock.getSccNum() != -1 &&
286 SccI->isSCCHeader(DstBlock.getBlock(), DstBlock.getSccNum())));
287}
288
289void BranchProbabilityInfo::getLoopEnterBlocks(
290 const LoopBlock &LB, SmallVectorImpl<BasicBlock *> &Enters) const {
291 if (LB.getLoop()) {
292 auto *Header = LB.getLoop()->getHeader();
293 Enters.append(pred_begin(Header), pred_end(Header));
294 } else {
295 assert(LB.getSccNum() != -1 && "LB doesn't belong to any loop?");
296 SccI->getSccEnterBlocks(LB.getSccNum(), Enters);
297 }
298}
299
300void BranchProbabilityInfo::getLoopExitBlocks(
301 const LoopBlock &LB, SmallVectorImpl<BasicBlock *> &Exits) const {
302 if (LB.getLoop()) {
303 LB.getLoop()->getExitBlocks(Exits);
304 } else {
305 assert(LB.getSccNum() != -1 && "LB doesn't belong to any loop?");
306 SccI->getSccExitBlocks(LB.getSccNum(), Exits);
307 }
308}
309
Taewook Oh2da205d2019-12-02 10:15:22 -0800310static void UpdatePDTWorklist(const BasicBlock *BB, PostDominatorTree *PDT,
311 SmallVectorImpl<const BasicBlock *> &WorkList,
312 SmallPtrSetImpl<const BasicBlock *> &TargetSet) {
313 SmallVector<BasicBlock *, 8> Descendants;
314 SmallPtrSet<const BasicBlock *, 16> NewItems;
Chandler Carruth7111f452011-10-24 12:01:08 +0000315
Taewook Oh2da205d2019-12-02 10:15:22 -0800316 PDT->getDescendants(const_cast<BasicBlock *>(BB), Descendants);
317 for (auto *BB : Descendants)
318 if (TargetSet.insert(BB).second)
319 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
320 if (!TargetSet.count(*PI))
321 NewItems.insert(*PI);
322 WorkList.insert(WorkList.end(), NewItems.begin(), NewItems.end());
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000323}
324
Taewook Oh2da205d2019-12-02 10:15:22 -0800325/// Compute a set of basic blocks that are post-dominated by unreachables.
326void BranchProbabilityInfo::computePostDominatedByUnreachable(
327 const Function &F, PostDominatorTree *PDT) {
328 SmallVector<const BasicBlock *, 8> WorkList;
329 for (auto &BB : F) {
330 const Instruction *TI = BB.getTerminator();
331 if (TI->getNumSuccessors() == 0) {
332 if (isa<UnreachableInst>(TI) ||
333 // If this block is terminated by a call to
334 // @llvm.experimental.deoptimize then treat it like an unreachable
335 // since the @llvm.experimental.deoptimize call is expected to
336 // practically never execute.
337 BB.getTerminatingDeoptimizeCall())
338 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByUnreachable);
339 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000340 }
341
Taewook Oh2da205d2019-12-02 10:15:22 -0800342 while (!WorkList.empty()) {
343 const BasicBlock *BB = WorkList.pop_back_val();
344 if (PostDominatedByUnreachable.count(BB))
345 continue;
346 // If the terminator is an InvokeInst, check only the normal destination
347 // block as the unwind edge of InvokeInst is also very unlikely taken.
348 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
349 if (PostDominatedByUnreachable.count(II->getNormalDest()))
350 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000351 }
Taewook Oh2da205d2019-12-02 10:15:22 -0800352 // If all the successors are unreachable, BB is unreachable as well.
353 else if (!successors(BB).empty() &&
354 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
355 return PostDominatedByUnreachable.count(Succ);
356 }))
357 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
358 }
359}
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000360
Taewook Oh2da205d2019-12-02 10:15:22 -0800361/// compute a set of basic blocks that are post-dominated by ColdCalls.
362void BranchProbabilityInfo::computePostDominatedByColdCall(
363 const Function &F, PostDominatorTree *PDT) {
364 SmallVector<const BasicBlock *, 8> WorkList;
365 for (auto &BB : F)
366 for (auto &I : BB)
367 if (const CallInst *CI = dyn_cast<CallInst>(&I))
368 if (CI->hasFnAttr(Attribute::Cold))
369 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByColdCall);
370
371 while (!WorkList.empty()) {
372 const BasicBlock *BB = WorkList.pop_back_val();
373
374 // If the terminator is an InvokeInst, check only the normal destination
375 // block as the unwind edge of InvokeInst is also very unlikely taken.
376 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
377 if (PostDominatedByColdCall.count(II->getNormalDest()))
378 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
379 }
380 // If all of successor are post dominated then BB is also done.
381 else if (!successors(BB).empty() &&
382 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
383 return PostDominatedByColdCall.count(Succ);
384 }))
385 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
386 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000387}
388
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000389/// Calculate edge weights for successors lead to unreachable.
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000390///
391/// Predict that a successor which leads necessarily to an
392/// unreachable-terminated block as extremely unlikely.
393bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000394 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000395 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000396 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000397 assert(!isa<InvokeInst>(TI) &&
398 "Invokes should have already been handled by calcInvokeHeuristics");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000399
Manman Rencf104462012-08-24 18:14:27 +0000400 SmallVector<unsigned, 4> UnreachableEdges;
401 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000402
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700403 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Chandler Carruth7111f452011-10-24 12:01:08 +0000404 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000405 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000406 else
Manman Rencf104462012-08-24 18:14:27 +0000407 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000408
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000409 // Skip probabilities if all were reachable.
410 if (UnreachableEdges.empty())
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000411 return false;
Jun Bum Lima23e5f72015-12-21 22:00:51 +0000412
Yevgeny Rouban81384872020-05-21 11:49:11 +0700413 SmallVector<BranchProbability, 4> EdgeProbabilities(
414 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000415 if (ReachableEdges.empty()) {
416 BranchProbability Prob(1, UnreachableEdges.size());
417 for (unsigned SuccIdx : UnreachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700418 EdgeProbabilities[SuccIdx] = Prob;
419 setEdgeProbability(BB, EdgeProbabilities);
Chandler Carruth7111f452011-10-24 12:01:08 +0000420 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000421 }
422
Serguei Katkovba831f72017-05-18 06:11:56 +0000423 auto UnreachableProb = UR_TAKEN_PROB;
424 auto ReachableProb =
425 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
426 ReachableEdges.size();
Cong Houe93b8e12015-12-22 18:56:14 +0000427
428 for (unsigned SuccIdx : UnreachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700429 EdgeProbabilities[SuccIdx] = UnreachableProb;
Cong Houe93b8e12015-12-22 18:56:14 +0000430 for (unsigned SuccIdx : ReachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700431 EdgeProbabilities[SuccIdx] = ReachableProb;
Chandler Carruth7111f452011-10-24 12:01:08 +0000432
Yevgeny Rouban81384872020-05-21 11:49:11 +0700433 setEdgeProbability(BB, EdgeProbabilities);
Chandler Carruth7111f452011-10-24 12:01:08 +0000434 return true;
435}
436
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000437// Propagate existing explicit probabilities from either profile data or
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000438// 'expect' intrinsic processing. Examine metadata against unreachable
439// heuristic. The probability of the edge coming to unreachable block is
440// set to min of metadata and unreachable heuristic.
Mehdi Aminia7978772016-04-07 21:59:28 +0000441bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000442 const Instruction *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000443 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Yevgeny Roubandcfa78a2020-06-04 15:34:14 +0700444 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI) ||
445 isa<InvokeInst>(TI)))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000446 return false;
447
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000448 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000449 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000450 return false;
451
Diego Novillode5b8012015-05-07 17:22:06 +0000452 // Check that the number of successors is manageable.
453 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
454
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000455 // Ensure there are weights for all of the successors. Note that the first
456 // operand to the metadata node is a name, not a weight.
457 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000458 return false;
459
Diego Novillode5b8012015-05-07 17:22:06 +0000460 // Build up the final weights that will be used in a temporary buffer.
461 // Compute the sum of all weights to later decide whether they need to
462 // be scaled to fit in 32 bits.
463 uint64_t WeightSum = 0;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000464 SmallVector<uint32_t, 2> Weights;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000465 SmallVector<unsigned, 2> UnreachableIdxs;
466 SmallVector<unsigned, 2> ReachableIdxs;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000467 Weights.reserve(TI->getNumSuccessors());
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700468 for (unsigned I = 1, E = WeightsNode->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000469 ConstantInt *Weight =
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700470 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(I));
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000471 if (!Weight)
472 return false;
Diego Novillode5b8012015-05-07 17:22:06 +0000473 assert(Weight->getValue().getActiveBits() <= 32 &&
474 "Too many bits for uint32_t");
475 Weights.push_back(Weight->getZExtValue());
476 WeightSum += Weights.back();
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700477 if (PostDominatedByUnreachable.count(TI->getSuccessor(I - 1)))
478 UnreachableIdxs.push_back(I - 1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000479 else
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700480 ReachableIdxs.push_back(I - 1);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000481 }
482 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
Diego Novillode5b8012015-05-07 17:22:06 +0000483
484 // If the sum of weights does not fit in 32 bits, scale every weight down
485 // accordingly.
486 uint64_t ScalingFactor =
487 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
488
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000489 if (ScalingFactor > 1) {
490 WeightSum = 0;
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700491 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
492 Weights[I] /= ScalingFactor;
493 WeightSum += Weights[I];
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000494 }
Diego Novillode5b8012015-05-07 17:22:06 +0000495 }
Serguei Katkov63c9c812017-05-12 07:50:06 +0000496 assert(WeightSum <= UINT32_MAX &&
497 "Expected weights to scale down to 32 bits");
Cong Hou6a2c71a2015-12-22 23:45:55 +0000498
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000499 if (WeightSum == 0 || ReachableIdxs.size() == 0) {
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700500 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I)
501 Weights[I] = 1;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000502 WeightSum = TI->getNumSuccessors();
Cong Hou6a2c71a2015-12-22 23:45:55 +0000503 }
Cong Houe93b8e12015-12-22 18:56:14 +0000504
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000505 // Set the probability.
506 SmallVector<BranchProbability, 2> BP;
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700507 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I)
508 BP.push_back({ Weights[I], static_cast<uint32_t>(WeightSum) });
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000509
510 // Examine the metadata against unreachable heuristic.
511 // If the unreachable heuristic is more strong then we use it for this edge.
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700512 if (UnreachableIdxs.size() == 0 || ReachableIdxs.size() == 0) {
513 setEdgeProbability(BB, BP);
514 return true;
515 }
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000516
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700517 auto UnreachableProb = UR_TAKEN_PROB;
518 for (auto I : UnreachableIdxs)
519 if (UnreachableProb < BP[I]) {
520 BP[I] = UnreachableProb;
521 }
Yevgeny Rouban81384872020-05-21 11:49:11 +0700522
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700523 // Sum of all edge probabilities must be 1.0. If we modified the probability
524 // of some edges then we must distribute the introduced difference over the
525 // reachable blocks.
526 //
527 // Proportional distribution: the relation between probabilities of the
528 // reachable edges is kept unchanged. That is for any reachable edges i and j:
529 // newBP[i] / newBP[j] == oldBP[i] / oldBP[j] =>
530 // newBP[i] / oldBP[i] == newBP[j] / oldBP[j] == K
531 // Where K is independent of i,j.
532 // newBP[i] == oldBP[i] * K
533 // We need to find K.
534 // Make sum of all reachables of the left and right parts:
535 // sum_of_reachable(newBP) == K * sum_of_reachable(oldBP)
536 // Sum of newBP must be equal to 1.0:
537 // sum_of_reachable(newBP) + sum_of_unreachable(newBP) == 1.0 =>
538 // sum_of_reachable(newBP) = 1.0 - sum_of_unreachable(newBP)
539 // Where sum_of_unreachable(newBP) is what has been just changed.
540 // Finally:
541 // K == sum_of_reachable(newBP) / sum_of_reachable(oldBP) =>
542 // K == (1.0 - sum_of_unreachable(newBP)) / sum_of_reachable(oldBP)
543 BranchProbability NewUnreachableSum = BranchProbability::getZero();
544 for (auto I : UnreachableIdxs)
545 NewUnreachableSum += BP[I];
546
547 BranchProbability NewReachableSum =
548 BranchProbability::getOne() - NewUnreachableSum;
549
550 BranchProbability OldReachableSum = BranchProbability::getZero();
551 for (auto I : ReachableIdxs)
552 OldReachableSum += BP[I];
553
554 if (OldReachableSum != NewReachableSum) { // Anything to dsitribute?
555 if (OldReachableSum.isZero()) {
556 // If all oldBP[i] are zeroes then the proportional distribution results
557 // in all zero probabilities and the error stays big. In this case we
558 // evenly spread NewReachableSum over the reachable edges.
559 BranchProbability PerEdge = NewReachableSum / ReachableIdxs.size();
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700560 for (auto I : ReachableIdxs)
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700561 BP[I] = PerEdge;
562 } else {
563 for (auto I : ReachableIdxs) {
564 // We use uint64_t to avoid double rounding error of the following
565 // calculation: BP[i] = BP[i] * NewReachableSum / OldReachableSum
566 // The formula is taken from the private constructor
567 // BranchProbability(uint32_t Numerator, uint32_t Denominator)
568 uint64_t Mul = static_cast<uint64_t>(NewReachableSum.getNumerator()) *
569 BP[I].getNumerator();
570 uint32_t Div = static_cast<uint32_t>(
571 divideNearest(Mul, OldReachableSum.getNumerator()));
572 BP[I] = BranchProbability::getRaw(Div);
573 }
574 }
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000575 }
576
Yevgeny Rouban81384872020-05-21 11:49:11 +0700577 setEdgeProbability(BB, BP);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000578
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000579 return true;
580}
581
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000582/// Calculate edge weights for edges leading to cold blocks.
Diego Novilloc6399532013-05-24 12:26:52 +0000583///
584/// A cold block is one post-dominated by a block with a call to a
585/// cold function. Those edges are unlikely to be taken, so we give
586/// them relatively low weight.
587///
588/// Return true if we could compute the weights for cold edges.
589/// Return false, otherwise.
Mehdi Aminia7978772016-04-07 21:59:28 +0000590bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000591 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000592 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000593 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000594 assert(!isa<InvokeInst>(TI) &&
595 "Invokes should have already been handled by calcInvokeHeuristics");
Diego Novilloc6399532013-05-24 12:26:52 +0000596
597 // Determine which successors are post-dominated by a cold block.
598 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000599 SmallVector<unsigned, 4> NormalEdges;
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700600 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Diego Novilloc6399532013-05-24 12:26:52 +0000601 if (PostDominatedByColdCall.count(*I))
602 ColdEdges.push_back(I.getSuccessorIndex());
603 else
604 NormalEdges.push_back(I.getSuccessorIndex());
605
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000606 // Skip probabilities if no cold edges.
607 if (ColdEdges.empty())
Diego Novilloc6399532013-05-24 12:26:52 +0000608 return false;
609
Yevgeny Rouban81384872020-05-21 11:49:11 +0700610 SmallVector<BranchProbability, 4> EdgeProbabilities(
611 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000612 if (NormalEdges.empty()) {
613 BranchProbability Prob(1, ColdEdges.size());
614 for (unsigned SuccIdx : ColdEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700615 EdgeProbabilities[SuccIdx] = Prob;
616 setEdgeProbability(BB, EdgeProbabilities);
Diego Novilloc6399532013-05-24 12:26:52 +0000617 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000618 }
619
Vedant Kumara4bd1462016-12-17 01:02:08 +0000620 auto ColdProb = BranchProbability::getBranchProbability(
621 CC_TAKEN_WEIGHT,
622 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
623 auto NormalProb = BranchProbability::getBranchProbability(
624 CC_NONTAKEN_WEIGHT,
625 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
Cong Houe93b8e12015-12-22 18:56:14 +0000626
627 for (unsigned SuccIdx : ColdEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700628 EdgeProbabilities[SuccIdx] = ColdProb;
Cong Houe93b8e12015-12-22 18:56:14 +0000629 for (unsigned SuccIdx : NormalEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700630 EdgeProbabilities[SuccIdx] = NormalProb;
Diego Novilloc6399532013-05-24 12:26:52 +0000631
Yevgeny Rouban81384872020-05-21 11:49:11 +0700632 setEdgeProbability(BB, EdgeProbabilities);
Diego Novilloc6399532013-05-24 12:26:52 +0000633 return true;
634}
635
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000636// Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
Andrew Trick49371f32011-06-04 01:16:30 +0000637// between two pointer or pointer and NULL will fail.
Mehdi Aminia7978772016-04-07 21:59:28 +0000638bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
639 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Andrew Trick49371f32011-06-04 01:16:30 +0000640 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000641 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000642
643 Value *Cond = BI->getCondition();
644 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000645 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000646 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000647
648 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000649
650 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000651 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000652
Nick Lewycky75b20532011-06-04 02:07:10 +0000653 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000654
Yevgeny Rouban81384872020-05-21 11:49:11 +0700655 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
656 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
657 BranchProbability UntakenProb(PH_NONTAKEN_WEIGHT,
658 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
659
Andrew Trick49371f32011-06-04 01:16:30 +0000660 // p != 0 -> isProb = true
661 // p == 0 -> isProb = false
662 // p != q -> isProb = true
663 // p == q -> isProb = false;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000664 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000665 if (!isProb)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700666 std::swap(TakenProb, UntakenProb);
Andrew Trick49371f32011-06-04 01:16:30 +0000667
Yevgeny Rouban81384872020-05-21 11:49:11 +0700668 setEdgeProbability(
669 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb}));
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000670 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000671}
672
John Brawn29bbed32018-02-23 17:17:31 +0000673// Compute the unlikely successors to the block BB in the loop L, specifically
674// those that are unlikely because this is a loop, and add them to the
675// UnlikelyBlocks set.
676static void
677computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
678 SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
679 // Sometimes in a loop we have a branch whose condition is made false by
680 // taking it. This is typically something like
681 // int n = 0;
682 // while (...) {
683 // if (++n >= MAX) {
684 // n = 0;
685 // }
686 // }
687 // In this sort of situation taking the branch means that at the very least it
688 // won't be taken again in the next iteration of the loop, so we should
689 // consider it less likely than a typical branch.
690 //
691 // We detect this by looking back through the graph of PHI nodes that sets the
692 // value that the condition depends on, and seeing if we can reach a successor
693 // block which can be determined to make the condition false.
694 //
695 // FIXME: We currently consider unlikely blocks to be half as likely as other
696 // blocks, but if we consider the example above the likelyhood is actually
697 // 1/MAX. We could therefore be more precise in how unlikely we consider
698 // blocks to be, but it would require more careful examination of the form
699 // of the comparison expression.
700 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
701 if (!BI || !BI->isConditional())
702 return;
703
704 // Check if the branch is based on an instruction compared with a constant
705 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
706 if (!CI || !isa<Instruction>(CI->getOperand(0)) ||
707 !isa<Constant>(CI->getOperand(1)))
708 return;
709
710 // Either the instruction must be a PHI, or a chain of operations involving
711 // constants that ends in a PHI which we can then collapse into a single value
712 // if the PHI value is known.
713 Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0));
714 PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
715 Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1));
716 // Collect the instructions until we hit a PHI
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000717 SmallVector<BinaryOperator *, 1> InstChain;
John Brawn29bbed32018-02-23 17:17:31 +0000718 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
719 isa<Constant>(CmpLHS->getOperand(1))) {
720 // Stop if the chain extends outside of the loop
721 if (!L->contains(CmpLHS))
722 return;
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000723 InstChain.push_back(cast<BinaryOperator>(CmpLHS));
John Brawn29bbed32018-02-23 17:17:31 +0000724 CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
725 if (CmpLHS)
726 CmpPHI = dyn_cast<PHINode>(CmpLHS);
727 }
728 if (!CmpPHI || !L->contains(CmpPHI))
729 return;
730
731 // Trace the phi node to find all values that come from successors of BB
732 SmallPtrSet<PHINode*, 8> VisitedInsts;
733 SmallVector<PHINode*, 8> WorkList;
734 WorkList.push_back(CmpPHI);
735 VisitedInsts.insert(CmpPHI);
736 while (!WorkList.empty()) {
737 PHINode *P = WorkList.back();
738 WorkList.pop_back();
739 for (BasicBlock *B : P->blocks()) {
740 // Skip blocks that aren't part of the loop
741 if (!L->contains(B))
742 continue;
743 Value *V = P->getIncomingValueForBlock(B);
744 // If the source is a PHI add it to the work list if we haven't
745 // already visited it.
746 if (PHINode *PN = dyn_cast<PHINode>(V)) {
747 if (VisitedInsts.insert(PN).second)
748 WorkList.push_back(PN);
749 continue;
750 }
751 // If this incoming value is a constant and B is a successor of BB, then
752 // we can constant-evaluate the compare to see if it makes the branch be
753 // taken or not.
754 Constant *CmpLHSConst = dyn_cast<Constant>(V);
Kazu Hirata60434982020-08-01 21:49:38 -0700755 if (!CmpLHSConst || !llvm::is_contained(successors(BB), B))
John Brawn29bbed32018-02-23 17:17:31 +0000756 continue;
757 // First collapse InstChain
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000758 for (Instruction *I : llvm::reverse(InstChain)) {
John Brawn29bbed32018-02-23 17:17:31 +0000759 CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst,
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000760 cast<Constant>(I->getOperand(1)), true);
John Brawn29bbed32018-02-23 17:17:31 +0000761 if (!CmpLHSConst)
762 break;
763 }
764 if (!CmpLHSConst)
765 continue;
766 // Now constant-evaluate the compare
767 Constant *Result = ConstantExpr::getCompare(CI->getPredicate(),
768 CmpLHSConst, CmpConst, true);
769 // If the result means we don't branch to the block then that block is
770 // unlikely.
771 if (Result &&
772 ((Result->isZeroValue() && B == BI->getSuccessor(0)) ||
773 (Result->isOneValue() && B == BI->getSuccessor(1))))
774 UnlikelyBlocks.insert(B);
775 }
776 }
777}
778
Andrew Trick49371f32011-06-04 01:16:30 +0000779// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
780// as taken, exiting edges as not-taken.
Mehdi Aminia7978772016-04-07 21:59:28 +0000781bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +0700782 const LoopInfo &LI) {
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700783 LoopBlock LB(BB, LI, *SccI.get());
784 if (!LB.belongsToLoop())
785 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000786
John Brawn29bbed32018-02-23 17:17:31 +0000787 SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks;
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700788 if (LB.getLoop())
789 computeUnlikelySuccessors(BB, LB.getLoop(), UnlikelyBlocks);
John Brawn29bbed32018-02-23 17:17:31 +0000790
Manman Rencf104462012-08-24 18:14:27 +0000791 SmallVector<unsigned, 8> BackEdges;
792 SmallVector<unsigned, 8> ExitingEdges;
793 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
John Brawn29bbed32018-02-23 17:17:31 +0000794 SmallVector<unsigned, 8> UnlikelyEdges;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000795
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700796 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700797 LoopBlock SuccLB(*I, LI, *SccI.get());
798 LoopEdge Edge(LB, SuccLB);
799 bool IsUnlikelyEdge =
800 LB.getLoop() && (UnlikelyBlocks.find(*I) != UnlikelyBlocks.end());
801
802 if (IsUnlikelyEdge)
803 UnlikelyEdges.push_back(I.getSuccessorIndex());
804 else if (isLoopExitingEdge(Edge))
805 ExitingEdges.push_back(I.getSuccessorIndex());
806 else if (isLoopBackEdge(Edge))
807 BackEdges.push_back(I.getSuccessorIndex());
808 else {
809 InEdges.push_back(I.getSuccessorIndex());
Geoff Berryeed65312017-11-01 15:16:50 +0000810 }
Andrew Trick49371f32011-06-04 01:16:30 +0000811 }
812
John Brawn29bbed32018-02-23 17:17:31 +0000813 if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty())
Akira Hatanaka5638b892014-04-14 16:56:19 +0000814 return false;
815
Cong Houe93b8e12015-12-22 18:56:14 +0000816 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
817 // normalize them so that they sum up to one.
Cong Houe93b8e12015-12-22 18:56:14 +0000818 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
819 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
John Brawn29bbed32018-02-23 17:17:31 +0000820 (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) +
Cong Houe93b8e12015-12-22 18:56:14 +0000821 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
Andrew Trick49371f32011-06-04 01:16:30 +0000822
Yevgeny Rouban81384872020-05-21 11:49:11 +0700823 SmallVector<BranchProbability, 4> EdgeProbabilities(
824 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000825 if (uint32_t numBackEdges = BackEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000826 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
827 auto Prob = TakenProb / numBackEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000828 for (unsigned SuccIdx : BackEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700829 EdgeProbabilities[SuccIdx] = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000830 }
831
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000832 if (uint32_t numInEdges = InEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000833 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
834 auto Prob = TakenProb / numInEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000835 for (unsigned SuccIdx : InEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700836 EdgeProbabilities[SuccIdx] = Prob;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000837 }
838
Chandler Carruth32f46e72011-10-25 09:47:41 +0000839 if (uint32_t numExitingEdges = ExitingEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000840 BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT,
841 Denom);
842 auto Prob = NotTakenProb / numExitingEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000843 for (unsigned SuccIdx : ExitingEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700844 EdgeProbabilities[SuccIdx] = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000845 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000846
John Brawn29bbed32018-02-23 17:17:31 +0000847 if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) {
848 BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT,
849 Denom);
850 auto Prob = UnlikelyProb / numUnlikelyEdges;
851 for (unsigned SuccIdx : UnlikelyEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700852 EdgeProbabilities[SuccIdx] = Prob;
John Brawn29bbed32018-02-23 17:17:31 +0000853 }
854
Yevgeny Rouban81384872020-05-21 11:49:11 +0700855 setEdgeProbability(BB, EdgeProbabilities);
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000856 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000857}
858
John Brawnda4a68a2017-06-08 09:44:40 +0000859bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
860 const TargetLibraryInfo *TLI) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000861 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000862 if (!BI || !BI->isConditional())
863 return false;
864
865 Value *Cond = BI->getCondition();
866 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
867 if (!CI)
868 return false;
869
Sam Parker0b53e842019-02-15 11:50:21 +0000870 auto GetConstantInt = [](Value *V) {
871 if (auto *I = dyn_cast<BitCastInst>(V))
872 return dyn_cast<ConstantInt>(I->getOperand(0));
873 return dyn_cast<ConstantInt>(V);
874 };
875
Jakub Staszak17af66a2011-07-31 03:27:24 +0000876 Value *RHS = CI->getOperand(1);
Sam Parker0b53e842019-02-15 11:50:21 +0000877 ConstantInt *CV = GetConstantInt(RHS);
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000878 if (!CV)
Jakub Staszak17af66a2011-07-31 03:27:24 +0000879 return false;
880
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000881 // If the LHS is the result of AND'ing a value with a single bit bitmask,
882 // we don't have information about probabilities.
883 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
884 if (LHS->getOpcode() == Instruction::And)
885 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
Craig Topper4e22ee62017-08-04 16:59:29 +0000886 if (AndRHS->getValue().isPowerOf2())
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000887 return false;
888
John Brawnda4a68a2017-06-08 09:44:40 +0000889 // Check if the LHS is the return value of a library function
890 LibFunc Func = NumLibFuncs;
891 if (TLI)
892 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
893 if (Function *CalledFn = Call->getCalledFunction())
894 TLI->getLibFunc(*CalledFn, Func);
895
Jakub Staszak17af66a2011-07-31 03:27:24 +0000896 bool isProb;
John Brawnda4a68a2017-06-08 09:44:40 +0000897 if (Func == LibFunc_strcasecmp ||
898 Func == LibFunc_strcmp ||
899 Func == LibFunc_strncasecmp ||
900 Func == LibFunc_strncmp ||
901 Func == LibFunc_memcmp) {
902 // 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
Cong Houe93b8e12015-12-22 18:56:14 +0000966 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
967 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
Yevgeny Rouban81384872020-05-21 11:49:11 +0700968 BranchProbability UntakenProb(ZH_NONTAKEN_WEIGHT,
969 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
970 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
Alina Sbirlea3abcbf92020-03-10 11:33:02 -07001070 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Mehdi Aminia7978772016-04-07 21:59:28 +00001071 const BasicBlock *Succ = *I;
Cong Houe93b8e12015-12-22 18:56:14 +00001072 auto Prob = getEdgeProbability(BB, Succ);
1073 if (Prob > MaxProb) {
1074 MaxProb = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +00001075 MaxSucc = Succ;
1076 }
1077 }
1078
Benjamin Kramer929f53f2011-10-23 11:19:14 +00001079 // Hot probability is at least 4/5 = 80%
Cong Houe93b8e12015-12-22 18:56:14 +00001080 if (MaxProb > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +00001081 return MaxSucc;
1082
Craig Topper9f008862014-04-15 04:59:12 +00001083 return nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +00001084}
1085
Cong Houe93b8e12015-12-22 18:56:14 +00001086/// Get the raw edge probability for the edge. If can't find it, return a
1087/// default probability 1/N where N is the number of successors. Here an edge is
1088/// specified using PredBlock and an
1089/// index to the successors.
1090BranchProbability
1091BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
1092 unsigned IndexInSuccessors) const {
1093 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick49371f32011-06-04 01:16:30 +00001094
Cong Houe93b8e12015-12-22 18:56:14 +00001095 if (I != Probs.end())
Andrew Trick49371f32011-06-04 01:16:30 +00001096 return I->second;
1097
Vedant Kumare0b5f862018-05-10 23:01:54 +00001098 return {1, static_cast<uint32_t>(succ_size(Src))};
Andrew Trick49371f32011-06-04 01:16:30 +00001099}
1100
Cong Houd97c1002015-12-01 05:29:22 +00001101BranchProbability
1102BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
Alina Sbirlea3abcbf92020-03-10 11:33:02 -07001103 const_succ_iterator Dst) const {
Cong Houd97c1002015-12-01 05:29:22 +00001104 return getEdgeProbability(Src, Dst.getSuccessorIndex());
1105}
1106
Cong Houe93b8e12015-12-22 18:56:14 +00001107/// Get the raw edge probability calculated for the block pair. This returns the
1108/// sum of all raw edge probabilities from Src to Dst.
1109BranchProbability
1110BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
1111 const BasicBlock *Dst) const {
1112 auto Prob = BranchProbability::getZero();
1113 bool FoundProb = false;
Evgeniy Brevnovbb0842a2020-04-29 14:08:01 +07001114 uint32_t EdgeCount = 0;
Alina Sbirlea3abcbf92020-03-10 11:33:02 -07001115 for (const_succ_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
Cong Houe93b8e12015-12-22 18:56:14 +00001116 if (*I == Dst) {
Evgeniy Brevnovbb0842a2020-04-29 14:08:01 +07001117 ++EdgeCount;
Cong Houe93b8e12015-12-22 18:56:14 +00001118 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
1119 if (MapI != Probs.end()) {
1120 FoundProb = true;
1121 Prob += MapI->second;
1122 }
1123 }
1124 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
Evgeniy Brevnovbb0842a2020-04-29 14:08:01 +07001125 return FoundProb ? Prob : BranchProbability(EdgeCount, succ_num);
Cong Houe93b8e12015-12-22 18:56:14 +00001126}
1127
1128/// Set the edge probability for a given edge specified by PredBlock and an
1129/// index to the successors.
1130void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
1131 unsigned IndexInSuccessors,
1132 BranchProbability Prob) {
1133 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001134 Handles.insert(BasicBlockCallbackVH(Src, this));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001135 LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
1136 << IndexInSuccessors << " successor probability to " << Prob
1137 << "\n");
Cong Houe93b8e12015-12-22 18:56:14 +00001138}
1139
Yevgeny Rouban81384872020-05-21 11:49:11 +07001140/// Set the edge probability for all edges at once.
1141void BranchProbabilityInfo::setEdgeProbability(
1142 const BasicBlock *Src, const SmallVectorImpl<BranchProbability> &Probs) {
1143 assert(Src->getTerminator()->getNumSuccessors() == Probs.size());
1144 if (Probs.size() == 0)
1145 return; // Nothing to set.
1146
1147 uint64_t TotalNumerator = 0;
1148 for (unsigned SuccIdx = 0; SuccIdx < Probs.size(); ++SuccIdx) {
1149 setEdgeProbability(Src, SuccIdx, Probs[SuccIdx]);
1150 TotalNumerator += Probs[SuccIdx].getNumerator();
1151 }
1152
1153 // Because of rounding errors the total probability cannot be checked to be
1154 // 1.0 exactly. That is TotalNumerator == BranchProbability::getDenominator.
1155 // Instead, every single probability in Probs must be as accurate as possible.
1156 // This results in error 1/denominator at most, thus the total absolute error
1157 // should be within Probs.size / BranchProbability::getDenominator.
1158 assert(TotalNumerator <= BranchProbability::getDenominator() + Probs.size());
1159 assert(TotalNumerator >= BranchProbability::getDenominator() - Probs.size());
1160}
1161
Andrew Trick49371f32011-06-04 01:16:30 +00001162raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +00001163BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
1164 const BasicBlock *Src,
1165 const BasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001166 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +00001167 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +00001168 << " probability is " << Prob
1169 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +00001170
1171 return OS;
1172}
Cong Houab23bfb2015-07-15 22:48:29 +00001173
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001174void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
Teresa Johnson3e5173d2020-07-10 15:25:27 -07001175 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
1176 auto MapI = Probs.find(std::make_pair(BB, I.getSuccessorIndex()));
1177 if (MapI != Probs.end())
1178 Probs.erase(MapI);
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001179 }
1180}
1181
John Brawnda4a68a2017-06-08 09:44:40 +00001182void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001183 const TargetLibraryInfo *TLI,
1184 PostDominatorTree *PDT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001185 LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
1186 << " ----\n\n");
Cong Houab23bfb2015-07-15 22:48:29 +00001187 LastF = &F; // Store the last function we ran on for printing.
1188 assert(PostDominatedByUnreachable.empty());
1189 assert(PostDominatedByColdCall.empty());
1190
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +07001191 SccI = std::make_unique<SccInfo>(F);
Geoff Berryeed65312017-11-01 15:16:50 +00001192
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001193 std::unique_ptr<PostDominatorTree> PDTPtr;
1194
1195 if (!PDT) {
1196 PDTPtr = std::make_unique<PostDominatorTree>(const_cast<Function &>(F));
1197 PDT = PDTPtr.get();
1198 }
1199
1200 computePostDominatedByUnreachable(F, PDT);
1201 computePostDominatedByColdCall(F, PDT);
Taewook Oh2da205d2019-12-02 10:15:22 -08001202
Cong Houab23bfb2015-07-15 22:48:29 +00001203 // Walk the basic blocks in post-order so that we can build up state about
1204 // the successors of a block iteratively.
1205 for (auto BB : post_order(&F.getEntryBlock())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001206 LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName()
1207 << "\n");
Serguei Katkov11d9c4f2017-04-17 06:39:47 +00001208 // If there is no at least two successors, no sense to set probability.
1209 if (BB->getTerminator()->getNumSuccessors() < 2)
1210 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001211 if (calcMetadataWeights(BB))
1212 continue;
Artur Pilipenko4d063e72018-06-08 13:03:21 +00001213 if (calcInvokeHeuristics(BB))
1214 continue;
Serguei Katkov2616bbb2017-04-17 04:33:04 +00001215 if (calcUnreachableHeuristics(BB))
1216 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001217 if (calcColdCallHeuristics(BB))
1218 continue;
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +07001219 if (calcLoopBranchHeuristics(BB, LI))
Cong Houab23bfb2015-07-15 22:48:29 +00001220 continue;
1221 if (calcPointerHeuristics(BB))
1222 continue;
John Brawnda4a68a2017-06-08 09:44:40 +00001223 if (calcZeroHeuristics(BB, TLI))
Cong Houab23bfb2015-07-15 22:48:29 +00001224 continue;
1225 if (calcFloatingPointHeuristics(BB))
1226 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001227 }
1228
1229 PostDominatedByUnreachable.clear();
1230 PostDominatedByColdCall.clear();
Evgeniy Brevnov412b3932020-07-28 19:50:40 +07001231 SccI.reset();
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +00001232
1233 if (PrintBranchProb &&
1234 (PrintBranchProbFuncName.empty() ||
1235 F.getName().equals(PrintBranchProbFuncName))) {
1236 print(dbgs());
1237 }
Cong Houab23bfb2015-07-15 22:48:29 +00001238}
1239
1240void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
1241 AnalysisUsage &AU) const {
Mikael Holmen2ca16892018-05-17 09:05:40 +00001242 // We require DT so it's available when LI is available. The LI updating code
1243 // asserts that DT is also present so if we don't make sure that we have DT
1244 // here, that assert will trigger.
1245 AU.addRequired<DominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001246 AU.addRequired<LoopInfoWrapperPass>();
John Brawnda4a68a2017-06-08 09:44:40 +00001247 AU.addRequired<TargetLibraryInfoWrapperPass>();
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001248 AU.addRequired<PostDominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001249 AU.setPreservesAll();
1250}
1251
1252bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
1253 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnson9c27b592019-09-07 03:09:36 +00001254 const TargetLibraryInfo &TLI =
1255 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001256 PostDominatorTree &PDT =
1257 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
1258 BPI.calculate(F, LI, &TLI, &PDT);
Cong Houab23bfb2015-07-15 22:48:29 +00001259 return false;
1260}
1261
1262void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
1263
1264void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
1265 const Module *) const {
1266 BPI.print(OS);
1267}
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001268
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001269AnalysisKey BranchProbabilityAnalysis::Key;
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001270BranchProbabilityInfo
Sean Silva36e0d012016-08-09 00:28:15 +00001271BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001272 BranchProbabilityInfo BPI;
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001273 BPI.calculate(F, AM.getResult<LoopAnalysis>(F),
1274 &AM.getResult<TargetLibraryAnalysis>(F),
1275 &AM.getResult<PostDominatorTreeAnalysis>(F));
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001276 return BPI;
1277}
1278
1279PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +00001280BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001281 OS << "Printing analysis results of BPI for function "
1282 << "'" << F.getName() << "':"
1283 << "\n";
1284 AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
1285 return PreservedAnalyses::all();
1286}