Eugene Zelenko | 38c02bc | 2017-07-21 21:37:46 +0000 | [diff] [blame] | 1 | //===- BranchProbabilityInfo.cpp - Branch Probability Analysis ------------===// |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // 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 Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // Loops should be simplified before this analysis. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 13 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
| 14 | #include "llvm/ADT/PostOrderIterator.h" |
Geoff Berry | eed6531 | 2017-11-01 15:16:50 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/SCCIterator.h" |
Eugene Zelenko | 38c02bc | 2017-07-21 21:37:46 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/STLExtras.h" |
| 17 | #include "llvm/ADT/SmallVector.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/LoopInfo.h" |
Taewook Oh | 2da205d | 2019-12-02 10:15:22 -0800 | [diff] [blame] | 19 | #include "llvm/Analysis/PostDominators.h" |
John Brawn | da4a68a | 2017-06-08 09:44:40 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Eugene Zelenko | 38c02bc | 2017-07-21 21:37:46 +0000 | [diff] [blame] | 21 | #include "llvm/IR/Attributes.h" |
| 22 | #include "llvm/IR/BasicBlock.h" |
Chandler Carruth | 1305dc3 | 2014-03-04 11:45:46 +0000 | [diff] [blame] | 23 | #include "llvm/IR/CFG.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 24 | #include "llvm/IR/Constants.h" |
Mikael Holmen | 2ca1689 | 2018-05-17 09:05:40 +0000 | [diff] [blame] | 25 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 26 | #include "llvm/IR/Function.h" |
Eugene Zelenko | 38c02bc | 2017-07-21 21:37:46 +0000 | [diff] [blame] | 27 | #include "llvm/IR/InstrTypes.h" |
| 28 | #include "llvm/IR/Instruction.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 29 | #include "llvm/IR/Instructions.h" |
| 30 | #include "llvm/IR/LLVMContext.h" |
| 31 | #include "llvm/IR/Metadata.h" |
Eugene Zelenko | 38c02bc | 2017-07-21 21:37:46 +0000 | [diff] [blame] | 32 | #include "llvm/IR/PassManager.h" |
| 33 | #include "llvm/IR/Type.h" |
| 34 | #include "llvm/IR/Value.h" |
Reid Kleckner | 05da2fe | 2019-11-13 13:15:01 -0800 | [diff] [blame] | 35 | #include "llvm/InitializePasses.h" |
Eugene Zelenko | 38c02bc | 2017-07-21 21:37:46 +0000 | [diff] [blame] | 36 | #include "llvm/Pass.h" |
| 37 | #include "llvm/Support/BranchProbability.h" |
| 38 | #include "llvm/Support/Casting.h" |
Reid Kleckner | 4c1a1d3 | 2019-11-14 15:15:48 -0800 | [diff] [blame] | 39 | #include "llvm/Support/CommandLine.h" |
Andrew Trick | 3d4e64b | 2011-06-11 01:05:22 +0000 | [diff] [blame] | 40 | #include "llvm/Support/Debug.h" |
Arthur Eubanks | 10f2a0d | 2020-09-30 12:11:46 -0700 | [diff] [blame^] | 41 | #include "llvm/Support/MathExtras.h" |
Benjamin Kramer | 16132e6 | 2015-03-23 18:07:13 +0000 | [diff] [blame] | 42 | #include "llvm/Support/raw_ostream.h" |
Eugene Zelenko | 38c02bc | 2017-07-21 21:37:46 +0000 | [diff] [blame] | 43 | #include <cassert> |
| 44 | #include <cstdint> |
| 45 | #include <iterator> |
| 46 | #include <utility> |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 47 | |
| 48 | using namespace llvm; |
| 49 | |
Chandler Carruth | f1221bd | 2014-04-22 02:48:03 +0000 | [diff] [blame] | 50 | #define DEBUG_TYPE "branch-prob" |
| 51 | |
Hiroshi Yamauchi | 63e17eb | 2017-08-26 00:31:00 +0000 | [diff] [blame] | 52 | static cl::opt<bool> PrintBranchProb( |
| 53 | "print-bpi", cl::init(false), cl::Hidden, |
| 54 | cl::desc("Print the branch probability info.")); |
| 55 | |
| 56 | cl::opt<std::string> PrintBranchProbFuncName( |
| 57 | "print-bpi-func-name", cl::Hidden, |
| 58 | cl::desc("The option to specify the name of the function " |
| 59 | "whose branch probability info is printed.")); |
| 60 | |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 61 | INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob", |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 62 | "Branch Probability Analysis", false, true) |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame] | 63 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
John Brawn | da4a68a | 2017-06-08 09:44:40 +0000 | [diff] [blame] | 64 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Evgeniy Brevnov | 3e68a667 | 2020-04-28 16:31:20 +0700 | [diff] [blame] | 65 | INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 66 | INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob", |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 67 | "Branch Probability Analysis", false, true) |
| 68 | |
Reid Kleckner | 05da2fe | 2019-11-13 13:15:01 -0800 | [diff] [blame] | 69 | BranchProbabilityInfoWrapperPass::BranchProbabilityInfoWrapperPass() |
| 70 | : FunctionPass(ID) { |
| 71 | initializeBranchProbabilityInfoWrapperPassPass( |
| 72 | *PassRegistry::getPassRegistry()); |
| 73 | } |
| 74 | |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 75 | char BranchProbabilityInfoWrapperPass::ID = 0; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 76 | |
Chandler Carruth | 7a0094a | 2011-10-24 01:40:45 +0000 | [diff] [blame] | 77 | // Weights are for internal use only. They are used by heuristics to help to |
| 78 | // estimate edges' probability. Example: |
| 79 | // |
| 80 | // Using "Loop Branch Heuristics" we predict weights of edges for the |
| 81 | // block BB2. |
| 82 | // ... |
| 83 | // | |
| 84 | // V |
| 85 | // BB1<-+ |
| 86 | // | | |
| 87 | // | | (Weight = 124) |
| 88 | // V | |
| 89 | // BB2--+ |
| 90 | // | |
| 91 | // | (Weight = 4) |
| 92 | // V |
| 93 | // BB3 |
| 94 | // |
| 95 | // Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875 |
| 96 | // Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125 |
| 97 | static const uint32_t LBH_TAKEN_WEIGHT = 124; |
| 98 | static const uint32_t LBH_NONTAKEN_WEIGHT = 4; |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 99 | // Unlikely edges within a loop are half as likely as other edges |
| 100 | static const uint32_t LBH_UNLIKELY_WEIGHT = 62; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 101 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 102 | /// Unreachable-terminating branch taken probability. |
Chandler Carruth | 7111f45 | 2011-10-24 12:01:08 +0000 | [diff] [blame] | 103 | /// |
Serguei Katkov | ba831f7 | 2017-05-18 06:11:56 +0000 | [diff] [blame] | 104 | /// This is the probability for a branch being taken to a block that terminates |
Chandler Carruth | 7111f45 | 2011-10-24 12:01:08 +0000 | [diff] [blame] | 105 | /// (eventually) in unreachable. These are predicted as unlikely as possible. |
Yevgeny Rouban | 07239c7 | 2020-06-02 11:28:12 +0700 | [diff] [blame] | 106 | /// All reachable probability will proportionally share the remaining part. |
Serguei Katkov | ba831f7 | 2017-05-18 06:11:56 +0000 | [diff] [blame] | 107 | static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1); |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 108 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 109 | /// Weight for a branch taken going into a cold block. |
Diego Novillo | c639953 | 2013-05-24 12:26:52 +0000 | [diff] [blame] | 110 | /// |
| 111 | /// This is the weight for a branch taken toward a block marked |
| 112 | /// cold. A block is marked cold if it's postdominated by a |
| 113 | /// block containing a call to a cold function. Cold functions |
| 114 | /// are those marked with attribute 'cold'. |
| 115 | static const uint32_t CC_TAKEN_WEIGHT = 4; |
| 116 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 117 | /// Weight for a branch not-taken into a cold block. |
Diego Novillo | c639953 | 2013-05-24 12:26:52 +0000 | [diff] [blame] | 118 | /// |
| 119 | /// This is the weight for a branch not taken toward a block marked |
| 120 | /// cold. |
| 121 | static const uint32_t CC_NONTAKEN_WEIGHT = 64; |
| 122 | |
Chandler Carruth | 7a0094a | 2011-10-24 01:40:45 +0000 | [diff] [blame] | 123 | static const uint32_t PH_TAKEN_WEIGHT = 20; |
| 124 | static const uint32_t PH_NONTAKEN_WEIGHT = 12; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 125 | |
Dávid Bolvanský | 0f14b2e | 2020-08-17 20:42:57 +0200 | [diff] [blame] | 126 | static const uint32_t ZH_TAKEN_WEIGHT = 20; |
| 127 | static const uint32_t ZH_NONTAKEN_WEIGHT = 12; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 128 | |
Chandler Carruth | 7a0094a | 2011-10-24 01:40:45 +0000 | [diff] [blame] | 129 | static const uint32_t FPH_TAKEN_WEIGHT = 20; |
| 130 | static const uint32_t FPH_NONTAKEN_WEIGHT = 12; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 131 | |
Guozhi Wei | b329e07 | 2019-09-10 17:25:11 +0000 | [diff] [blame] | 132 | /// This is the probability for an ordered floating point comparison. |
| 133 | static const uint32_t FPH_ORD_WEIGHT = 1024 * 1024 - 1; |
| 134 | /// This is the probability for an unordered floating point comparison, it means |
| 135 | /// one or two of the operands are NaN. Usually it is used to test for an |
| 136 | /// exceptional case, so the result is unlikely. |
| 137 | static const uint32_t FPH_UNO_WEIGHT = 1; |
| 138 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 139 | /// Invoke-terminating normal branch taken weight |
Bill Wendling | e1c5426 | 2012-08-15 12:22:35 +0000 | [diff] [blame] | 140 | /// |
| 141 | /// This is the weight for branching to the normal destination of an invoke |
| 142 | /// instruction. We expect this to happen most of the time. Set the weight to an |
| 143 | /// absurdly high value so that nested loops subsume it. |
| 144 | static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1; |
| 145 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 146 | /// Invoke-terminating normal branch not-taken weight. |
Bill Wendling | e1c5426 | 2012-08-15 12:22:35 +0000 | [diff] [blame] | 147 | /// |
| 148 | /// This is the weight for branching to the unwind destination of an invoke |
| 149 | /// instruction. This is essentially never taken. |
| 150 | static const uint32_t IH_NONTAKEN_WEIGHT = 1; |
| 151 | |
Evgeniy Brevnov | 3a2b05f | 2020-07-24 18:57:10 +0700 | [diff] [blame] | 152 | BranchProbabilityInfo::SccInfo::SccInfo(const Function &F) { |
| 153 | // Record SCC numbers of blocks in the CFG to identify irreducible loops. |
| 154 | // FIXME: We could only calculate this if the CFG is known to be irreducible |
| 155 | // (perhaps cache this info in LoopInfo if we can easily calculate it there?). |
| 156 | int SccNum = 0; |
| 157 | for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd(); |
| 158 | ++It, ++SccNum) { |
| 159 | // Ignore single-block SCCs since they either aren't loops or LoopInfo will |
| 160 | // catch them. |
| 161 | const std::vector<const BasicBlock *> &Scc = *It; |
| 162 | if (Scc.size() == 1) |
| 163 | continue; |
| 164 | |
| 165 | LLVM_DEBUG(dbgs() << "BPI: SCC " << SccNum << ":"); |
| 166 | for (const auto *BB : Scc) { |
| 167 | LLVM_DEBUG(dbgs() << " " << BB->getName()); |
| 168 | SccNums[BB] = SccNum; |
| 169 | calculateSccBlockType(BB, SccNum); |
| 170 | } |
| 171 | LLVM_DEBUG(dbgs() << "\n"); |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | int BranchProbabilityInfo::SccInfo::getSCCNum(const BasicBlock *BB) const { |
| 176 | auto SccIt = SccNums.find(BB); |
| 177 | if (SccIt == SccNums.end()) |
| 178 | return -1; |
| 179 | return SccIt->second; |
| 180 | } |
| 181 | |
| 182 | void BranchProbabilityInfo::SccInfo::getSccEnterBlocks( |
| 183 | int SccNum, SmallVectorImpl<BasicBlock *> &Enters) const { |
| 184 | |
| 185 | for (auto MapIt : SccBlocks[SccNum]) { |
| 186 | const auto *BB = MapIt.first; |
| 187 | if (isSCCHeader(BB, SccNum)) |
| 188 | for (const auto *Pred : predecessors(BB)) |
| 189 | if (getSCCNum(Pred) != SccNum) |
| 190 | Enters.push_back(const_cast<BasicBlock *>(BB)); |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | void BranchProbabilityInfo::SccInfo::getSccExitBlocks( |
| 195 | int SccNum, SmallVectorImpl<BasicBlock *> &Exits) const { |
| 196 | for (auto MapIt : SccBlocks[SccNum]) { |
| 197 | const auto *BB = MapIt.first; |
| 198 | if (isSCCExitingBlock(BB, SccNum)) |
| 199 | for (const auto *Succ : successors(BB)) |
| 200 | if (getSCCNum(Succ) != SccNum) |
| 201 | Exits.push_back(const_cast<BasicBlock *>(BB)); |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | uint32_t BranchProbabilityInfo::SccInfo::getSccBlockType(const BasicBlock *BB, |
| 206 | int SccNum) const { |
| 207 | assert(getSCCNum(BB) == SccNum); |
| 208 | |
| 209 | assert(SccBlocks.size() > static_cast<unsigned>(SccNum) && "Unknown SCC"); |
| 210 | const auto &SccBlockTypes = SccBlocks[SccNum]; |
| 211 | |
| 212 | auto It = SccBlockTypes.find(BB); |
| 213 | if (It != SccBlockTypes.end()) { |
| 214 | return It->second; |
| 215 | } |
| 216 | return Inner; |
| 217 | } |
| 218 | |
| 219 | void BranchProbabilityInfo::SccInfo::calculateSccBlockType(const BasicBlock *BB, |
| 220 | int SccNum) { |
| 221 | assert(getSCCNum(BB) == SccNum); |
| 222 | uint32_t BlockType = Inner; |
| 223 | |
| 224 | if (llvm::any_of(make_range(pred_begin(BB), pred_end(BB)), |
| 225 | [&](const BasicBlock *Pred) { |
| 226 | // Consider any block that is an entry point to the SCC as |
| 227 | // a header. |
| 228 | return getSCCNum(Pred) != SccNum; |
| 229 | })) |
| 230 | BlockType |= Header; |
| 231 | |
| 232 | if (llvm::any_of( |
| 233 | make_range(succ_begin(BB), succ_end(BB)), |
| 234 | [&](const BasicBlock *Succ) { return getSCCNum(Succ) != SccNum; })) |
| 235 | BlockType |= Exiting; |
| 236 | |
| 237 | // Lazily compute the set of headers for a given SCC and cache the results |
| 238 | // in the SccHeaderMap. |
| 239 | if (SccBlocks.size() <= static_cast<unsigned>(SccNum)) |
| 240 | SccBlocks.resize(SccNum + 1); |
| 241 | auto &SccBlockTypes = SccBlocks[SccNum]; |
| 242 | |
| 243 | if (BlockType != Inner) { |
| 244 | bool IsInserted; |
| 245 | std::tie(std::ignore, IsInserted) = |
| 246 | SccBlockTypes.insert(std::make_pair(BB, BlockType)); |
| 247 | assert(IsInserted && "Duplicated block in SCC"); |
| 248 | } |
| 249 | } |
| 250 | |
Evgeniy Brevnov | 02a629d | 2020-07-29 19:19:00 +0700 | [diff] [blame] | 251 | BranchProbabilityInfo::LoopBlock::LoopBlock(const BasicBlock *BB, |
| 252 | const LoopInfo &LI, |
| 253 | const SccInfo &SccI) |
| 254 | : BB(BB) { |
| 255 | LD.first = LI.getLoopFor(BB); |
| 256 | if (!LD.first) { |
| 257 | LD.second = SccI.getSCCNum(BB); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | bool BranchProbabilityInfo::isLoopEnteringEdge(const LoopEdge &Edge) const { |
| 262 | const auto &SrcBlock = Edge.first; |
| 263 | const auto &DstBlock = Edge.second; |
| 264 | return (DstBlock.getLoop() && |
| 265 | !DstBlock.getLoop()->contains(SrcBlock.getLoop())) || |
| 266 | // Assume that SCCs can't be nested. |
| 267 | (DstBlock.getSccNum() != -1 && |
| 268 | SrcBlock.getSccNum() != DstBlock.getSccNum()); |
| 269 | } |
| 270 | |
| 271 | bool BranchProbabilityInfo::isLoopExitingEdge(const LoopEdge &Edge) const { |
| 272 | return isLoopEnteringEdge({Edge.second, Edge.first}); |
| 273 | } |
| 274 | |
| 275 | bool BranchProbabilityInfo::isLoopEnteringExitingEdge( |
| 276 | const LoopEdge &Edge) const { |
| 277 | return isLoopEnteringEdge(Edge) || isLoopExitingEdge(Edge); |
| 278 | } |
| 279 | |
| 280 | bool BranchProbabilityInfo::isLoopBackEdge(const LoopEdge &Edge) const { |
| 281 | const auto &SrcBlock = Edge.first; |
| 282 | const auto &DstBlock = Edge.second; |
| 283 | return SrcBlock.belongsToSameLoop(DstBlock) && |
| 284 | ((DstBlock.getLoop() && |
| 285 | DstBlock.getLoop()->getHeader() == DstBlock.getBlock()) || |
| 286 | (DstBlock.getSccNum() != -1 && |
| 287 | SccI->isSCCHeader(DstBlock.getBlock(), DstBlock.getSccNum()))); |
| 288 | } |
| 289 | |
| 290 | void BranchProbabilityInfo::getLoopEnterBlocks( |
| 291 | const LoopBlock &LB, SmallVectorImpl<BasicBlock *> &Enters) const { |
| 292 | if (LB.getLoop()) { |
| 293 | auto *Header = LB.getLoop()->getHeader(); |
| 294 | Enters.append(pred_begin(Header), pred_end(Header)); |
| 295 | } else { |
| 296 | assert(LB.getSccNum() != -1 && "LB doesn't belong to any loop?"); |
| 297 | SccI->getSccEnterBlocks(LB.getSccNum(), Enters); |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | void BranchProbabilityInfo::getLoopExitBlocks( |
| 302 | const LoopBlock &LB, SmallVectorImpl<BasicBlock *> &Exits) const { |
| 303 | if (LB.getLoop()) { |
| 304 | LB.getLoop()->getExitBlocks(Exits); |
| 305 | } else { |
| 306 | assert(LB.getSccNum() != -1 && "LB doesn't belong to any loop?"); |
| 307 | SccI->getSccExitBlocks(LB.getSccNum(), Exits); |
| 308 | } |
| 309 | } |
| 310 | |
Taewook Oh | 2da205d | 2019-12-02 10:15:22 -0800 | [diff] [blame] | 311 | static void UpdatePDTWorklist(const BasicBlock *BB, PostDominatorTree *PDT, |
| 312 | SmallVectorImpl<const BasicBlock *> &WorkList, |
| 313 | SmallPtrSetImpl<const BasicBlock *> &TargetSet) { |
| 314 | SmallVector<BasicBlock *, 8> Descendants; |
| 315 | SmallPtrSet<const BasicBlock *, 16> NewItems; |
Chandler Carruth | 7111f45 | 2011-10-24 12:01:08 +0000 | [diff] [blame] | 316 | |
Taewook Oh | 2da205d | 2019-12-02 10:15:22 -0800 | [diff] [blame] | 317 | PDT->getDescendants(const_cast<BasicBlock *>(BB), Descendants); |
| 318 | for (auto *BB : Descendants) |
| 319 | if (TargetSet.insert(BB).second) |
| 320 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 321 | if (!TargetSet.count(*PI)) |
| 322 | NewItems.insert(*PI); |
| 323 | WorkList.insert(WorkList.end(), NewItems.begin(), NewItems.end()); |
Serguei Katkov | ecebc3d | 2017-04-12 05:42:14 +0000 | [diff] [blame] | 324 | } |
| 325 | |
Taewook Oh | 2da205d | 2019-12-02 10:15:22 -0800 | [diff] [blame] | 326 | /// Compute a set of basic blocks that are post-dominated by unreachables. |
| 327 | void BranchProbabilityInfo::computePostDominatedByUnreachable( |
| 328 | const Function &F, PostDominatorTree *PDT) { |
| 329 | SmallVector<const BasicBlock *, 8> WorkList; |
| 330 | for (auto &BB : F) { |
| 331 | const Instruction *TI = BB.getTerminator(); |
| 332 | if (TI->getNumSuccessors() == 0) { |
| 333 | if (isa<UnreachableInst>(TI) || |
| 334 | // If this block is terminated by a call to |
| 335 | // @llvm.experimental.deoptimize then treat it like an unreachable |
| 336 | // since the @llvm.experimental.deoptimize call is expected to |
| 337 | // practically never execute. |
| 338 | BB.getTerminatingDeoptimizeCall()) |
| 339 | UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByUnreachable); |
| 340 | } |
Serguei Katkov | ecebc3d | 2017-04-12 05:42:14 +0000 | [diff] [blame] | 341 | } |
| 342 | |
Taewook Oh | 2da205d | 2019-12-02 10:15:22 -0800 | [diff] [blame] | 343 | while (!WorkList.empty()) { |
| 344 | const BasicBlock *BB = WorkList.pop_back_val(); |
| 345 | if (PostDominatedByUnreachable.count(BB)) |
| 346 | continue; |
| 347 | // If the terminator is an InvokeInst, check only the normal destination |
| 348 | // block as the unwind edge of InvokeInst is also very unlikely taken. |
| 349 | if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) { |
| 350 | if (PostDominatedByUnreachable.count(II->getNormalDest())) |
| 351 | UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable); |
Serguei Katkov | ecebc3d | 2017-04-12 05:42:14 +0000 | [diff] [blame] | 352 | } |
Taewook Oh | 2da205d | 2019-12-02 10:15:22 -0800 | [diff] [blame] | 353 | // If all the successors are unreachable, BB is unreachable as well. |
| 354 | else if (!successors(BB).empty() && |
| 355 | llvm::all_of(successors(BB), [this](const BasicBlock *Succ) { |
| 356 | return PostDominatedByUnreachable.count(Succ); |
| 357 | })) |
| 358 | UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable); |
| 359 | } |
| 360 | } |
Serguei Katkov | ecebc3d | 2017-04-12 05:42:14 +0000 | [diff] [blame] | 361 | |
Taewook Oh | 2da205d | 2019-12-02 10:15:22 -0800 | [diff] [blame] | 362 | /// compute a set of basic blocks that are post-dominated by ColdCalls. |
| 363 | void BranchProbabilityInfo::computePostDominatedByColdCall( |
| 364 | const Function &F, PostDominatorTree *PDT) { |
| 365 | SmallVector<const BasicBlock *, 8> WorkList; |
| 366 | for (auto &BB : F) |
| 367 | for (auto &I : BB) |
| 368 | if (const CallInst *CI = dyn_cast<CallInst>(&I)) |
| 369 | if (CI->hasFnAttr(Attribute::Cold)) |
| 370 | UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByColdCall); |
| 371 | |
| 372 | while (!WorkList.empty()) { |
| 373 | const BasicBlock *BB = WorkList.pop_back_val(); |
| 374 | |
| 375 | // If the terminator is an InvokeInst, check only the normal destination |
| 376 | // block as the unwind edge of InvokeInst is also very unlikely taken. |
| 377 | if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) { |
| 378 | if (PostDominatedByColdCall.count(II->getNormalDest())) |
| 379 | UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall); |
| 380 | } |
| 381 | // If all of successor are post dominated then BB is also done. |
| 382 | else if (!successors(BB).empty() && |
| 383 | llvm::all_of(successors(BB), [this](const BasicBlock *Succ) { |
| 384 | return PostDominatedByColdCall.count(Succ); |
| 385 | })) |
| 386 | UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall); |
| 387 | } |
Serguei Katkov | ecebc3d | 2017-04-12 05:42:14 +0000 | [diff] [blame] | 388 | } |
| 389 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 390 | /// Calculate edge weights for successors lead to unreachable. |
Serguei Katkov | ecebc3d | 2017-04-12 05:42:14 +0000 | [diff] [blame] | 391 | /// |
| 392 | /// Predict that a successor which leads necessarily to an |
| 393 | /// unreachable-terminated block as extremely unlikely. |
| 394 | bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 395 | const Instruction *TI = BB->getTerminator(); |
Artur Pilipenko | 4d063e7 | 2018-06-08 13:03:21 +0000 | [diff] [blame] | 396 | (void) TI; |
Serguei Katkov | 11d9c4f | 2017-04-17 06:39:47 +0000 | [diff] [blame] | 397 | assert(TI->getNumSuccessors() > 1 && "expected more than one successor!"); |
Artur Pilipenko | 4d063e7 | 2018-06-08 13:03:21 +0000 | [diff] [blame] | 398 | assert(!isa<InvokeInst>(TI) && |
| 399 | "Invokes should have already been handled by calcInvokeHeuristics"); |
Serguei Katkov | ecebc3d | 2017-04-12 05:42:14 +0000 | [diff] [blame] | 400 | |
Manman Ren | cf10446 | 2012-08-24 18:14:27 +0000 | [diff] [blame] | 401 | SmallVector<unsigned, 4> UnreachableEdges; |
| 402 | SmallVector<unsigned, 4> ReachableEdges; |
Chandler Carruth | 7111f45 | 2011-10-24 12:01:08 +0000 | [diff] [blame] | 403 | |
Alina Sbirlea | 3abcbf9 | 2020-03-10 11:33:02 -0700 | [diff] [blame] | 404 | for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) |
Chandler Carruth | 7111f45 | 2011-10-24 12:01:08 +0000 | [diff] [blame] | 405 | if (PostDominatedByUnreachable.count(*I)) |
Manman Ren | cf10446 | 2012-08-24 18:14:27 +0000 | [diff] [blame] | 406 | UnreachableEdges.push_back(I.getSuccessorIndex()); |
Chandler Carruth | 7111f45 | 2011-10-24 12:01:08 +0000 | [diff] [blame] | 407 | else |
Manman Ren | cf10446 | 2012-08-24 18:14:27 +0000 | [diff] [blame] | 408 | ReachableEdges.push_back(I.getSuccessorIndex()); |
Chandler Carruth | 7111f45 | 2011-10-24 12:01:08 +0000 | [diff] [blame] | 409 | |
Serguei Katkov | 11d9c4f | 2017-04-17 06:39:47 +0000 | [diff] [blame] | 410 | // Skip probabilities if all were reachable. |
| 411 | if (UnreachableEdges.empty()) |
Serguei Katkov | ecebc3d | 2017-04-12 05:42:14 +0000 | [diff] [blame] | 412 | return false; |
Jun Bum Lim | a23e5f7 | 2015-12-21 22:00:51 +0000 | [diff] [blame] | 413 | |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 414 | SmallVector<BranchProbability, 4> EdgeProbabilities( |
| 415 | BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown()); |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 416 | if (ReachableEdges.empty()) { |
| 417 | BranchProbability Prob(1, UnreachableEdges.size()); |
| 418 | for (unsigned SuccIdx : UnreachableEdges) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 419 | EdgeProbabilities[SuccIdx] = Prob; |
| 420 | setEdgeProbability(BB, EdgeProbabilities); |
Chandler Carruth | 7111f45 | 2011-10-24 12:01:08 +0000 | [diff] [blame] | 421 | return true; |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 422 | } |
| 423 | |
Serguei Katkov | ba831f7 | 2017-05-18 06:11:56 +0000 | [diff] [blame] | 424 | auto UnreachableProb = UR_TAKEN_PROB; |
| 425 | auto ReachableProb = |
| 426 | (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) / |
| 427 | ReachableEdges.size(); |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 428 | |
| 429 | for (unsigned SuccIdx : UnreachableEdges) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 430 | EdgeProbabilities[SuccIdx] = UnreachableProb; |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 431 | for (unsigned SuccIdx : ReachableEdges) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 432 | EdgeProbabilities[SuccIdx] = ReachableProb; |
Chandler Carruth | 7111f45 | 2011-10-24 12:01:08 +0000 | [diff] [blame] | 433 | |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 434 | setEdgeProbability(BB, EdgeProbabilities); |
Chandler Carruth | 7111f45 | 2011-10-24 12:01:08 +0000 | [diff] [blame] | 435 | return true; |
| 436 | } |
| 437 | |
Arthur Eubanks | 10f2a0d | 2020-09-30 12:11:46 -0700 | [diff] [blame^] | 438 | // Scales all values in Weights so that the total fits in 64 bits. Returns the |
| 439 | // total. |
| 440 | // FIXME: only scale by the minimum necessary to fit the total within 64 bits. |
| 441 | static uint64_t ScaleWeights(MutableArrayRef<uint64_t> Weights) { |
| 442 | uint64_t Total = 0; |
| 443 | bool Overflowed = false; |
| 444 | for (uint64_t W : Weights) { |
| 445 | Total = SaturatingAdd(Total, W, &Overflowed); |
| 446 | if (Overflowed) |
| 447 | break; |
| 448 | } |
| 449 | if (Overflowed) { |
| 450 | uint64_t ScaledTotal = 0; |
| 451 | for (uint64_t &W : Weights) { |
| 452 | W /= UINT32_MAX; |
| 453 | ScaledTotal += W; |
| 454 | } |
| 455 | return ScaledTotal; |
| 456 | } |
| 457 | return Total; |
| 458 | } |
| 459 | |
Chandler Carruth | d27a7a9 | 2011-10-19 10:30:30 +0000 | [diff] [blame] | 460 | // Propagate existing explicit probabilities from either profile data or |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 461 | // 'expect' intrinsic processing. Examine metadata against unreachable |
| 462 | // heuristic. The probability of the edge coming to unreachable block is |
| 463 | // set to min of metadata and unreachable heuristic. |
Mehdi Amini | a797877 | 2016-04-07 21:59:28 +0000 | [diff] [blame] | 464 | bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 465 | const Instruction *TI = BB->getTerminator(); |
Serguei Katkov | 11d9c4f | 2017-04-17 06:39:47 +0000 | [diff] [blame] | 466 | assert(TI->getNumSuccessors() > 1 && "expected more than one successor!"); |
Yevgeny Rouban | dcfa78a | 2020-06-04 15:34:14 +0700 | [diff] [blame] | 467 | if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI) || |
| 468 | isa<InvokeInst>(TI))) |
Chandler Carruth | d27a7a9 | 2011-10-19 10:30:30 +0000 | [diff] [blame] | 469 | return false; |
| 470 | |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 471 | MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof); |
Chandler Carruth | deac50c | 2011-10-19 10:32:19 +0000 | [diff] [blame] | 472 | if (!WeightsNode) |
Chandler Carruth | d27a7a9 | 2011-10-19 10:30:30 +0000 | [diff] [blame] | 473 | return false; |
| 474 | |
Diego Novillo | de5b801 | 2015-05-07 17:22:06 +0000 | [diff] [blame] | 475 | // Check that the number of successors is manageable. |
| 476 | assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors"); |
| 477 | |
Chandler Carruth | deac50c | 2011-10-19 10:32:19 +0000 | [diff] [blame] | 478 | // Ensure there are weights for all of the successors. Note that the first |
| 479 | // operand to the metadata node is a name, not a weight. |
| 480 | if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1) |
Chandler Carruth | d27a7a9 | 2011-10-19 10:30:30 +0000 | [diff] [blame] | 481 | return false; |
| 482 | |
Diego Novillo | de5b801 | 2015-05-07 17:22:06 +0000 | [diff] [blame] | 483 | // Build up the final weights that will be used in a temporary buffer. |
Arthur Eubanks | 10f2a0d | 2020-09-30 12:11:46 -0700 | [diff] [blame^] | 484 | SmallVector<uint64_t, 2> Weights; |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 485 | SmallVector<unsigned, 2> UnreachableIdxs; |
| 486 | SmallVector<unsigned, 2> ReachableIdxs; |
Chandler Carruth | deac50c | 2011-10-19 10:32:19 +0000 | [diff] [blame] | 487 | Weights.reserve(TI->getNumSuccessors()); |
Yevgeny Rouban | 3bb0d95 | 2020-06-02 10:55:27 +0700 | [diff] [blame] | 488 | for (unsigned I = 1, E = WeightsNode->getNumOperands(); I != E; ++I) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 489 | ConstantInt *Weight = |
Yevgeny Rouban | 3bb0d95 | 2020-06-02 10:55:27 +0700 | [diff] [blame] | 490 | mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(I)); |
Chandler Carruth | deac50c | 2011-10-19 10:32:19 +0000 | [diff] [blame] | 491 | if (!Weight) |
| 492 | return false; |
Arthur Eubanks | 10f2a0d | 2020-09-30 12:11:46 -0700 | [diff] [blame^] | 493 | // TODO: remove scaling by UINT32_MAX and use full uint64_t range. |
| 494 | uint64_t WeightVal = Weight->getZExtValue(); |
| 495 | Weights.push_back(WeightVal); |
| 496 | // WeightSum += WeightVal; |
Yevgeny Rouban | 3bb0d95 | 2020-06-02 10:55:27 +0700 | [diff] [blame] | 497 | if (PostDominatedByUnreachable.count(TI->getSuccessor(I - 1))) |
| 498 | UnreachableIdxs.push_back(I - 1); |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 499 | else |
Yevgeny Rouban | 3bb0d95 | 2020-06-02 10:55:27 +0700 | [diff] [blame] | 500 | ReachableIdxs.push_back(I - 1); |
Chandler Carruth | deac50c | 2011-10-19 10:32:19 +0000 | [diff] [blame] | 501 | } |
| 502 | assert(Weights.size() == TI->getNumSuccessors() && "Checked above"); |
Diego Novillo | de5b801 | 2015-05-07 17:22:06 +0000 | [diff] [blame] | 503 | |
Arthur Eubanks | 10f2a0d | 2020-09-30 12:11:46 -0700 | [diff] [blame^] | 504 | uint64_t WeightSum = ScaleWeights(Weights); |
Cong Hou | 6a2c71a | 2015-12-22 23:45:55 +0000 | [diff] [blame] | 505 | |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 506 | if (WeightSum == 0 || ReachableIdxs.size() == 0) { |
Yevgeny Rouban | 3bb0d95 | 2020-06-02 10:55:27 +0700 | [diff] [blame] | 507 | for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) |
| 508 | Weights[I] = 1; |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 509 | WeightSum = TI->getNumSuccessors(); |
Cong Hou | 6a2c71a | 2015-12-22 23:45:55 +0000 | [diff] [blame] | 510 | } |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 511 | |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 512 | // Set the probability. |
| 513 | SmallVector<BranchProbability, 2> BP; |
Yevgeny Rouban | 3bb0d95 | 2020-06-02 10:55:27 +0700 | [diff] [blame] | 514 | for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) |
Arthur Eubanks | 10f2a0d | 2020-09-30 12:11:46 -0700 | [diff] [blame^] | 515 | BP.push_back( |
| 516 | BranchProbability::getBranchProbability(Weights[I], WeightSum)); |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 517 | |
| 518 | // Examine the metadata against unreachable heuristic. |
| 519 | // If the unreachable heuristic is more strong then we use it for this edge. |
Yevgeny Rouban | 07239c7 | 2020-06-02 11:28:12 +0700 | [diff] [blame] | 520 | if (UnreachableIdxs.size() == 0 || ReachableIdxs.size() == 0) { |
| 521 | setEdgeProbability(BB, BP); |
| 522 | return true; |
| 523 | } |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 524 | |
Yevgeny Rouban | 07239c7 | 2020-06-02 11:28:12 +0700 | [diff] [blame] | 525 | auto UnreachableProb = UR_TAKEN_PROB; |
| 526 | for (auto I : UnreachableIdxs) |
| 527 | if (UnreachableProb < BP[I]) { |
| 528 | BP[I] = UnreachableProb; |
| 529 | } |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 530 | |
Yevgeny Rouban | 07239c7 | 2020-06-02 11:28:12 +0700 | [diff] [blame] | 531 | // Sum of all edge probabilities must be 1.0. If we modified the probability |
| 532 | // of some edges then we must distribute the introduced difference over the |
| 533 | // reachable blocks. |
| 534 | // |
| 535 | // Proportional distribution: the relation between probabilities of the |
| 536 | // reachable edges is kept unchanged. That is for any reachable edges i and j: |
| 537 | // newBP[i] / newBP[j] == oldBP[i] / oldBP[j] => |
| 538 | // newBP[i] / oldBP[i] == newBP[j] / oldBP[j] == K |
| 539 | // Where K is independent of i,j. |
| 540 | // newBP[i] == oldBP[i] * K |
| 541 | // We need to find K. |
| 542 | // Make sum of all reachables of the left and right parts: |
| 543 | // sum_of_reachable(newBP) == K * sum_of_reachable(oldBP) |
| 544 | // Sum of newBP must be equal to 1.0: |
| 545 | // sum_of_reachable(newBP) + sum_of_unreachable(newBP) == 1.0 => |
| 546 | // sum_of_reachable(newBP) = 1.0 - sum_of_unreachable(newBP) |
| 547 | // Where sum_of_unreachable(newBP) is what has been just changed. |
| 548 | // Finally: |
| 549 | // K == sum_of_reachable(newBP) / sum_of_reachable(oldBP) => |
| 550 | // K == (1.0 - sum_of_unreachable(newBP)) / sum_of_reachable(oldBP) |
| 551 | BranchProbability NewUnreachableSum = BranchProbability::getZero(); |
| 552 | for (auto I : UnreachableIdxs) |
| 553 | NewUnreachableSum += BP[I]; |
| 554 | |
| 555 | BranchProbability NewReachableSum = |
| 556 | BranchProbability::getOne() - NewUnreachableSum; |
| 557 | |
| 558 | BranchProbability OldReachableSum = BranchProbability::getZero(); |
| 559 | for (auto I : ReachableIdxs) |
| 560 | OldReachableSum += BP[I]; |
| 561 | |
| 562 | if (OldReachableSum != NewReachableSum) { // Anything to dsitribute? |
| 563 | if (OldReachableSum.isZero()) { |
| 564 | // If all oldBP[i] are zeroes then the proportional distribution results |
| 565 | // in all zero probabilities and the error stays big. In this case we |
| 566 | // evenly spread NewReachableSum over the reachable edges. |
| 567 | BranchProbability PerEdge = NewReachableSum / ReachableIdxs.size(); |
Yevgeny Rouban | 3bb0d95 | 2020-06-02 10:55:27 +0700 | [diff] [blame] | 568 | for (auto I : ReachableIdxs) |
Yevgeny Rouban | 07239c7 | 2020-06-02 11:28:12 +0700 | [diff] [blame] | 569 | BP[I] = PerEdge; |
| 570 | } else { |
| 571 | for (auto I : ReachableIdxs) { |
| 572 | // We use uint64_t to avoid double rounding error of the following |
| 573 | // calculation: BP[i] = BP[i] * NewReachableSum / OldReachableSum |
| 574 | // The formula is taken from the private constructor |
| 575 | // BranchProbability(uint32_t Numerator, uint32_t Denominator) |
| 576 | uint64_t Mul = static_cast<uint64_t>(NewReachableSum.getNumerator()) * |
| 577 | BP[I].getNumerator(); |
| 578 | uint32_t Div = static_cast<uint32_t>( |
| 579 | divideNearest(Mul, OldReachableSum.getNumerator())); |
| 580 | BP[I] = BranchProbability::getRaw(Div); |
| 581 | } |
| 582 | } |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 583 | } |
| 584 | |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 585 | setEdgeProbability(BB, BP); |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 586 | |
Chandler Carruth | d27a7a9 | 2011-10-19 10:30:30 +0000 | [diff] [blame] | 587 | return true; |
| 588 | } |
| 589 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 590 | /// Calculate edge weights for edges leading to cold blocks. |
Diego Novillo | c639953 | 2013-05-24 12:26:52 +0000 | [diff] [blame] | 591 | /// |
| 592 | /// A cold block is one post-dominated by a block with a call to a |
| 593 | /// cold function. Those edges are unlikely to be taken, so we give |
| 594 | /// them relatively low weight. |
| 595 | /// |
| 596 | /// Return true if we could compute the weights for cold edges. |
| 597 | /// Return false, otherwise. |
Mehdi Amini | a797877 | 2016-04-07 21:59:28 +0000 | [diff] [blame] | 598 | bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 599 | const Instruction *TI = BB->getTerminator(); |
Artur Pilipenko | 4d063e7 | 2018-06-08 13:03:21 +0000 | [diff] [blame] | 600 | (void) TI; |
Serguei Katkov | 11d9c4f | 2017-04-17 06:39:47 +0000 | [diff] [blame] | 601 | assert(TI->getNumSuccessors() > 1 && "expected more than one successor!"); |
Artur Pilipenko | 4d063e7 | 2018-06-08 13:03:21 +0000 | [diff] [blame] | 602 | assert(!isa<InvokeInst>(TI) && |
| 603 | "Invokes should have already been handled by calcInvokeHeuristics"); |
Diego Novillo | c639953 | 2013-05-24 12:26:52 +0000 | [diff] [blame] | 604 | |
| 605 | // Determine which successors are post-dominated by a cold block. |
| 606 | SmallVector<unsigned, 4> ColdEdges; |
Diego Novillo | c639953 | 2013-05-24 12:26:52 +0000 | [diff] [blame] | 607 | SmallVector<unsigned, 4> NormalEdges; |
Alina Sbirlea | 3abcbf9 | 2020-03-10 11:33:02 -0700 | [diff] [blame] | 608 | for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) |
Diego Novillo | c639953 | 2013-05-24 12:26:52 +0000 | [diff] [blame] | 609 | if (PostDominatedByColdCall.count(*I)) |
| 610 | ColdEdges.push_back(I.getSuccessorIndex()); |
| 611 | else |
| 612 | NormalEdges.push_back(I.getSuccessorIndex()); |
| 613 | |
Serguei Katkov | 11d9c4f | 2017-04-17 06:39:47 +0000 | [diff] [blame] | 614 | // Skip probabilities if no cold edges. |
| 615 | if (ColdEdges.empty()) |
Diego Novillo | c639953 | 2013-05-24 12:26:52 +0000 | [diff] [blame] | 616 | return false; |
| 617 | |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 618 | SmallVector<BranchProbability, 4> EdgeProbabilities( |
| 619 | BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown()); |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 620 | if (NormalEdges.empty()) { |
| 621 | BranchProbability Prob(1, ColdEdges.size()); |
| 622 | for (unsigned SuccIdx : ColdEdges) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 623 | EdgeProbabilities[SuccIdx] = Prob; |
| 624 | setEdgeProbability(BB, EdgeProbabilities); |
Diego Novillo | c639953 | 2013-05-24 12:26:52 +0000 | [diff] [blame] | 625 | return true; |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 626 | } |
| 627 | |
Vedant Kumar | a4bd146 | 2016-12-17 01:02:08 +0000 | [diff] [blame] | 628 | auto ColdProb = BranchProbability::getBranchProbability( |
| 629 | CC_TAKEN_WEIGHT, |
| 630 | (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size())); |
| 631 | auto NormalProb = BranchProbability::getBranchProbability( |
| 632 | CC_NONTAKEN_WEIGHT, |
| 633 | (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size())); |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 634 | |
| 635 | for (unsigned SuccIdx : ColdEdges) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 636 | EdgeProbabilities[SuccIdx] = ColdProb; |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 637 | for (unsigned SuccIdx : NormalEdges) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 638 | EdgeProbabilities[SuccIdx] = NormalProb; |
Diego Novillo | c639953 | 2013-05-24 12:26:52 +0000 | [diff] [blame] | 639 | |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 640 | setEdgeProbability(BB, EdgeProbabilities); |
Diego Novillo | c639953 | 2013-05-24 12:26:52 +0000 | [diff] [blame] | 641 | return true; |
| 642 | } |
| 643 | |
Vedant Kumar | 1a8456d | 2018-03-02 18:57:02 +0000 | [diff] [blame] | 644 | // Calculate Edge Weights using "Pointer Heuristics". Predict a comparison |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 645 | // between two pointer or pointer and NULL will fail. |
Mehdi Amini | a797877 | 2016-04-07 21:59:28 +0000 | [diff] [blame] | 646 | bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) { |
| 647 | const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 648 | if (!BI || !BI->isConditional()) |
Jakub Staszak | d07b2e1 | 2011-07-28 21:45:07 +0000 | [diff] [blame] | 649 | return false; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 650 | |
| 651 | Value *Cond = BI->getCondition(); |
| 652 | ICmpInst *CI = dyn_cast<ICmpInst>(Cond); |
Jakub Staszak | abb236f | 2011-07-15 20:51:06 +0000 | [diff] [blame] | 653 | if (!CI || !CI->isEquality()) |
Jakub Staszak | d07b2e1 | 2011-07-28 21:45:07 +0000 | [diff] [blame] | 654 | return false; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 655 | |
| 656 | Value *LHS = CI->getOperand(0); |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 657 | |
| 658 | if (!LHS->getType()->isPointerTy()) |
Jakub Staszak | d07b2e1 | 2011-07-28 21:45:07 +0000 | [diff] [blame] | 659 | return false; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 660 | |
Nick Lewycky | 75b2053 | 2011-06-04 02:07:10 +0000 | [diff] [blame] | 661 | assert(CI->getOperand(1)->getType()->isPointerTy()); |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 662 | |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 663 | BranchProbability TakenProb(PH_TAKEN_WEIGHT, |
| 664 | PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT); |
| 665 | BranchProbability UntakenProb(PH_NONTAKEN_WEIGHT, |
| 666 | PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT); |
| 667 | |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 668 | // p != 0 -> isProb = true |
| 669 | // p == 0 -> isProb = false |
| 670 | // p != q -> isProb = true |
| 671 | // p == q -> isProb = false; |
Jakub Staszak | abb236f | 2011-07-15 20:51:06 +0000 | [diff] [blame] | 672 | bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 673 | if (!isProb) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 674 | std::swap(TakenProb, UntakenProb); |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 675 | |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 676 | setEdgeProbability( |
| 677 | BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb})); |
Jakub Staszak | d07b2e1 | 2011-07-28 21:45:07 +0000 | [diff] [blame] | 678 | return true; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 679 | } |
| 680 | |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 681 | // Compute the unlikely successors to the block BB in the loop L, specifically |
| 682 | // those that are unlikely because this is a loop, and add them to the |
| 683 | // UnlikelyBlocks set. |
| 684 | static void |
| 685 | computeUnlikelySuccessors(const BasicBlock *BB, Loop *L, |
| 686 | SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) { |
| 687 | // Sometimes in a loop we have a branch whose condition is made false by |
| 688 | // taking it. This is typically something like |
| 689 | // int n = 0; |
| 690 | // while (...) { |
| 691 | // if (++n >= MAX) { |
| 692 | // n = 0; |
| 693 | // } |
| 694 | // } |
| 695 | // In this sort of situation taking the branch means that at the very least it |
| 696 | // won't be taken again in the next iteration of the loop, so we should |
| 697 | // consider it less likely than a typical branch. |
| 698 | // |
| 699 | // We detect this by looking back through the graph of PHI nodes that sets the |
| 700 | // value that the condition depends on, and seeing if we can reach a successor |
| 701 | // block which can be determined to make the condition false. |
| 702 | // |
| 703 | // FIXME: We currently consider unlikely blocks to be half as likely as other |
| 704 | // blocks, but if we consider the example above the likelyhood is actually |
| 705 | // 1/MAX. We could therefore be more precise in how unlikely we consider |
| 706 | // blocks to be, but it would require more careful examination of the form |
| 707 | // of the comparison expression. |
| 708 | const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 709 | if (!BI || !BI->isConditional()) |
| 710 | return; |
| 711 | |
| 712 | // Check if the branch is based on an instruction compared with a constant |
| 713 | CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition()); |
| 714 | if (!CI || !isa<Instruction>(CI->getOperand(0)) || |
| 715 | !isa<Constant>(CI->getOperand(1))) |
| 716 | return; |
| 717 | |
| 718 | // Either the instruction must be a PHI, or a chain of operations involving |
| 719 | // constants that ends in a PHI which we can then collapse into a single value |
| 720 | // if the PHI value is known. |
| 721 | Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0)); |
| 722 | PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS); |
| 723 | Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1)); |
| 724 | // Collect the instructions until we hit a PHI |
Benjamin Kramer | 7f68a30 | 2018-06-15 21:06:43 +0000 | [diff] [blame] | 725 | SmallVector<BinaryOperator *, 1> InstChain; |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 726 | while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) && |
| 727 | isa<Constant>(CmpLHS->getOperand(1))) { |
| 728 | // Stop if the chain extends outside of the loop |
| 729 | if (!L->contains(CmpLHS)) |
| 730 | return; |
Benjamin Kramer | 7f68a30 | 2018-06-15 21:06:43 +0000 | [diff] [blame] | 731 | InstChain.push_back(cast<BinaryOperator>(CmpLHS)); |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 732 | CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0)); |
| 733 | if (CmpLHS) |
| 734 | CmpPHI = dyn_cast<PHINode>(CmpLHS); |
| 735 | } |
| 736 | if (!CmpPHI || !L->contains(CmpPHI)) |
| 737 | return; |
| 738 | |
| 739 | // Trace the phi node to find all values that come from successors of BB |
| 740 | SmallPtrSet<PHINode*, 8> VisitedInsts; |
| 741 | SmallVector<PHINode*, 8> WorkList; |
| 742 | WorkList.push_back(CmpPHI); |
| 743 | VisitedInsts.insert(CmpPHI); |
| 744 | while (!WorkList.empty()) { |
| 745 | PHINode *P = WorkList.back(); |
| 746 | WorkList.pop_back(); |
| 747 | for (BasicBlock *B : P->blocks()) { |
| 748 | // Skip blocks that aren't part of the loop |
| 749 | if (!L->contains(B)) |
| 750 | continue; |
| 751 | Value *V = P->getIncomingValueForBlock(B); |
| 752 | // If the source is a PHI add it to the work list if we haven't |
| 753 | // already visited it. |
| 754 | if (PHINode *PN = dyn_cast<PHINode>(V)) { |
| 755 | if (VisitedInsts.insert(PN).second) |
| 756 | WorkList.push_back(PN); |
| 757 | continue; |
| 758 | } |
| 759 | // If this incoming value is a constant and B is a successor of BB, then |
| 760 | // we can constant-evaluate the compare to see if it makes the branch be |
| 761 | // taken or not. |
| 762 | Constant *CmpLHSConst = dyn_cast<Constant>(V); |
Kazu Hirata | 6043498 | 2020-08-01 21:49:38 -0700 | [diff] [blame] | 763 | if (!CmpLHSConst || !llvm::is_contained(successors(BB), B)) |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 764 | continue; |
| 765 | // First collapse InstChain |
Benjamin Kramer | 7f68a30 | 2018-06-15 21:06:43 +0000 | [diff] [blame] | 766 | for (Instruction *I : llvm::reverse(InstChain)) { |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 767 | CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst, |
Benjamin Kramer | 7f68a30 | 2018-06-15 21:06:43 +0000 | [diff] [blame] | 768 | cast<Constant>(I->getOperand(1)), true); |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 769 | if (!CmpLHSConst) |
| 770 | break; |
| 771 | } |
| 772 | if (!CmpLHSConst) |
| 773 | continue; |
| 774 | // Now constant-evaluate the compare |
| 775 | Constant *Result = ConstantExpr::getCompare(CI->getPredicate(), |
| 776 | CmpLHSConst, CmpConst, true); |
| 777 | // If the result means we don't branch to the block then that block is |
| 778 | // unlikely. |
| 779 | if (Result && |
| 780 | ((Result->isZeroValue() && B == BI->getSuccessor(0)) || |
| 781 | (Result->isOneValue() && B == BI->getSuccessor(1)))) |
| 782 | UnlikelyBlocks.insert(B); |
| 783 | } |
| 784 | } |
| 785 | } |
| 786 | |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 787 | // Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges |
| 788 | // as taken, exiting edges as not-taken. |
Mehdi Amini | a797877 | 2016-04-07 21:59:28 +0000 | [diff] [blame] | 789 | bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB, |
Evgeniy Brevnov | 3a2b05f | 2020-07-24 18:57:10 +0700 | [diff] [blame] | 790 | const LoopInfo &LI) { |
Evgeniy Brevnov | 02a629d | 2020-07-29 19:19:00 +0700 | [diff] [blame] | 791 | LoopBlock LB(BB, LI, *SccI.get()); |
| 792 | if (!LB.belongsToLoop()) |
| 793 | return false; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 794 | |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 795 | SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks; |
Evgeniy Brevnov | 02a629d | 2020-07-29 19:19:00 +0700 | [diff] [blame] | 796 | if (LB.getLoop()) |
| 797 | computeUnlikelySuccessors(BB, LB.getLoop(), UnlikelyBlocks); |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 798 | |
Manman Ren | cf10446 | 2012-08-24 18:14:27 +0000 | [diff] [blame] | 799 | SmallVector<unsigned, 8> BackEdges; |
| 800 | SmallVector<unsigned, 8> ExitingEdges; |
| 801 | SmallVector<unsigned, 8> InEdges; // Edges from header to the loop. |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 802 | SmallVector<unsigned, 8> UnlikelyEdges; |
Jakub Staszak | bcb3c65 | 2011-07-28 21:33:46 +0000 | [diff] [blame] | 803 | |
Alina Sbirlea | 3abcbf9 | 2020-03-10 11:33:02 -0700 | [diff] [blame] | 804 | for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) { |
Evgeniy Brevnov | 02a629d | 2020-07-29 19:19:00 +0700 | [diff] [blame] | 805 | LoopBlock SuccLB(*I, LI, *SccI.get()); |
| 806 | LoopEdge Edge(LB, SuccLB); |
| 807 | bool IsUnlikelyEdge = |
| 808 | LB.getLoop() && (UnlikelyBlocks.find(*I) != UnlikelyBlocks.end()); |
| 809 | |
| 810 | if (IsUnlikelyEdge) |
| 811 | UnlikelyEdges.push_back(I.getSuccessorIndex()); |
| 812 | else if (isLoopExitingEdge(Edge)) |
| 813 | ExitingEdges.push_back(I.getSuccessorIndex()); |
| 814 | else if (isLoopBackEdge(Edge)) |
| 815 | BackEdges.push_back(I.getSuccessorIndex()); |
| 816 | else { |
| 817 | InEdges.push_back(I.getSuccessorIndex()); |
Geoff Berry | eed6531 | 2017-11-01 15:16:50 +0000 | [diff] [blame] | 818 | } |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 819 | } |
| 820 | |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 821 | if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty()) |
Akira Hatanaka | 5638b89 | 2014-04-14 16:56:19 +0000 | [diff] [blame] | 822 | return false; |
| 823 | |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 824 | // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and |
| 825 | // normalize them so that they sum up to one. |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 826 | unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) + |
| 827 | (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) + |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 828 | (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) + |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 829 | (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT); |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 830 | |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 831 | SmallVector<BranchProbability, 4> EdgeProbabilities( |
| 832 | BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown()); |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 833 | if (uint32_t numBackEdges = BackEdges.size()) { |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 834 | BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom); |
| 835 | auto Prob = TakenProb / numBackEdges; |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 836 | for (unsigned SuccIdx : BackEdges) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 837 | EdgeProbabilities[SuccIdx] = Prob; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 838 | } |
| 839 | |
Jakub Staszak | bcb3c65 | 2011-07-28 21:33:46 +0000 | [diff] [blame] | 840 | if (uint32_t numInEdges = InEdges.size()) { |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 841 | BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom); |
| 842 | auto Prob = TakenProb / numInEdges; |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 843 | for (unsigned SuccIdx : InEdges) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 844 | EdgeProbabilities[SuccIdx] = Prob; |
Jakub Staszak | bcb3c65 | 2011-07-28 21:33:46 +0000 | [diff] [blame] | 845 | } |
| 846 | |
Chandler Carruth | 32f46e7 | 2011-10-25 09:47:41 +0000 | [diff] [blame] | 847 | if (uint32_t numExitingEdges = ExitingEdges.size()) { |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 848 | BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT, |
| 849 | Denom); |
| 850 | auto Prob = NotTakenProb / numExitingEdges; |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 851 | for (unsigned SuccIdx : ExitingEdges) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 852 | EdgeProbabilities[SuccIdx] = Prob; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 853 | } |
Jakub Staszak | d07b2e1 | 2011-07-28 21:45:07 +0000 | [diff] [blame] | 854 | |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 855 | if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) { |
| 856 | BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT, |
| 857 | Denom); |
| 858 | auto Prob = UnlikelyProb / numUnlikelyEdges; |
| 859 | for (unsigned SuccIdx : UnlikelyEdges) |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 860 | EdgeProbabilities[SuccIdx] = Prob; |
John Brawn | 29bbed3 | 2018-02-23 17:17:31 +0000 | [diff] [blame] | 861 | } |
| 862 | |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 863 | setEdgeProbability(BB, EdgeProbabilities); |
Jakub Staszak | d07b2e1 | 2011-07-28 21:45:07 +0000 | [diff] [blame] | 864 | return true; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 865 | } |
| 866 | |
Dávid Bolvanský | 0f14b2e | 2020-08-17 20:42:57 +0200 | [diff] [blame] | 867 | bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB, |
John Brawn | da4a68a | 2017-06-08 09:44:40 +0000 | [diff] [blame] | 868 | const TargetLibraryInfo *TLI) { |
Mehdi Amini | a797877 | 2016-04-07 21:59:28 +0000 | [diff] [blame] | 869 | const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
Jakub Staszak | 17af66a | 2011-07-31 03:27:24 +0000 | [diff] [blame] | 870 | if (!BI || !BI->isConditional()) |
| 871 | return false; |
| 872 | |
| 873 | Value *Cond = BI->getCondition(); |
| 874 | ICmpInst *CI = dyn_cast<ICmpInst>(Cond); |
| 875 | if (!CI) |
| 876 | return false; |
| 877 | |
Sam Parker | 0b53e84 | 2019-02-15 11:50:21 +0000 | [diff] [blame] | 878 | auto GetConstantInt = [](Value *V) { |
| 879 | if (auto *I = dyn_cast<BitCastInst>(V)) |
| 880 | return dyn_cast<ConstantInt>(I->getOperand(0)); |
| 881 | return dyn_cast<ConstantInt>(V); |
| 882 | }; |
| 883 | |
Jakub Staszak | 17af66a | 2011-07-31 03:27:24 +0000 | [diff] [blame] | 884 | Value *RHS = CI->getOperand(1); |
Sam Parker | 0b53e84 | 2019-02-15 11:50:21 +0000 | [diff] [blame] | 885 | ConstantInt *CV = GetConstantInt(RHS); |
Dávid Bolvanský | 0f14b2e | 2020-08-17 20:42:57 +0200 | [diff] [blame] | 886 | if (!CV) |
| 887 | return false; |
Jakub Staszak | 17af66a | 2011-07-31 03:27:24 +0000 | [diff] [blame] | 888 | |
Daniel Jasper | a73f3d5 | 2015-04-15 06:24:07 +0000 | [diff] [blame] | 889 | // If the LHS is the result of AND'ing a value with a single bit bitmask, |
| 890 | // we don't have information about probabilities. |
| 891 | if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0))) |
| 892 | if (LHS->getOpcode() == Instruction::And) |
| 893 | if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) |
Craig Topper | 4e22ee6 | 2017-08-04 16:59:29 +0000 | [diff] [blame] | 894 | if (AndRHS->getValue().isPowerOf2()) |
Daniel Jasper | a73f3d5 | 2015-04-15 06:24:07 +0000 | [diff] [blame] | 895 | return false; |
| 896 | |
John Brawn | da4a68a | 2017-06-08 09:44:40 +0000 | [diff] [blame] | 897 | // Check if the LHS is the return value of a library function |
| 898 | LibFunc Func = NumLibFuncs; |
| 899 | if (TLI) |
| 900 | if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0))) |
| 901 | if (Function *CalledFn = Call->getCalledFunction()) |
| 902 | TLI->getLibFunc(*CalledFn, Func); |
| 903 | |
Jakub Staszak | 17af66a | 2011-07-31 03:27:24 +0000 | [diff] [blame] | 904 | bool isProb; |
John Brawn | da4a68a | 2017-06-08 09:44:40 +0000 | [diff] [blame] | 905 | if (Func == LibFunc_strcasecmp || |
| 906 | Func == LibFunc_strcmp || |
| 907 | Func == LibFunc_strncasecmp || |
| 908 | Func == LibFunc_strncmp || |
Dávid Bolvanský | d68a285 | 2020-08-11 20:42:58 +0200 | [diff] [blame] | 909 | Func == LibFunc_memcmp || |
| 910 | Func == LibFunc_bcmp) { |
John Brawn | da4a68a | 2017-06-08 09:44:40 +0000 | [diff] [blame] | 911 | // strcmp and similar functions return zero, negative, or positive, if the |
| 912 | // first string is equal, less, or greater than the second. We consider it |
| 913 | // likely that the strings are not equal, so a comparison with zero is |
| 914 | // probably false, but also a comparison with any other number is also |
| 915 | // probably false given that what exactly is returned for nonzero values is |
| 916 | // not specified. Any kind of comparison other than equality we know |
| 917 | // nothing about. |
| 918 | switch (CI->getPredicate()) { |
| 919 | case CmpInst::ICMP_EQ: |
| 920 | isProb = false; |
| 921 | break; |
| 922 | case CmpInst::ICMP_NE: |
| 923 | isProb = true; |
| 924 | break; |
| 925 | default: |
| 926 | return false; |
| 927 | } |
| 928 | } else if (CV->isZero()) { |
Benjamin Kramer | 0ca1ad0 | 2011-09-04 23:53:04 +0000 | [diff] [blame] | 929 | switch (CI->getPredicate()) { |
| 930 | case CmpInst::ICMP_EQ: |
| 931 | // X == 0 -> Unlikely |
| 932 | isProb = false; |
| 933 | break; |
| 934 | case CmpInst::ICMP_NE: |
| 935 | // X != 0 -> Likely |
| 936 | isProb = true; |
| 937 | break; |
| 938 | case CmpInst::ICMP_SLT: |
| 939 | // X < 0 -> Unlikely |
| 940 | isProb = false; |
| 941 | break; |
| 942 | case CmpInst::ICMP_SGT: |
| 943 | // X > 0 -> Likely |
| 944 | isProb = true; |
| 945 | break; |
| 946 | default: |
| 947 | return false; |
| 948 | } |
| 949 | } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) { |
| 950 | // InstCombine canonicalizes X <= 0 into X < 1. |
| 951 | // X <= 0 -> Unlikely |
Jakub Staszak | 17af66a | 2011-07-31 03:27:24 +0000 | [diff] [blame] | 952 | isProb = false; |
Craig Topper | 79ab643 | 2017-07-06 18:39:47 +0000 | [diff] [blame] | 953 | } else if (CV->isMinusOne()) { |
Hal Finkel | 4d94930 | 2013-11-01 10:58:22 +0000 | [diff] [blame] | 954 | switch (CI->getPredicate()) { |
| 955 | case CmpInst::ICMP_EQ: |
| 956 | // X == -1 -> Unlikely |
| 957 | isProb = false; |
| 958 | break; |
| 959 | case CmpInst::ICMP_NE: |
| 960 | // X != -1 -> Likely |
| 961 | isProb = true; |
| 962 | break; |
| 963 | case CmpInst::ICMP_SGT: |
| 964 | // InstCombine canonicalizes X >= 0 into X > -1. |
| 965 | // X >= 0 -> Likely |
| 966 | isProb = true; |
| 967 | break; |
| 968 | default: |
| 969 | return false; |
| 970 | } |
Benjamin Kramer | 0ca1ad0 | 2011-09-04 23:53:04 +0000 | [diff] [blame] | 971 | } else { |
Jakub Staszak | 17af66a | 2011-07-31 03:27:24 +0000 | [diff] [blame] | 972 | return false; |
Benjamin Kramer | 0ca1ad0 | 2011-09-04 23:53:04 +0000 | [diff] [blame] | 973 | } |
Jakub Staszak | 17af66a | 2011-07-31 03:27:24 +0000 | [diff] [blame] | 974 | |
Dávid Bolvanský | 0f14b2e | 2020-08-17 20:42:57 +0200 | [diff] [blame] | 975 | BranchProbability TakenProb(ZH_TAKEN_WEIGHT, |
| 976 | ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT); |
| 977 | BranchProbability UntakenProb(ZH_NONTAKEN_WEIGHT, |
| 978 | ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT); |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 979 | if (!isProb) |
| 980 | std::swap(TakenProb, UntakenProb); |
| 981 | |
| 982 | setEdgeProbability( |
| 983 | BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb})); |
Jakub Staszak | 17af66a | 2011-07-31 03:27:24 +0000 | [diff] [blame] | 984 | return true; |
| 985 | } |
| 986 | |
Mehdi Amini | a797877 | 2016-04-07 21:59:28 +0000 | [diff] [blame] | 987 | bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) { |
| 988 | const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
Benjamin Kramer | 1e731a1 | 2011-10-21 20:12:47 +0000 | [diff] [blame] | 989 | if (!BI || !BI->isConditional()) |
| 990 | return false; |
| 991 | |
| 992 | Value *Cond = BI->getCondition(); |
| 993 | FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond); |
Benjamin Kramer | 606a50a | 2011-10-21 21:13:47 +0000 | [diff] [blame] | 994 | if (!FCmp) |
Benjamin Kramer | 1e731a1 | 2011-10-21 20:12:47 +0000 | [diff] [blame] | 995 | return false; |
| 996 | |
Guozhi Wei | b329e07 | 2019-09-10 17:25:11 +0000 | [diff] [blame] | 997 | uint32_t TakenWeight = FPH_TAKEN_WEIGHT; |
| 998 | uint32_t NontakenWeight = FPH_NONTAKEN_WEIGHT; |
Benjamin Kramer | 606a50a | 2011-10-21 21:13:47 +0000 | [diff] [blame] | 999 | bool isProb; |
| 1000 | if (FCmp->isEquality()) { |
| 1001 | // f1 == f2 -> Unlikely |
| 1002 | // f1 != f2 -> Likely |
| 1003 | isProb = !FCmp->isTrueWhenEqual(); |
| 1004 | } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) { |
| 1005 | // !isnan -> Likely |
| 1006 | isProb = true; |
Guozhi Wei | b329e07 | 2019-09-10 17:25:11 +0000 | [diff] [blame] | 1007 | TakenWeight = FPH_ORD_WEIGHT; |
| 1008 | NontakenWeight = FPH_UNO_WEIGHT; |
Benjamin Kramer | 606a50a | 2011-10-21 21:13:47 +0000 | [diff] [blame] | 1009 | } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) { |
| 1010 | // isnan -> Unlikely |
| 1011 | isProb = false; |
Guozhi Wei | b329e07 | 2019-09-10 17:25:11 +0000 | [diff] [blame] | 1012 | TakenWeight = FPH_ORD_WEIGHT; |
| 1013 | NontakenWeight = FPH_UNO_WEIGHT; |
Benjamin Kramer | 606a50a | 2011-10-21 21:13:47 +0000 | [diff] [blame] | 1014 | } else { |
| 1015 | return false; |
| 1016 | } |
| 1017 | |
Reid Kleckner | 1370757 | 2020-05-13 08:23:09 -0700 | [diff] [blame] | 1018 | BranchProbability TakenProb(TakenWeight, TakenWeight + NontakenWeight); |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 1019 | BranchProbability UntakenProb(NontakenWeight, TakenWeight + NontakenWeight); |
| 1020 | if (!isProb) |
| 1021 | std::swap(TakenProb, UntakenProb); |
| 1022 | |
| 1023 | setEdgeProbability( |
| 1024 | BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb})); |
Benjamin Kramer | 1e731a1 | 2011-10-21 20:12:47 +0000 | [diff] [blame] | 1025 | return true; |
| 1026 | } |
Jakub Staszak | 17af66a | 2011-07-31 03:27:24 +0000 | [diff] [blame] | 1027 | |
Mehdi Amini | a797877 | 2016-04-07 21:59:28 +0000 | [diff] [blame] | 1028 | bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) { |
| 1029 | const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()); |
Bill Wendling | e1c5426 | 2012-08-15 12:22:35 +0000 | [diff] [blame] | 1030 | if (!II) |
| 1031 | return false; |
| 1032 | |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1033 | BranchProbability TakenProb(IH_TAKEN_WEIGHT, |
| 1034 | IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT); |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 1035 | setEdgeProbability( |
| 1036 | BB, SmallVector<BranchProbability, 2>({TakenProb, TakenProb.getCompl()})); |
Bill Wendling | e1c5426 | 2012-08-15 12:22:35 +0000 | [diff] [blame] | 1037 | return true; |
| 1038 | } |
| 1039 | |
Pete Cooper | b9d2e34 | 2015-05-28 19:43:06 +0000 | [diff] [blame] | 1040 | void BranchProbabilityInfo::releaseMemory() { |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1041 | Probs.clear(); |
Kazu Hirata | a7b662d | 2020-10-27 16:14:25 -0700 | [diff] [blame] | 1042 | MaxSuccIdx.clear(); |
Nikita Popov | fe8abbf | 2020-04-07 21:21:30 +0200 | [diff] [blame] | 1043 | Handles.clear(); |
Pete Cooper | b9d2e34 | 2015-05-28 19:43:06 +0000 | [diff] [blame] | 1044 | } |
| 1045 | |
Alina Sbirlea | 62a50a9 | 2020-01-15 14:02:33 -0800 | [diff] [blame] | 1046 | bool BranchProbabilityInfo::invalidate(Function &, const PreservedAnalyses &PA, |
| 1047 | FunctionAnalysisManager::Invalidator &) { |
| 1048 | // Check whether the analysis, all analyses on functions, or the function's |
| 1049 | // CFG have been preserved. |
| 1050 | auto PAC = PA.getChecker<BranchProbabilityAnalysis>(); |
| 1051 | return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() || |
| 1052 | PAC.preservedSet<CFGAnalyses>()); |
| 1053 | } |
| 1054 | |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1055 | void BranchProbabilityInfo::print(raw_ostream &OS) const { |
Chandler Carruth | 1c8ace0 | 2011-10-23 21:21:50 +0000 | [diff] [blame] | 1056 | OS << "---- Branch Probabilities ----\n"; |
| 1057 | // We print the probabilities from the last function the analysis ran over, |
| 1058 | // or the function it is currently running over. |
| 1059 | assert(LastF && "Cannot print prior to running over a function"); |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1060 | for (const auto &BI : *LastF) { |
Alina Sbirlea | 3abcbf9 | 2020-03-10 11:33:02 -0700 | [diff] [blame] | 1061 | for (const_succ_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE; |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1062 | ++SI) { |
| 1063 | printEdgeProbability(OS << " ", &BI, *SI); |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1064 | } |
| 1065 | } |
Chandler Carruth | 1c8ace0 | 2011-10-23 21:21:50 +0000 | [diff] [blame] | 1066 | } |
| 1067 | |
Jakub Staszak | efd94c8 | 2011-07-29 19:30:00 +0000 | [diff] [blame] | 1068 | bool BranchProbabilityInfo:: |
| 1069 | isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const { |
Andrew Trick | 3d4e64b | 2011-06-11 01:05:22 +0000 | [diff] [blame] | 1070 | // Hot probability is at least 4/5 = 80% |
Benjamin Kramer | 929f53f | 2011-10-23 11:19:14 +0000 | [diff] [blame] | 1071 | // FIXME: Compare against a static "hot" BranchProbability. |
| 1072 | return getEdgeProbability(Src, Dst) > BranchProbability(4, 5); |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 1073 | } |
| 1074 | |
Mehdi Amini | a797877 | 2016-04-07 21:59:28 +0000 | [diff] [blame] | 1075 | const BasicBlock * |
| 1076 | BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const { |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1077 | auto MaxProb = BranchProbability::getZero(); |
Mehdi Amini | a797877 | 2016-04-07 21:59:28 +0000 | [diff] [blame] | 1078 | const BasicBlock *MaxSucc = nullptr; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 1079 | |
Alina Sbirlea | 3abcbf9 | 2020-03-10 11:33:02 -0700 | [diff] [blame] | 1080 | for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) { |
Mehdi Amini | a797877 | 2016-04-07 21:59:28 +0000 | [diff] [blame] | 1081 | const BasicBlock *Succ = *I; |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1082 | auto Prob = getEdgeProbability(BB, Succ); |
| 1083 | if (Prob > MaxProb) { |
| 1084 | MaxProb = Prob; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 1085 | MaxSucc = Succ; |
| 1086 | } |
| 1087 | } |
| 1088 | |
Benjamin Kramer | 929f53f | 2011-10-23 11:19:14 +0000 | [diff] [blame] | 1089 | // Hot probability is at least 4/5 = 80% |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1090 | if (MaxProb > BranchProbability(4, 5)) |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 1091 | return MaxSucc; |
| 1092 | |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1093 | return nullptr; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 1094 | } |
| 1095 | |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1096 | /// Get the raw edge probability for the edge. If can't find it, return a |
| 1097 | /// default probability 1/N where N is the number of successors. Here an edge is |
| 1098 | /// specified using PredBlock and an |
| 1099 | /// index to the successors. |
| 1100 | BranchProbability |
| 1101 | BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src, |
| 1102 | unsigned IndexInSuccessors) const { |
| 1103 | auto I = Probs.find(std::make_pair(Src, IndexInSuccessors)); |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 1104 | |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1105 | if (I != Probs.end()) |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 1106 | return I->second; |
| 1107 | |
Vedant Kumar | e0b5f86 | 2018-05-10 23:01:54 +0000 | [diff] [blame] | 1108 | return {1, static_cast<uint32_t>(succ_size(Src))}; |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 1109 | } |
| 1110 | |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 1111 | BranchProbability |
| 1112 | BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src, |
Alina Sbirlea | 3abcbf9 | 2020-03-10 11:33:02 -0700 | [diff] [blame] | 1113 | const_succ_iterator Dst) const { |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 1114 | return getEdgeProbability(Src, Dst.getSuccessorIndex()); |
| 1115 | } |
| 1116 | |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1117 | /// Get the raw edge probability calculated for the block pair. This returns the |
| 1118 | /// sum of all raw edge probabilities from Src to Dst. |
| 1119 | BranchProbability |
| 1120 | BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src, |
| 1121 | const BasicBlock *Dst) const { |
| 1122 | auto Prob = BranchProbability::getZero(); |
| 1123 | bool FoundProb = false; |
Evgeniy Brevnov | bb0842a | 2020-04-29 14:08:01 +0700 | [diff] [blame] | 1124 | uint32_t EdgeCount = 0; |
Alina Sbirlea | 3abcbf9 | 2020-03-10 11:33:02 -0700 | [diff] [blame] | 1125 | for (const_succ_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I) |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1126 | if (*I == Dst) { |
Evgeniy Brevnov | bb0842a | 2020-04-29 14:08:01 +0700 | [diff] [blame] | 1127 | ++EdgeCount; |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1128 | auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex())); |
| 1129 | if (MapI != Probs.end()) { |
| 1130 | FoundProb = true; |
| 1131 | Prob += MapI->second; |
| 1132 | } |
| 1133 | } |
| 1134 | uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src)); |
Evgeniy Brevnov | bb0842a | 2020-04-29 14:08:01 +0700 | [diff] [blame] | 1135 | return FoundProb ? Prob : BranchProbability(EdgeCount, succ_num); |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1136 | } |
| 1137 | |
| 1138 | /// Set the edge probability for a given edge specified by PredBlock and an |
| 1139 | /// index to the successors. |
| 1140 | void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src, |
| 1141 | unsigned IndexInSuccessors, |
| 1142 | BranchProbability Prob) { |
| 1143 | Probs[std::make_pair(Src, IndexInSuccessors)] = Prob; |
Igor Laevsky | ee40d1e | 2016-07-15 14:31:16 +0000 | [diff] [blame] | 1144 | Handles.insert(BasicBlockCallbackVH(Src, this)); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1145 | LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> " |
| 1146 | << IndexInSuccessors << " successor probability to " << Prob |
| 1147 | << "\n"); |
Kazu Hirata | a7b662d | 2020-10-27 16:14:25 -0700 | [diff] [blame] | 1148 | |
Fangrui Song | d69ada3 | 2020-10-27 16:29:10 -0700 | [diff] [blame] | 1149 | unsigned &SuccIdx = MaxSuccIdx[Src]; |
| 1150 | SuccIdx = std::max(SuccIdx, IndexInSuccessors); |
Cong Hou | e93b8e1 | 2015-12-22 18:56:14 +0000 | [diff] [blame] | 1151 | } |
| 1152 | |
Yevgeny Rouban | 8138487 | 2020-05-21 11:49:11 +0700 | [diff] [blame] | 1153 | /// Set the edge probability for all edges at once. |
| 1154 | void BranchProbabilityInfo::setEdgeProbability( |
| 1155 | const BasicBlock *Src, const SmallVectorImpl<BranchProbability> &Probs) { |
| 1156 | assert(Src->getTerminator()->getNumSuccessors() == Probs.size()); |
| 1157 | if (Probs.size() == 0) |
| 1158 | return; // Nothing to set. |
| 1159 | |
| 1160 | uint64_t TotalNumerator = 0; |
| 1161 | for (unsigned SuccIdx = 0; SuccIdx < Probs.size(); ++SuccIdx) { |
| 1162 | setEdgeProbability(Src, SuccIdx, Probs[SuccIdx]); |
| 1163 | TotalNumerator += Probs[SuccIdx].getNumerator(); |
| 1164 | } |
| 1165 | |
| 1166 | // Because of rounding errors the total probability cannot be checked to be |
| 1167 | // 1.0 exactly. That is TotalNumerator == BranchProbability::getDenominator. |
| 1168 | // Instead, every single probability in Probs must be as accurate as possible. |
| 1169 | // This results in error 1/denominator at most, thus the total absolute error |
| 1170 | // should be within Probs.size / BranchProbability::getDenominator. |
| 1171 | assert(TotalNumerator <= BranchProbability::getDenominator() + Probs.size()); |
| 1172 | assert(TotalNumerator >= BranchProbability::getDenominator() - Probs.size()); |
| 1173 | } |
| 1174 | |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 1175 | raw_ostream & |
Chandler Carruth | 1c8ace0 | 2011-10-23 21:21:50 +0000 | [diff] [blame] | 1176 | BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS, |
| 1177 | const BasicBlock *Src, |
| 1178 | const BasicBlock *Dst) const { |
Jakub Staszak | 12a43bd | 2011-06-16 20:22:37 +0000 | [diff] [blame] | 1179 | const BranchProbability Prob = getEdgeProbability(Src, Dst); |
Benjamin Kramer | 1f97a5a | 2011-11-15 16:27:03 +0000 | [diff] [blame] | 1180 | OS << "edge " << Src->getName() << " -> " << Dst->getName() |
Andrew Trick | 3d4e64b | 2011-06-11 01:05:22 +0000 | [diff] [blame] | 1181 | << " probability is " << Prob |
| 1182 | << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n"); |
Andrew Trick | 49371f3 | 2011-06-04 01:16:30 +0000 | [diff] [blame] | 1183 | |
| 1184 | return OS; |
| 1185 | } |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1186 | |
Igor Laevsky | ee40d1e | 2016-07-15 14:31:16 +0000 | [diff] [blame] | 1187 | void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) { |
Fangrui Song | d69ada3 | 2020-10-27 16:29:10 -0700 | [diff] [blame] | 1188 | // Note that we cannot use successors of BB because the terminator of BB may |
| 1189 | // have changed when eraseBlock is called as a BasicBlockCallbackVH callback. |
Kazu Hirata | a7b662d | 2020-10-27 16:14:25 -0700 | [diff] [blame] | 1190 | auto It = MaxSuccIdx.find(BB); |
| 1191 | if (It == MaxSuccIdx.end()) |
| 1192 | return; |
| 1193 | |
| 1194 | for (unsigned I = 0, E = It->second; I <= E; ++I) { |
| 1195 | auto MapI = Probs.find(std::make_pair(BB, I)); |
Teresa Johnson | 3e5173d | 2020-07-10 15:25:27 -0700 | [diff] [blame] | 1196 | if (MapI != Probs.end()) |
| 1197 | Probs.erase(MapI); |
Igor Laevsky | ee40d1e | 2016-07-15 14:31:16 +0000 | [diff] [blame] | 1198 | } |
Kazu Hirata | a7b662d | 2020-10-27 16:14:25 -0700 | [diff] [blame] | 1199 | MaxSuccIdx.erase(BB); |
Igor Laevsky | ee40d1e | 2016-07-15 14:31:16 +0000 | [diff] [blame] | 1200 | } |
| 1201 | |
John Brawn | da4a68a | 2017-06-08 09:44:40 +0000 | [diff] [blame] | 1202 | void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI, |
Evgeniy Brevnov | 3e68a667 | 2020-04-28 16:31:20 +0700 | [diff] [blame] | 1203 | const TargetLibraryInfo *TLI, |
| 1204 | PostDominatorTree *PDT) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1205 | LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName() |
| 1206 | << " ----\n\n"); |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1207 | LastF = &F; // Store the last function we ran on for printing. |
| 1208 | assert(PostDominatedByUnreachable.empty()); |
| 1209 | assert(PostDominatedByColdCall.empty()); |
| 1210 | |
Evgeniy Brevnov | 3a2b05f | 2020-07-24 18:57:10 +0700 | [diff] [blame] | 1211 | SccI = std::make_unique<SccInfo>(F); |
Geoff Berry | eed6531 | 2017-11-01 15:16:50 +0000 | [diff] [blame] | 1212 | |
Evgeniy Brevnov | 3e68a667 | 2020-04-28 16:31:20 +0700 | [diff] [blame] | 1213 | std::unique_ptr<PostDominatorTree> PDTPtr; |
| 1214 | |
| 1215 | if (!PDT) { |
| 1216 | PDTPtr = std::make_unique<PostDominatorTree>(const_cast<Function &>(F)); |
| 1217 | PDT = PDTPtr.get(); |
| 1218 | } |
| 1219 | |
| 1220 | computePostDominatedByUnreachable(F, PDT); |
| 1221 | computePostDominatedByColdCall(F, PDT); |
Taewook Oh | 2da205d | 2019-12-02 10:15:22 -0800 | [diff] [blame] | 1222 | |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1223 | // Walk the basic blocks in post-order so that we can build up state about |
| 1224 | // the successors of a block iteratively. |
| 1225 | for (auto BB : post_order(&F.getEntryBlock())) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1226 | LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName() |
| 1227 | << "\n"); |
Serguei Katkov | 11d9c4f | 2017-04-17 06:39:47 +0000 | [diff] [blame] | 1228 | // If there is no at least two successors, no sense to set probability. |
| 1229 | if (BB->getTerminator()->getNumSuccessors() < 2) |
| 1230 | continue; |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1231 | if (calcMetadataWeights(BB)) |
| 1232 | continue; |
Artur Pilipenko | 4d063e7 | 2018-06-08 13:03:21 +0000 | [diff] [blame] | 1233 | if (calcInvokeHeuristics(BB)) |
| 1234 | continue; |
Serguei Katkov | 2616bbb | 2017-04-17 04:33:04 +0000 | [diff] [blame] | 1235 | if (calcUnreachableHeuristics(BB)) |
| 1236 | continue; |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1237 | if (calcColdCallHeuristics(BB)) |
| 1238 | continue; |
Evgeniy Brevnov | 3a2b05f | 2020-07-24 18:57:10 +0700 | [diff] [blame] | 1239 | if (calcLoopBranchHeuristics(BB, LI)) |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1240 | continue; |
| 1241 | if (calcPointerHeuristics(BB)) |
| 1242 | continue; |
Dávid Bolvanský | 0f14b2e | 2020-08-17 20:42:57 +0200 | [diff] [blame] | 1243 | if (calcZeroHeuristics(BB, TLI)) |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1244 | continue; |
| 1245 | if (calcFloatingPointHeuristics(BB)) |
| 1246 | continue; |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1247 | } |
| 1248 | |
| 1249 | PostDominatedByUnreachable.clear(); |
| 1250 | PostDominatedByColdCall.clear(); |
Evgeniy Brevnov | 412b393 | 2020-07-28 19:50:40 +0700 | [diff] [blame] | 1251 | SccI.reset(); |
Hiroshi Yamauchi | 63e17eb | 2017-08-26 00:31:00 +0000 | [diff] [blame] | 1252 | |
| 1253 | if (PrintBranchProb && |
| 1254 | (PrintBranchProbFuncName.empty() || |
| 1255 | F.getName().equals(PrintBranchProbFuncName))) { |
| 1256 | print(dbgs()); |
| 1257 | } |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1258 | } |
| 1259 | |
| 1260 | void BranchProbabilityInfoWrapperPass::getAnalysisUsage( |
| 1261 | AnalysisUsage &AU) const { |
Mikael Holmen | 2ca1689 | 2018-05-17 09:05:40 +0000 | [diff] [blame] | 1262 | // We require DT so it's available when LI is available. The LI updating code |
| 1263 | // asserts that DT is also present so if we don't make sure that we have DT |
| 1264 | // here, that assert will trigger. |
| 1265 | AU.addRequired<DominatorTreeWrapperPass>(); |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1266 | AU.addRequired<LoopInfoWrapperPass>(); |
John Brawn | da4a68a | 2017-06-08 09:44:40 +0000 | [diff] [blame] | 1267 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Evgeniy Brevnov | 3e68a667 | 2020-04-28 16:31:20 +0700 | [diff] [blame] | 1268 | AU.addRequired<PostDominatorTreeWrapperPass>(); |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1269 | AU.setPreservesAll(); |
| 1270 | } |
| 1271 | |
| 1272 | bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) { |
| 1273 | const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Teresa Johnson | 9c27b59 | 2019-09-07 03:09:36 +0000 | [diff] [blame] | 1274 | const TargetLibraryInfo &TLI = |
| 1275 | getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); |
Evgeniy Brevnov | 3e68a667 | 2020-04-28 16:31:20 +0700 | [diff] [blame] | 1276 | PostDominatorTree &PDT = |
| 1277 | getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); |
| 1278 | BPI.calculate(F, LI, &TLI, &PDT); |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1279 | return false; |
| 1280 | } |
| 1281 | |
| 1282 | void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); } |
| 1283 | |
| 1284 | void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS, |
| 1285 | const Module *) const { |
| 1286 | BPI.print(OS); |
| 1287 | } |
Xinliang David Li | 6e5dd41 | 2016-05-05 02:59:57 +0000 | [diff] [blame] | 1288 | |
Chandler Carruth | dab4eae | 2016-11-23 17:53:26 +0000 | [diff] [blame] | 1289 | AnalysisKey BranchProbabilityAnalysis::Key; |
Xinliang David Li | 6e5dd41 | 2016-05-05 02:59:57 +0000 | [diff] [blame] | 1290 | BranchProbabilityInfo |
Sean Silva | 36e0d01 | 2016-08-09 00:28:15 +0000 | [diff] [blame] | 1291 | BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) { |
Xinliang David Li | 6e5dd41 | 2016-05-05 02:59:57 +0000 | [diff] [blame] | 1292 | BranchProbabilityInfo BPI; |
Evgeniy Brevnov | 3e68a667 | 2020-04-28 16:31:20 +0700 | [diff] [blame] | 1293 | BPI.calculate(F, AM.getResult<LoopAnalysis>(F), |
| 1294 | &AM.getResult<TargetLibraryAnalysis>(F), |
| 1295 | &AM.getResult<PostDominatorTreeAnalysis>(F)); |
Xinliang David Li | 6e5dd41 | 2016-05-05 02:59:57 +0000 | [diff] [blame] | 1296 | return BPI; |
| 1297 | } |
| 1298 | |
| 1299 | PreservedAnalyses |
Sean Silva | 36e0d01 | 2016-08-09 00:28:15 +0000 | [diff] [blame] | 1300 | BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { |
Xinliang David Li | 6e5dd41 | 2016-05-05 02:59:57 +0000 | [diff] [blame] | 1301 | OS << "Printing analysis results of BPI for function " |
| 1302 | << "'" << F.getName() << "':" |
| 1303 | << "\n"; |
| 1304 | AM.getResult<BranchProbabilityAnalysis>(F).print(OS); |
| 1305 | return PreservedAnalyses::all(); |
| 1306 | } |