1 //===- BranchProbabilityInfo.cpp - Branch Probability Analysis ------------===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Loops should be simplified before this analysis. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Analysis/BranchProbabilityInfo.h" 14 #include "llvm/ADT/PostOrderIterator.h" 15 #include "llvm/ADT/SCCIterator.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/LoopInfo.h" 19 #include "llvm/Analysis/PostDominators.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/IR/Attributes.h" 22 #include "llvm/IR/BasicBlock.h" 23 #include "llvm/IR/CFG.h" 24 #include "llvm/IR/Constants.h" 25 #include "llvm/IR/Dominators.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/InstrTypes.h" 28 #include "llvm/IR/Instruction.h" 29 #include "llvm/IR/Instructions.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/PassManager.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/IR/Value.h" 35 #include "llvm/InitializePasses.h" 36 #include "llvm/Pass.h" 37 #include "llvm/Support/BranchProbability.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <cassert> 43 #include <cstdint> 44 #include <iterator> 45 #include <utility> 46 47 using namespace llvm; 48 49 #define DEBUG_TYPE "branch-prob" 50 51 static cl::opt<bool> PrintBranchProb( 52 "print-bpi", cl::init(false), cl::Hidden, 53 cl::desc("Print the branch probability info.")); 54 55 cl::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 60 INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob", 61 "Branch Probability Analysis", false, true) 62 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 63 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 64 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 65 INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob", 66 "Branch Probability Analysis", false, true) 67 68 BranchProbabilityInfoWrapperPass::BranchProbabilityInfoWrapperPass() 69 : FunctionPass(ID) { 70 initializeBranchProbabilityInfoWrapperPassPass( 71 *PassRegistry::getPassRegistry()); 72 } 73 74 char BranchProbabilityInfoWrapperPass::ID = 0; 75 76 // 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 96 static const uint32_t LBH_TAKEN_WEIGHT = 124; 97 static const uint32_t LBH_NONTAKEN_WEIGHT = 4; 98 // Unlikely edges within a loop are half as likely as other edges 99 static const uint32_t LBH_UNLIKELY_WEIGHT = 62; 100 101 /// Unreachable-terminating branch taken probability. 102 /// 103 /// This is the probability for a branch being taken to a block that terminates 104 /// (eventually) in unreachable. These are predicted as unlikely as possible. 105 /// All reachable probability will equally share the remaining part. 106 static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1); 107 108 /// Weight for a branch taken going into a cold block. 109 /// 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'. 114 static const uint32_t CC_TAKEN_WEIGHT = 4; 115 116 /// Weight for a branch not-taken into a cold block. 117 /// 118 /// This is the weight for a branch not taken toward a block marked 119 /// cold. 120 static const uint32_t CC_NONTAKEN_WEIGHT = 64; 121 122 static const uint32_t PH_TAKEN_WEIGHT = 20; 123 static const uint32_t PH_NONTAKEN_WEIGHT = 12; 124 125 static const uint32_t ZH_TAKEN_WEIGHT = 20; 126 static const uint32_t ZH_NONTAKEN_WEIGHT = 12; 127 128 static const uint32_t FPH_TAKEN_WEIGHT = 20; 129 static const uint32_t FPH_NONTAKEN_WEIGHT = 12; 130 131 /// This is the probability for an ordered floating point comparison. 132 static 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. 136 static const uint32_t FPH_UNO_WEIGHT = 1; 137 138 /// Invoke-terminating normal branch taken weight 139 /// 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. 143 static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1; 144 145 /// Invoke-terminating normal branch not-taken weight. 146 /// 147 /// This is the weight for branching to the unwind destination of an invoke 148 /// instruction. This is essentially never taken. 149 static const uint32_t IH_NONTAKEN_WEIGHT = 1; 150 151 static void UpdatePDTWorklist(const BasicBlock *BB, PostDominatorTree *PDT, 152 SmallVectorImpl<const BasicBlock *> &WorkList, 153 SmallPtrSetImpl<const BasicBlock *> &TargetSet) { 154 SmallVector<BasicBlock *, 8> Descendants; 155 SmallPtrSet<const BasicBlock *, 16> NewItems; 156 157 PDT->getDescendants(const_cast<BasicBlock *>(BB), Descendants); 158 for (auto *BB : Descendants) 159 if (TargetSet.insert(BB).second) 160 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 161 if (!TargetSet.count(*PI)) 162 NewItems.insert(*PI); 163 WorkList.insert(WorkList.end(), NewItems.begin(), NewItems.end()); 164 } 165 166 /// Compute a set of basic blocks that are post-dominated by unreachables. 167 void BranchProbabilityInfo::computePostDominatedByUnreachable( 168 const Function &F, PostDominatorTree *PDT) { 169 SmallVector<const BasicBlock *, 8> WorkList; 170 for (auto &BB : F) { 171 const Instruction *TI = BB.getTerminator(); 172 if (TI->getNumSuccessors() == 0) { 173 if (isa<UnreachableInst>(TI) || 174 // If this block is terminated by a call to 175 // @llvm.experimental.deoptimize then treat it like an unreachable 176 // since the @llvm.experimental.deoptimize call is expected to 177 // practically never execute. 178 BB.getTerminatingDeoptimizeCall()) 179 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByUnreachable); 180 } 181 } 182 183 while (!WorkList.empty()) { 184 const BasicBlock *BB = WorkList.pop_back_val(); 185 if (PostDominatedByUnreachable.count(BB)) 186 continue; 187 // If the terminator is an InvokeInst, check only the normal destination 188 // block as the unwind edge of InvokeInst is also very unlikely taken. 189 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) { 190 if (PostDominatedByUnreachable.count(II->getNormalDest())) 191 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable); 192 } 193 // If all the successors are unreachable, BB is unreachable as well. 194 else if (!successors(BB).empty() && 195 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) { 196 return PostDominatedByUnreachable.count(Succ); 197 })) 198 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable); 199 } 200 } 201 202 /// compute a set of basic blocks that are post-dominated by ColdCalls. 203 void BranchProbabilityInfo::computePostDominatedByColdCall( 204 const Function &F, PostDominatorTree *PDT) { 205 SmallVector<const BasicBlock *, 8> WorkList; 206 for (auto &BB : F) 207 for (auto &I : BB) 208 if (const CallInst *CI = dyn_cast<CallInst>(&I)) 209 if (CI->hasFnAttr(Attribute::Cold)) 210 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByColdCall); 211 212 while (!WorkList.empty()) { 213 const BasicBlock *BB = WorkList.pop_back_val(); 214 215 // If the terminator is an InvokeInst, check only the normal destination 216 // block as the unwind edge of InvokeInst is also very unlikely taken. 217 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) { 218 if (PostDominatedByColdCall.count(II->getNormalDest())) 219 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall); 220 } 221 // If all of successor are post dominated then BB is also done. 222 else if (!successors(BB).empty() && 223 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) { 224 return PostDominatedByColdCall.count(Succ); 225 })) 226 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall); 227 } 228 } 229 230 /// Calculate edge weights for successors lead to unreachable. 231 /// 232 /// Predict that a successor which leads necessarily to an 233 /// unreachable-terminated block as extremely unlikely. 234 bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) { 235 const Instruction *TI = BB->getTerminator(); 236 (void) TI; 237 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!"); 238 assert(!isa<InvokeInst>(TI) && 239 "Invokes should have already been handled by calcInvokeHeuristics"); 240 241 SmallVector<unsigned, 4> UnreachableEdges; 242 SmallVector<unsigned, 4> ReachableEdges; 243 244 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) 245 if (PostDominatedByUnreachable.count(*I)) 246 UnreachableEdges.push_back(I.getSuccessorIndex()); 247 else 248 ReachableEdges.push_back(I.getSuccessorIndex()); 249 250 // Skip probabilities if all were reachable. 251 if (UnreachableEdges.empty()) 252 return false; 253 254 SmallVector<BranchProbability, 4> EdgeProbabilities( 255 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown()); 256 if (ReachableEdges.empty()) { 257 BranchProbability Prob(1, UnreachableEdges.size()); 258 for (unsigned SuccIdx : UnreachableEdges) 259 EdgeProbabilities[SuccIdx] = Prob; 260 setEdgeProbability(BB, EdgeProbabilities); 261 return true; 262 } 263 264 auto UnreachableProb = UR_TAKEN_PROB; 265 auto ReachableProb = 266 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) / 267 ReachableEdges.size(); 268 269 for (unsigned SuccIdx : UnreachableEdges) 270 EdgeProbabilities[SuccIdx] = UnreachableProb; 271 for (unsigned SuccIdx : ReachableEdges) 272 EdgeProbabilities[SuccIdx] = ReachableProb; 273 274 setEdgeProbability(BB, EdgeProbabilities); 275 return true; 276 } 277 278 // Propagate existing explicit probabilities from either profile data or 279 // 'expect' intrinsic processing. Examine metadata against unreachable 280 // heuristic. The probability of the edge coming to unreachable block is 281 // set to min of metadata and unreachable heuristic. 282 bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) { 283 const Instruction *TI = BB->getTerminator(); 284 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!"); 285 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI))) 286 return false; 287 288 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof); 289 if (!WeightsNode) 290 return false; 291 292 // Check that the number of successors is manageable. 293 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors"); 294 295 // Ensure there are weights for all of the successors. Note that the first 296 // operand to the metadata node is a name, not a weight. 297 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1) 298 return false; 299 300 // Build up the final weights that will be used in a temporary buffer. 301 // Compute the sum of all weights to later decide whether they need to 302 // be scaled to fit in 32 bits. 303 uint64_t WeightSum = 0; 304 SmallVector<uint32_t, 2> Weights; 305 SmallVector<unsigned, 2> UnreachableIdxs; 306 SmallVector<unsigned, 2> ReachableIdxs; 307 Weights.reserve(TI->getNumSuccessors()); 308 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) { 309 ConstantInt *Weight = 310 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i)); 311 if (!Weight) 312 return false; 313 assert(Weight->getValue().getActiveBits() <= 32 && 314 "Too many bits for uint32_t"); 315 Weights.push_back(Weight->getZExtValue()); 316 WeightSum += Weights.back(); 317 if (PostDominatedByUnreachable.count(TI->getSuccessor(i - 1))) 318 UnreachableIdxs.push_back(i - 1); 319 else 320 ReachableIdxs.push_back(i - 1); 321 } 322 assert(Weights.size() == TI->getNumSuccessors() && "Checked above"); 323 324 // If the sum of weights does not fit in 32 bits, scale every weight down 325 // accordingly. 326 uint64_t ScalingFactor = 327 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1; 328 329 if (ScalingFactor > 1) { 330 WeightSum = 0; 331 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 332 Weights[i] /= ScalingFactor; 333 WeightSum += Weights[i]; 334 } 335 } 336 assert(WeightSum <= UINT32_MAX && 337 "Expected weights to scale down to 32 bits"); 338 339 if (WeightSum == 0 || ReachableIdxs.size() == 0) { 340 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 341 Weights[i] = 1; 342 WeightSum = TI->getNumSuccessors(); 343 } 344 345 // Set the probability. 346 SmallVector<BranchProbability, 2> BP; 347 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 348 BP.push_back({ Weights[i], static_cast<uint32_t>(WeightSum) }); 349 350 // Examine the metadata against unreachable heuristic. 351 // If the unreachable heuristic is more strong then we use it for this edge. 352 if (UnreachableIdxs.size() > 0 && ReachableIdxs.size() > 0) { 353 auto UnreachableProb = UR_TAKEN_PROB; 354 for (auto i : UnreachableIdxs) 355 if (UnreachableProb < BP[i]) { 356 BP[i] = UnreachableProb; 357 } 358 359 // Because of possible rounding errors and the above fix up for 360 // the unreachable heuristic the sum of probabilities of all edges may be 361 // less than 1.0. Distribute the remaining probability (calculated as 362 // 1.0 - (sum of BP[i])) evenly among all the reachable edges. 363 auto ToDistribute = BranchProbability::getOne(); 364 for (auto &P : BP) 365 ToDistribute -= P; 366 367 // If we modified the probability of some edges then we must distribute 368 // the difference between reachable blocks. 369 // TODO: This spreads ToDistribute evenly upon the reachable edges. A better 370 // distribution would be proportional. So the relation between weights of 371 // the reachable edges would be kept unchanged. That is for any reachable 372 // edges i and j: 373 // newBP[i] / newBP[j] == oldBP[i] / oldBP[j] 374 // newBP[i] / oldBP[i] == newBP[j] / oldBP[j] == 375 // == Denominator / (Denominator - ToDistribute) 376 // newBP[i] = oldBP[i] * Denominator / (Denominator - ToDistribute) 377 BranchProbability PerEdge = ToDistribute / ReachableIdxs.size(); 378 if (PerEdge > BranchProbability::getZero()) 379 for (auto i : ReachableIdxs) 380 BP[i] += PerEdge; 381 } 382 383 setEdgeProbability(BB, BP); 384 385 return true; 386 } 387 388 /// Calculate edge weights for edges leading to cold blocks. 389 /// 390 /// A cold block is one post-dominated by a block with a call to a 391 /// cold function. Those edges are unlikely to be taken, so we give 392 /// them relatively low weight. 393 /// 394 /// Return true if we could compute the weights for cold edges. 395 /// Return false, otherwise. 396 bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) { 397 const Instruction *TI = BB->getTerminator(); 398 (void) TI; 399 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!"); 400 assert(!isa<InvokeInst>(TI) && 401 "Invokes should have already been handled by calcInvokeHeuristics"); 402 403 // Determine which successors are post-dominated by a cold block. 404 SmallVector<unsigned, 4> ColdEdges; 405 SmallVector<unsigned, 4> NormalEdges; 406 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) 407 if (PostDominatedByColdCall.count(*I)) 408 ColdEdges.push_back(I.getSuccessorIndex()); 409 else 410 NormalEdges.push_back(I.getSuccessorIndex()); 411 412 // Skip probabilities if no cold edges. 413 if (ColdEdges.empty()) 414 return false; 415 416 SmallVector<BranchProbability, 4> EdgeProbabilities( 417 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown()); 418 if (NormalEdges.empty()) { 419 BranchProbability Prob(1, ColdEdges.size()); 420 for (unsigned SuccIdx : ColdEdges) 421 EdgeProbabilities[SuccIdx] = Prob; 422 setEdgeProbability(BB, EdgeProbabilities); 423 return true; 424 } 425 426 auto ColdProb = BranchProbability::getBranchProbability( 427 CC_TAKEN_WEIGHT, 428 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size())); 429 auto NormalProb = BranchProbability::getBranchProbability( 430 CC_NONTAKEN_WEIGHT, 431 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size())); 432 433 for (unsigned SuccIdx : ColdEdges) 434 EdgeProbabilities[SuccIdx] = ColdProb; 435 for (unsigned SuccIdx : NormalEdges) 436 EdgeProbabilities[SuccIdx] = NormalProb; 437 438 setEdgeProbability(BB, EdgeProbabilities); 439 return true; 440 } 441 442 // Calculate Edge Weights using "Pointer Heuristics". Predict a comparison 443 // between two pointer or pointer and NULL will fail. 444 bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) { 445 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); 446 if (!BI || !BI->isConditional()) 447 return false; 448 449 Value *Cond = BI->getCondition(); 450 ICmpInst *CI = dyn_cast<ICmpInst>(Cond); 451 if (!CI || !CI->isEquality()) 452 return false; 453 454 Value *LHS = CI->getOperand(0); 455 456 if (!LHS->getType()->isPointerTy()) 457 return false; 458 459 assert(CI->getOperand(1)->getType()->isPointerTy()); 460 461 BranchProbability TakenProb(PH_TAKEN_WEIGHT, 462 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT); 463 BranchProbability UntakenProb(PH_NONTAKEN_WEIGHT, 464 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT); 465 466 // p != 0 -> isProb = true 467 // p == 0 -> isProb = false 468 // p != q -> isProb = true 469 // p == q -> isProb = false; 470 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE; 471 if (!isProb) 472 std::swap(TakenProb, UntakenProb); 473 474 setEdgeProbability( 475 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb})); 476 return true; 477 } 478 479 static int getSCCNum(const BasicBlock *BB, 480 const BranchProbabilityInfo::SccInfo &SccI) { 481 auto SccIt = SccI.SccNums.find(BB); 482 if (SccIt == SccI.SccNums.end()) 483 return -1; 484 return SccIt->second; 485 } 486 487 // Consider any block that is an entry point to the SCC as a header. 488 static bool isSCCHeader(const BasicBlock *BB, int SccNum, 489 BranchProbabilityInfo::SccInfo &SccI) { 490 assert(getSCCNum(BB, SccI) == SccNum); 491 492 // Lazily compute the set of headers for a given SCC and cache the results 493 // in the SccHeaderMap. 494 if (SccI.SccHeaders.size() <= static_cast<unsigned>(SccNum)) 495 SccI.SccHeaders.resize(SccNum + 1); 496 auto &HeaderMap = SccI.SccHeaders[SccNum]; 497 bool Inserted; 498 BranchProbabilityInfo::SccHeaderMap::iterator HeaderMapIt; 499 std::tie(HeaderMapIt, Inserted) = HeaderMap.insert(std::make_pair(BB, false)); 500 if (Inserted) { 501 bool IsHeader = llvm::any_of(make_range(pred_begin(BB), pred_end(BB)), 502 [&](const BasicBlock *Pred) { 503 return getSCCNum(Pred, SccI) != SccNum; 504 }); 505 HeaderMapIt->second = IsHeader; 506 return IsHeader; 507 } else 508 return HeaderMapIt->second; 509 } 510 511 // Compute the unlikely successors to the block BB in the loop L, specifically 512 // those that are unlikely because this is a loop, and add them to the 513 // UnlikelyBlocks set. 514 static void 515 computeUnlikelySuccessors(const BasicBlock *BB, Loop *L, 516 SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) { 517 // Sometimes in a loop we have a branch whose condition is made false by 518 // taking it. This is typically something like 519 // int n = 0; 520 // while (...) { 521 // if (++n >= MAX) { 522 // n = 0; 523 // } 524 // } 525 // In this sort of situation taking the branch means that at the very least it 526 // won't be taken again in the next iteration of the loop, so we should 527 // consider it less likely than a typical branch. 528 // 529 // We detect this by looking back through the graph of PHI nodes that sets the 530 // value that the condition depends on, and seeing if we can reach a successor 531 // block which can be determined to make the condition false. 532 // 533 // FIXME: We currently consider unlikely blocks to be half as likely as other 534 // blocks, but if we consider the example above the likelyhood is actually 535 // 1/MAX. We could therefore be more precise in how unlikely we consider 536 // blocks to be, but it would require more careful examination of the form 537 // of the comparison expression. 538 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); 539 if (!BI || !BI->isConditional()) 540 return; 541 542 // Check if the branch is based on an instruction compared with a constant 543 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition()); 544 if (!CI || !isa<Instruction>(CI->getOperand(0)) || 545 !isa<Constant>(CI->getOperand(1))) 546 return; 547 548 // Either the instruction must be a PHI, or a chain of operations involving 549 // constants that ends in a PHI which we can then collapse into a single value 550 // if the PHI value is known. 551 Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0)); 552 PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS); 553 Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1)); 554 // Collect the instructions until we hit a PHI 555 SmallVector<BinaryOperator *, 1> InstChain; 556 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) && 557 isa<Constant>(CmpLHS->getOperand(1))) { 558 // Stop if the chain extends outside of the loop 559 if (!L->contains(CmpLHS)) 560 return; 561 InstChain.push_back(cast<BinaryOperator>(CmpLHS)); 562 CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0)); 563 if (CmpLHS) 564 CmpPHI = dyn_cast<PHINode>(CmpLHS); 565 } 566 if (!CmpPHI || !L->contains(CmpPHI)) 567 return; 568 569 // Trace the phi node to find all values that come from successors of BB 570 SmallPtrSet<PHINode*, 8> VisitedInsts; 571 SmallVector<PHINode*, 8> WorkList; 572 WorkList.push_back(CmpPHI); 573 VisitedInsts.insert(CmpPHI); 574 while (!WorkList.empty()) { 575 PHINode *P = WorkList.back(); 576 WorkList.pop_back(); 577 for (BasicBlock *B : P->blocks()) { 578 // Skip blocks that aren't part of the loop 579 if (!L->contains(B)) 580 continue; 581 Value *V = P->getIncomingValueForBlock(B); 582 // If the source is a PHI add it to the work list if we haven't 583 // already visited it. 584 if (PHINode *PN = dyn_cast<PHINode>(V)) { 585 if (VisitedInsts.insert(PN).second) 586 WorkList.push_back(PN); 587 continue; 588 } 589 // If this incoming value is a constant and B is a successor of BB, then 590 // we can constant-evaluate the compare to see if it makes the branch be 591 // taken or not. 592 Constant *CmpLHSConst = dyn_cast<Constant>(V); 593 if (!CmpLHSConst || 594 std::find(succ_begin(BB), succ_end(BB), B) == succ_end(BB)) 595 continue; 596 // First collapse InstChain 597 for (Instruction *I : llvm::reverse(InstChain)) { 598 CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst, 599 cast<Constant>(I->getOperand(1)), true); 600 if (!CmpLHSConst) 601 break; 602 } 603 if (!CmpLHSConst) 604 continue; 605 // Now constant-evaluate the compare 606 Constant *Result = ConstantExpr::getCompare(CI->getPredicate(), 607 CmpLHSConst, CmpConst, true); 608 // If the result means we don't branch to the block then that block is 609 // unlikely. 610 if (Result && 611 ((Result->isZeroValue() && B == BI->getSuccessor(0)) || 612 (Result->isOneValue() && B == BI->getSuccessor(1)))) 613 UnlikelyBlocks.insert(B); 614 } 615 } 616 } 617 618 // Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges 619 // as taken, exiting edges as not-taken. 620 bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB, 621 const LoopInfo &LI, 622 SccInfo &SccI) { 623 int SccNum; 624 Loop *L = LI.getLoopFor(BB); 625 if (!L) { 626 SccNum = getSCCNum(BB, SccI); 627 if (SccNum < 0) 628 return false; 629 } 630 631 SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks; 632 if (L) 633 computeUnlikelySuccessors(BB, L, UnlikelyBlocks); 634 635 SmallVector<unsigned, 8> BackEdges; 636 SmallVector<unsigned, 8> ExitingEdges; 637 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop. 638 SmallVector<unsigned, 8> UnlikelyEdges; 639 640 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) { 641 // Use LoopInfo if we have it, otherwise fall-back to SCC info to catch 642 // irreducible loops. 643 if (L) { 644 if (UnlikelyBlocks.count(*I) != 0) 645 UnlikelyEdges.push_back(I.getSuccessorIndex()); 646 else if (!L->contains(*I)) 647 ExitingEdges.push_back(I.getSuccessorIndex()); 648 else if (L->getHeader() == *I) 649 BackEdges.push_back(I.getSuccessorIndex()); 650 else 651 InEdges.push_back(I.getSuccessorIndex()); 652 } else { 653 if (getSCCNum(*I, SccI) != SccNum) 654 ExitingEdges.push_back(I.getSuccessorIndex()); 655 else if (isSCCHeader(*I, SccNum, SccI)) 656 BackEdges.push_back(I.getSuccessorIndex()); 657 else 658 InEdges.push_back(I.getSuccessorIndex()); 659 } 660 } 661 662 if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty()) 663 return false; 664 665 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and 666 // normalize them so that they sum up to one. 667 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) + 668 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) + 669 (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) + 670 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT); 671 672 SmallVector<BranchProbability, 4> EdgeProbabilities( 673 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown()); 674 if (uint32_t numBackEdges = BackEdges.size()) { 675 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom); 676 auto Prob = TakenProb / numBackEdges; 677 for (unsigned SuccIdx : BackEdges) 678 EdgeProbabilities[SuccIdx] = Prob; 679 } 680 681 if (uint32_t numInEdges = InEdges.size()) { 682 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom); 683 auto Prob = TakenProb / numInEdges; 684 for (unsigned SuccIdx : InEdges) 685 EdgeProbabilities[SuccIdx] = Prob; 686 } 687 688 if (uint32_t numExitingEdges = ExitingEdges.size()) { 689 BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT, 690 Denom); 691 auto Prob = NotTakenProb / numExitingEdges; 692 for (unsigned SuccIdx : ExitingEdges) 693 EdgeProbabilities[SuccIdx] = Prob; 694 } 695 696 if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) { 697 BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT, 698 Denom); 699 auto Prob = UnlikelyProb / numUnlikelyEdges; 700 for (unsigned SuccIdx : UnlikelyEdges) 701 EdgeProbabilities[SuccIdx] = Prob; 702 } 703 704 setEdgeProbability(BB, EdgeProbabilities); 705 return true; 706 } 707 708 bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB, 709 const TargetLibraryInfo *TLI) { 710 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); 711 if (!BI || !BI->isConditional()) 712 return false; 713 714 Value *Cond = BI->getCondition(); 715 ICmpInst *CI = dyn_cast<ICmpInst>(Cond); 716 if (!CI) 717 return false; 718 719 auto GetConstantInt = [](Value *V) { 720 if (auto *I = dyn_cast<BitCastInst>(V)) 721 return dyn_cast<ConstantInt>(I->getOperand(0)); 722 return dyn_cast<ConstantInt>(V); 723 }; 724 725 Value *RHS = CI->getOperand(1); 726 ConstantInt *CV = GetConstantInt(RHS); 727 if (!CV) 728 return false; 729 730 // If the LHS is the result of AND'ing a value with a single bit bitmask, 731 // we don't have information about probabilities. 732 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0))) 733 if (LHS->getOpcode() == Instruction::And) 734 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) 735 if (AndRHS->getValue().isPowerOf2()) 736 return false; 737 738 // Check if the LHS is the return value of a library function 739 LibFunc Func = NumLibFuncs; 740 if (TLI) 741 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0))) 742 if (Function *CalledFn = Call->getCalledFunction()) 743 TLI->getLibFunc(*CalledFn, Func); 744 745 bool isProb; 746 if (Func == LibFunc_strcasecmp || 747 Func == LibFunc_strcmp || 748 Func == LibFunc_strncasecmp || 749 Func == LibFunc_strncmp || 750 Func == LibFunc_memcmp) { 751 // strcmp and similar functions return zero, negative, or positive, if the 752 // first string is equal, less, or greater than the second. We consider it 753 // likely that the strings are not equal, so a comparison with zero is 754 // probably false, but also a comparison with any other number is also 755 // probably false given that what exactly is returned for nonzero values is 756 // not specified. Any kind of comparison other than equality we know 757 // nothing about. 758 switch (CI->getPredicate()) { 759 case CmpInst::ICMP_EQ: 760 isProb = false; 761 break; 762 case CmpInst::ICMP_NE: 763 isProb = true; 764 break; 765 default: 766 return false; 767 } 768 } else if (CV->isZero()) { 769 switch (CI->getPredicate()) { 770 case CmpInst::ICMP_EQ: 771 // X == 0 -> Unlikely 772 isProb = false; 773 break; 774 case CmpInst::ICMP_NE: 775 // X != 0 -> Likely 776 isProb = true; 777 break; 778 case CmpInst::ICMP_SLT: 779 // X < 0 -> Unlikely 780 isProb = false; 781 break; 782 case CmpInst::ICMP_SGT: 783 // X > 0 -> Likely 784 isProb = true; 785 break; 786 default: 787 return false; 788 } 789 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) { 790 // InstCombine canonicalizes X <= 0 into X < 1. 791 // X <= 0 -> Unlikely 792 isProb = false; 793 } else if (CV->isMinusOne()) { 794 switch (CI->getPredicate()) { 795 case CmpInst::ICMP_EQ: 796 // X == -1 -> Unlikely 797 isProb = false; 798 break; 799 case CmpInst::ICMP_NE: 800 // X != -1 -> Likely 801 isProb = true; 802 break; 803 case CmpInst::ICMP_SGT: 804 // InstCombine canonicalizes X >= 0 into X > -1. 805 // X >= 0 -> Likely 806 isProb = true; 807 break; 808 default: 809 return false; 810 } 811 } else { 812 return false; 813 } 814 815 BranchProbability TakenProb(ZH_TAKEN_WEIGHT, 816 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT); 817 BranchProbability UntakenProb(ZH_NONTAKEN_WEIGHT, 818 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT); 819 if (!isProb) 820 std::swap(TakenProb, UntakenProb); 821 822 setEdgeProbability( 823 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb})); 824 return true; 825 } 826 827 bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) { 828 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); 829 if (!BI || !BI->isConditional()) 830 return false; 831 832 Value *Cond = BI->getCondition(); 833 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond); 834 if (!FCmp) 835 return false; 836 837 uint32_t TakenWeight = FPH_TAKEN_WEIGHT; 838 uint32_t NontakenWeight = FPH_NONTAKEN_WEIGHT; 839 bool isProb; 840 if (FCmp->isEquality()) { 841 // f1 == f2 -> Unlikely 842 // f1 != f2 -> Likely 843 isProb = !FCmp->isTrueWhenEqual(); 844 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) { 845 // !isnan -> Likely 846 isProb = true; 847 TakenWeight = FPH_ORD_WEIGHT; 848 NontakenWeight = FPH_UNO_WEIGHT; 849 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) { 850 // isnan -> Unlikely 851 isProb = false; 852 TakenWeight = FPH_ORD_WEIGHT; 853 NontakenWeight = FPH_UNO_WEIGHT; 854 } else { 855 return false; 856 } 857 858 BranchProbability TakenProb(TakenWeight, TakenWeight + NontakenWeight); 859 BranchProbability UntakenProb(NontakenWeight, TakenWeight + NontakenWeight); 860 if (!isProb) 861 std::swap(TakenProb, UntakenProb); 862 863 setEdgeProbability( 864 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb})); 865 return true; 866 } 867 868 bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) { 869 const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()); 870 if (!II) 871 return false; 872 873 BranchProbability TakenProb(IH_TAKEN_WEIGHT, 874 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT); 875 setEdgeProbability( 876 BB, SmallVector<BranchProbability, 2>({TakenProb, TakenProb.getCompl()})); 877 return true; 878 } 879 880 void BranchProbabilityInfo::releaseMemory() { 881 Probs.clear(); 882 Handles.clear(); 883 } 884 885 bool BranchProbabilityInfo::invalidate(Function &, const PreservedAnalyses &PA, 886 FunctionAnalysisManager::Invalidator &) { 887 // Check whether the analysis, all analyses on functions, or the function's 888 // CFG have been preserved. 889 auto PAC = PA.getChecker<BranchProbabilityAnalysis>(); 890 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() || 891 PAC.preservedSet<CFGAnalyses>()); 892 } 893 894 void BranchProbabilityInfo::print(raw_ostream &OS) const { 895 OS << "---- Branch Probabilities ----\n"; 896 // We print the probabilities from the last function the analysis ran over, 897 // or the function it is currently running over. 898 assert(LastF && "Cannot print prior to running over a function"); 899 for (const auto &BI : *LastF) { 900 for (const_succ_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE; 901 ++SI) { 902 printEdgeProbability(OS << " ", &BI, *SI); 903 } 904 } 905 } 906 907 bool BranchProbabilityInfo:: 908 isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const { 909 // Hot probability is at least 4/5 = 80% 910 // FIXME: Compare against a static "hot" BranchProbability. 911 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5); 912 } 913 914 const BasicBlock * 915 BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const { 916 auto MaxProb = BranchProbability::getZero(); 917 const BasicBlock *MaxSucc = nullptr; 918 919 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) { 920 const BasicBlock *Succ = *I; 921 auto Prob = getEdgeProbability(BB, Succ); 922 if (Prob > MaxProb) { 923 MaxProb = Prob; 924 MaxSucc = Succ; 925 } 926 } 927 928 // Hot probability is at least 4/5 = 80% 929 if (MaxProb > BranchProbability(4, 5)) 930 return MaxSucc; 931 932 return nullptr; 933 } 934 935 /// Get the raw edge probability for the edge. If can't find it, return a 936 /// default probability 1/N where N is the number of successors. Here an edge is 937 /// specified using PredBlock and an 938 /// index to the successors. 939 BranchProbability 940 BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src, 941 unsigned IndexInSuccessors) const { 942 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors)); 943 944 if (I != Probs.end()) 945 return I->second; 946 947 return {1, static_cast<uint32_t>(succ_size(Src))}; 948 } 949 950 BranchProbability 951 BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src, 952 const_succ_iterator Dst) const { 953 return getEdgeProbability(Src, Dst.getSuccessorIndex()); 954 } 955 956 /// Get the raw edge probability calculated for the block pair. This returns the 957 /// sum of all raw edge probabilities from Src to Dst. 958 BranchProbability 959 BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src, 960 const BasicBlock *Dst) const { 961 auto Prob = BranchProbability::getZero(); 962 bool FoundProb = false; 963 uint32_t EdgeCount = 0; 964 for (const_succ_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I) 965 if (*I == Dst) { 966 ++EdgeCount; 967 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex())); 968 if (MapI != Probs.end()) { 969 FoundProb = true; 970 Prob += MapI->second; 971 } 972 } 973 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src)); 974 return FoundProb ? Prob : BranchProbability(EdgeCount, succ_num); 975 } 976 977 /// Set the edge probability for a given edge specified by PredBlock and an 978 /// index to the successors. 979 void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src, 980 unsigned IndexInSuccessors, 981 BranchProbability Prob) { 982 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob; 983 Handles.insert(BasicBlockCallbackVH(Src, this)); 984 LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> " 985 << IndexInSuccessors << " successor probability to " << Prob 986 << "\n"); 987 } 988 989 /// Set the edge probability for all edges at once. 990 void BranchProbabilityInfo::setEdgeProbability( 991 const BasicBlock *Src, const SmallVectorImpl<BranchProbability> &Probs) { 992 assert(Src->getTerminator()->getNumSuccessors() == Probs.size()); 993 if (Probs.size() == 0) 994 return; // Nothing to set. 995 996 uint64_t TotalNumerator = 0; 997 for (unsigned SuccIdx = 0; SuccIdx < Probs.size(); ++SuccIdx) { 998 setEdgeProbability(Src, SuccIdx, Probs[SuccIdx]); 999 TotalNumerator += Probs[SuccIdx].getNumerator(); 1000 } 1001 1002 // Because of rounding errors the total probability cannot be checked to be 1003 // 1.0 exactly. That is TotalNumerator == BranchProbability::getDenominator. 1004 // Instead, every single probability in Probs must be as accurate as possible. 1005 // This results in error 1/denominator at most, thus the total absolute error 1006 // should be within Probs.size / BranchProbability::getDenominator. 1007 assert(TotalNumerator <= BranchProbability::getDenominator() + Probs.size()); 1008 assert(TotalNumerator >= BranchProbability::getDenominator() - Probs.size()); 1009 } 1010 1011 raw_ostream & 1012 BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS, 1013 const BasicBlock *Src, 1014 const BasicBlock *Dst) const { 1015 const BranchProbability Prob = getEdgeProbability(Src, Dst); 1016 OS << "edge " << Src->getName() << " -> " << Dst->getName() 1017 << " probability is " << Prob 1018 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n"); 1019 1020 return OS; 1021 } 1022 1023 void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) { 1024 for (auto I = Probs.begin(), E = Probs.end(); I != E; ++I) { 1025 auto Key = I->first; 1026 if (Key.first == BB) 1027 Probs.erase(Key); 1028 } 1029 } 1030 1031 void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI, 1032 const TargetLibraryInfo *TLI, 1033 PostDominatorTree *PDT) { 1034 LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName() 1035 << " ----\n\n"); 1036 LastF = &F; // Store the last function we ran on for printing. 1037 assert(PostDominatedByUnreachable.empty()); 1038 assert(PostDominatedByColdCall.empty()); 1039 1040 // Record SCC numbers of blocks in the CFG to identify irreducible loops. 1041 // FIXME: We could only calculate this if the CFG is known to be irreducible 1042 // (perhaps cache this info in LoopInfo if we can easily calculate it there?). 1043 int SccNum = 0; 1044 SccInfo SccI; 1045 for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd(); 1046 ++It, ++SccNum) { 1047 // Ignore single-block SCCs since they either aren't loops or LoopInfo will 1048 // catch them. 1049 const std::vector<const BasicBlock *> &Scc = *It; 1050 if (Scc.size() == 1) 1051 continue; 1052 1053 LLVM_DEBUG(dbgs() << "BPI: SCC " << SccNum << ":"); 1054 for (auto *BB : Scc) { 1055 LLVM_DEBUG(dbgs() << " " << BB->getName()); 1056 SccI.SccNums[BB] = SccNum; 1057 } 1058 LLVM_DEBUG(dbgs() << "\n"); 1059 } 1060 1061 std::unique_ptr<PostDominatorTree> PDTPtr; 1062 1063 if (!PDT) { 1064 PDTPtr = std::make_unique<PostDominatorTree>(const_cast<Function &>(F)); 1065 PDT = PDTPtr.get(); 1066 } 1067 1068 computePostDominatedByUnreachable(F, PDT); 1069 computePostDominatedByColdCall(F, PDT); 1070 1071 // Walk the basic blocks in post-order so that we can build up state about 1072 // the successors of a block iteratively. 1073 for (auto BB : post_order(&F.getEntryBlock())) { 1074 LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName() 1075 << "\n"); 1076 // If there is no at least two successors, no sense to set probability. 1077 if (BB->getTerminator()->getNumSuccessors() < 2) 1078 continue; 1079 if (calcMetadataWeights(BB)) 1080 continue; 1081 if (calcInvokeHeuristics(BB)) 1082 continue; 1083 if (calcUnreachableHeuristics(BB)) 1084 continue; 1085 if (calcColdCallHeuristics(BB)) 1086 continue; 1087 if (calcLoopBranchHeuristics(BB, LI, SccI)) 1088 continue; 1089 if (calcPointerHeuristics(BB)) 1090 continue; 1091 if (calcZeroHeuristics(BB, TLI)) 1092 continue; 1093 if (calcFloatingPointHeuristics(BB)) 1094 continue; 1095 } 1096 1097 PostDominatedByUnreachable.clear(); 1098 PostDominatedByColdCall.clear(); 1099 1100 if (PrintBranchProb && 1101 (PrintBranchProbFuncName.empty() || 1102 F.getName().equals(PrintBranchProbFuncName))) { 1103 print(dbgs()); 1104 } 1105 } 1106 1107 void BranchProbabilityInfoWrapperPass::getAnalysisUsage( 1108 AnalysisUsage &AU) const { 1109 // We require DT so it's available when LI is available. The LI updating code 1110 // asserts that DT is also present so if we don't make sure that we have DT 1111 // here, that assert will trigger. 1112 AU.addRequired<DominatorTreeWrapperPass>(); 1113 AU.addRequired<LoopInfoWrapperPass>(); 1114 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1115 AU.addRequired<PostDominatorTreeWrapperPass>(); 1116 AU.setPreservesAll(); 1117 } 1118 1119 bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) { 1120 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1121 const TargetLibraryInfo &TLI = 1122 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 1123 PostDominatorTree &PDT = 1124 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 1125 BPI.calculate(F, LI, &TLI, &PDT); 1126 return false; 1127 } 1128 1129 void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); } 1130 1131 void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS, 1132 const Module *) const { 1133 BPI.print(OS); 1134 } 1135 1136 AnalysisKey BranchProbabilityAnalysis::Key; 1137 BranchProbabilityInfo 1138 BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) { 1139 BranchProbabilityInfo BPI; 1140 BPI.calculate(F, AM.getResult<LoopAnalysis>(F), 1141 &AM.getResult<TargetLibraryAnalysis>(F), 1142 &AM.getResult<PostDominatorTreeAnalysis>(F)); 1143 return BPI; 1144 } 1145 1146 PreservedAnalyses 1147 BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 1148 OS << "Printing analysis results of BPI for function " 1149 << "'" << F.getName() << "':" 1150 << "\n"; 1151 AM.getResult<BranchProbabilityAnalysis>(F).print(OS); 1152 return PreservedAnalyses::all(); 1153 } 1154