1 //===-- BranchProbabilityInfo.cpp - Branch Probability Analysis -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Loops should be simplified before this analysis. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #define DEBUG_TYPE "branch-prob" 15 #include "llvm/Analysis/BranchProbabilityInfo.h" 16 #include "llvm/ADT/PostOrderIterator.h" 17 #include "llvm/Analysis/LoopInfo.h" 18 #include "llvm/IR/CFG.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/Function.h" 21 #include "llvm/IR/Instructions.h" 22 #include "llvm/IR/LLVMContext.h" 23 #include "llvm/IR/Metadata.h" 24 #include "llvm/Support/Debug.h" 25 26 using namespace llvm; 27 28 INITIALIZE_PASS_BEGIN(BranchProbabilityInfo, "branch-prob", 29 "Branch Probability Analysis", false, true) 30 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 31 INITIALIZE_PASS_END(BranchProbabilityInfo, "branch-prob", 32 "Branch Probability Analysis", false, true) 33 34 char BranchProbabilityInfo::ID = 0; 35 36 // Weights are for internal use only. They are used by heuristics to help to 37 // estimate edges' probability. Example: 38 // 39 // Using "Loop Branch Heuristics" we predict weights of edges for the 40 // block BB2. 41 // ... 42 // | 43 // V 44 // BB1<-+ 45 // | | 46 // | | (Weight = 124) 47 // V | 48 // BB2--+ 49 // | 50 // | (Weight = 4) 51 // V 52 // BB3 53 // 54 // Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875 55 // Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125 56 static const uint32_t LBH_TAKEN_WEIGHT = 124; 57 static const uint32_t LBH_NONTAKEN_WEIGHT = 4; 58 59 /// \brief Unreachable-terminating branch taken weight. 60 /// 61 /// This is the weight for a branch being taken to a block that terminates 62 /// (eventually) in unreachable. These are predicted as unlikely as possible. 63 static const uint32_t UR_TAKEN_WEIGHT = 1; 64 65 /// \brief Unreachable-terminating branch not-taken weight. 66 /// 67 /// This is the weight for a branch not being taken toward a block that 68 /// terminates (eventually) in unreachable. Such a branch is essentially never 69 /// taken. Set the weight to an absurdly high value so that nested loops don't 70 /// easily subsume it. 71 static const uint32_t UR_NONTAKEN_WEIGHT = 1024*1024 - 1; 72 73 /// \brief Weight for a branch taken going into a cold block. 74 /// 75 /// This is the weight for a branch taken toward a block marked 76 /// cold. A block is marked cold if it's postdominated by a 77 /// block containing a call to a cold function. Cold functions 78 /// are those marked with attribute 'cold'. 79 static const uint32_t CC_TAKEN_WEIGHT = 4; 80 81 /// \brief Weight for a branch not-taken into a cold block. 82 /// 83 /// This is the weight for a branch not taken toward a block marked 84 /// cold. 85 static const uint32_t CC_NONTAKEN_WEIGHT = 64; 86 87 static const uint32_t PH_TAKEN_WEIGHT = 20; 88 static const uint32_t PH_NONTAKEN_WEIGHT = 12; 89 90 static const uint32_t ZH_TAKEN_WEIGHT = 20; 91 static const uint32_t ZH_NONTAKEN_WEIGHT = 12; 92 93 static const uint32_t FPH_TAKEN_WEIGHT = 20; 94 static const uint32_t FPH_NONTAKEN_WEIGHT = 12; 95 96 /// \brief Invoke-terminating normal branch taken weight 97 /// 98 /// This is the weight for branching to the normal destination of an invoke 99 /// instruction. We expect this to happen most of the time. Set the weight to an 100 /// absurdly high value so that nested loops subsume it. 101 static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1; 102 103 /// \brief Invoke-terminating normal branch not-taken weight. 104 /// 105 /// This is the weight for branching to the unwind destination of an invoke 106 /// instruction. This is essentially never taken. 107 static const uint32_t IH_NONTAKEN_WEIGHT = 1; 108 109 // Standard weight value. Used when none of the heuristics set weight for 110 // the edge. 111 static const uint32_t NORMAL_WEIGHT = 16; 112 113 // Minimum weight of an edge. Please note, that weight is NEVER 0. 114 static const uint32_t MIN_WEIGHT = 1; 115 116 static uint32_t getMaxWeightFor(BasicBlock *BB) { 117 return UINT32_MAX / BB->getTerminator()->getNumSuccessors(); 118 } 119 120 121 /// \brief Calculate edge weights for successors lead to unreachable. 122 /// 123 /// Predict that a successor which leads necessarily to an 124 /// unreachable-terminated block as extremely unlikely. 125 bool BranchProbabilityInfo::calcUnreachableHeuristics(BasicBlock *BB) { 126 TerminatorInst *TI = BB->getTerminator(); 127 if (TI->getNumSuccessors() == 0) { 128 if (isa<UnreachableInst>(TI)) 129 PostDominatedByUnreachable.insert(BB); 130 return false; 131 } 132 133 SmallVector<unsigned, 4> UnreachableEdges; 134 SmallVector<unsigned, 4> ReachableEdges; 135 136 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) { 137 if (PostDominatedByUnreachable.count(*I)) 138 UnreachableEdges.push_back(I.getSuccessorIndex()); 139 else 140 ReachableEdges.push_back(I.getSuccessorIndex()); 141 } 142 143 // If all successors are in the set of blocks post-dominated by unreachable, 144 // this block is too. 145 if (UnreachableEdges.size() == TI->getNumSuccessors()) 146 PostDominatedByUnreachable.insert(BB); 147 148 // Skip probabilities if this block has a single successor or if all were 149 // reachable. 150 if (TI->getNumSuccessors() == 1 || UnreachableEdges.empty()) 151 return false; 152 153 uint32_t UnreachableWeight = 154 std::max(UR_TAKEN_WEIGHT / (unsigned)UnreachableEdges.size(), MIN_WEIGHT); 155 for (SmallVectorImpl<unsigned>::iterator I = UnreachableEdges.begin(), 156 E = UnreachableEdges.end(); 157 I != E; ++I) 158 setEdgeWeight(BB, *I, UnreachableWeight); 159 160 if (ReachableEdges.empty()) 161 return true; 162 uint32_t ReachableWeight = 163 std::max(UR_NONTAKEN_WEIGHT / (unsigned)ReachableEdges.size(), 164 NORMAL_WEIGHT); 165 for (SmallVectorImpl<unsigned>::iterator I = ReachableEdges.begin(), 166 E = ReachableEdges.end(); 167 I != E; ++I) 168 setEdgeWeight(BB, *I, ReachableWeight); 169 170 return true; 171 } 172 173 // Propagate existing explicit probabilities from either profile data or 174 // 'expect' intrinsic processing. 175 bool BranchProbabilityInfo::calcMetadataWeights(BasicBlock *BB) { 176 TerminatorInst *TI = BB->getTerminator(); 177 if (TI->getNumSuccessors() == 1) 178 return false; 179 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) 180 return false; 181 182 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof); 183 if (!WeightsNode) 184 return false; 185 186 // Ensure there are weights for all of the successors. Note that the first 187 // operand to the metadata node is a name, not a weight. 188 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1) 189 return false; 190 191 // Build up the final weights that will be used in a temporary buffer, but 192 // don't add them until all weihts are present. Each weight value is clamped 193 // to [1, getMaxWeightFor(BB)]. 194 uint32_t WeightLimit = getMaxWeightFor(BB); 195 SmallVector<uint32_t, 2> Weights; 196 Weights.reserve(TI->getNumSuccessors()); 197 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) { 198 ConstantInt *Weight = dyn_cast<ConstantInt>(WeightsNode->getOperand(i)); 199 if (!Weight) 200 return false; 201 Weights.push_back( 202 std::max<uint32_t>(1, Weight->getLimitedValue(WeightLimit))); 203 } 204 assert(Weights.size() == TI->getNumSuccessors() && "Checked above"); 205 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 206 setEdgeWeight(BB, i, Weights[i]); 207 208 return true; 209 } 210 211 /// \brief Calculate edge weights for edges leading to cold blocks. 212 /// 213 /// A cold block is one post-dominated by a block with a call to a 214 /// cold function. Those edges are unlikely to be taken, so we give 215 /// them relatively low weight. 216 /// 217 /// Return true if we could compute the weights for cold edges. 218 /// Return false, otherwise. 219 bool BranchProbabilityInfo::calcColdCallHeuristics(BasicBlock *BB) { 220 TerminatorInst *TI = BB->getTerminator(); 221 if (TI->getNumSuccessors() == 0) 222 return false; 223 224 // Determine which successors are post-dominated by a cold block. 225 SmallVector<unsigned, 4> ColdEdges; 226 SmallVector<unsigned, 4> NormalEdges; 227 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) 228 if (PostDominatedByColdCall.count(*I)) 229 ColdEdges.push_back(I.getSuccessorIndex()); 230 else 231 NormalEdges.push_back(I.getSuccessorIndex()); 232 233 // If all successors are in the set of blocks post-dominated by cold calls, 234 // this block is in the set post-dominated by cold calls. 235 if (ColdEdges.size() == TI->getNumSuccessors()) 236 PostDominatedByColdCall.insert(BB); 237 else { 238 // Otherwise, if the block itself contains a cold function, add it to the 239 // set of blocks postdominated by a cold call. 240 assert(!PostDominatedByColdCall.count(BB)); 241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 242 if (CallInst *CI = dyn_cast<CallInst>(I)) 243 if (CI->hasFnAttr(Attribute::Cold)) { 244 PostDominatedByColdCall.insert(BB); 245 break; 246 } 247 } 248 249 // Skip probabilities if this block has a single successor. 250 if (TI->getNumSuccessors() == 1 || ColdEdges.empty()) 251 return false; 252 253 uint32_t ColdWeight = 254 std::max(CC_TAKEN_WEIGHT / (unsigned) ColdEdges.size(), MIN_WEIGHT); 255 for (SmallVectorImpl<unsigned>::iterator I = ColdEdges.begin(), 256 E = ColdEdges.end(); 257 I != E; ++I) 258 setEdgeWeight(BB, *I, ColdWeight); 259 260 if (NormalEdges.empty()) 261 return true; 262 uint32_t NormalWeight = std::max( 263 CC_NONTAKEN_WEIGHT / (unsigned) NormalEdges.size(), NORMAL_WEIGHT); 264 for (SmallVectorImpl<unsigned>::iterator I = NormalEdges.begin(), 265 E = NormalEdges.end(); 266 I != E; ++I) 267 setEdgeWeight(BB, *I, NormalWeight); 268 269 return true; 270 } 271 272 // Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion 273 // between two pointer or pointer and NULL will fail. 274 bool BranchProbabilityInfo::calcPointerHeuristics(BasicBlock *BB) { 275 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator()); 276 if (!BI || !BI->isConditional()) 277 return false; 278 279 Value *Cond = BI->getCondition(); 280 ICmpInst *CI = dyn_cast<ICmpInst>(Cond); 281 if (!CI || !CI->isEquality()) 282 return false; 283 284 Value *LHS = CI->getOperand(0); 285 286 if (!LHS->getType()->isPointerTy()) 287 return false; 288 289 assert(CI->getOperand(1)->getType()->isPointerTy()); 290 291 // p != 0 -> isProb = true 292 // p == 0 -> isProb = false 293 // p != q -> isProb = true 294 // p == q -> isProb = false; 295 unsigned TakenIdx = 0, NonTakenIdx = 1; 296 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE; 297 if (!isProb) 298 std::swap(TakenIdx, NonTakenIdx); 299 300 setEdgeWeight(BB, TakenIdx, PH_TAKEN_WEIGHT); 301 setEdgeWeight(BB, NonTakenIdx, PH_NONTAKEN_WEIGHT); 302 return true; 303 } 304 305 // Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges 306 // as taken, exiting edges as not-taken. 307 bool BranchProbabilityInfo::calcLoopBranchHeuristics(BasicBlock *BB) { 308 Loop *L = LI->getLoopFor(BB); 309 if (!L) 310 return false; 311 312 SmallVector<unsigned, 8> BackEdges; 313 SmallVector<unsigned, 8> ExitingEdges; 314 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop. 315 316 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) { 317 if (!L->contains(*I)) 318 ExitingEdges.push_back(I.getSuccessorIndex()); 319 else if (L->getHeader() == *I) 320 BackEdges.push_back(I.getSuccessorIndex()); 321 else 322 InEdges.push_back(I.getSuccessorIndex()); 323 } 324 325 if (BackEdges.empty() && ExitingEdges.empty()) 326 return false; 327 328 if (uint32_t numBackEdges = BackEdges.size()) { 329 uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges; 330 if (backWeight < NORMAL_WEIGHT) 331 backWeight = NORMAL_WEIGHT; 332 333 for (SmallVectorImpl<unsigned>::iterator EI = BackEdges.begin(), 334 EE = BackEdges.end(); EI != EE; ++EI) { 335 setEdgeWeight(BB, *EI, backWeight); 336 } 337 } 338 339 if (uint32_t numInEdges = InEdges.size()) { 340 uint32_t inWeight = LBH_TAKEN_WEIGHT / numInEdges; 341 if (inWeight < NORMAL_WEIGHT) 342 inWeight = NORMAL_WEIGHT; 343 344 for (SmallVectorImpl<unsigned>::iterator EI = InEdges.begin(), 345 EE = InEdges.end(); EI != EE; ++EI) { 346 setEdgeWeight(BB, *EI, inWeight); 347 } 348 } 349 350 if (uint32_t numExitingEdges = ExitingEdges.size()) { 351 uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numExitingEdges; 352 if (exitWeight < MIN_WEIGHT) 353 exitWeight = MIN_WEIGHT; 354 355 for (SmallVectorImpl<unsigned>::iterator EI = ExitingEdges.begin(), 356 EE = ExitingEdges.end(); EI != EE; ++EI) { 357 setEdgeWeight(BB, *EI, exitWeight); 358 } 359 } 360 361 return true; 362 } 363 364 bool BranchProbabilityInfo::calcZeroHeuristics(BasicBlock *BB) { 365 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator()); 366 if (!BI || !BI->isConditional()) 367 return false; 368 369 Value *Cond = BI->getCondition(); 370 ICmpInst *CI = dyn_cast<ICmpInst>(Cond); 371 if (!CI) 372 return false; 373 374 Value *RHS = CI->getOperand(1); 375 ConstantInt *CV = dyn_cast<ConstantInt>(RHS); 376 if (!CV) 377 return false; 378 379 bool isProb; 380 if (CV->isZero()) { 381 switch (CI->getPredicate()) { 382 case CmpInst::ICMP_EQ: 383 // X == 0 -> Unlikely 384 isProb = false; 385 break; 386 case CmpInst::ICMP_NE: 387 // X != 0 -> Likely 388 isProb = true; 389 break; 390 case CmpInst::ICMP_SLT: 391 // X < 0 -> Unlikely 392 isProb = false; 393 break; 394 case CmpInst::ICMP_SGT: 395 // X > 0 -> Likely 396 isProb = true; 397 break; 398 default: 399 return false; 400 } 401 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) { 402 // InstCombine canonicalizes X <= 0 into X < 1. 403 // X <= 0 -> Unlikely 404 isProb = false; 405 } else if (CV->isAllOnesValue()) { 406 switch (CI->getPredicate()) { 407 case CmpInst::ICMP_EQ: 408 // X == -1 -> Unlikely 409 isProb = false; 410 break; 411 case CmpInst::ICMP_NE: 412 // X != -1 -> Likely 413 isProb = true; 414 break; 415 case CmpInst::ICMP_SGT: 416 // InstCombine canonicalizes X >= 0 into X > -1. 417 // X >= 0 -> Likely 418 isProb = true; 419 break; 420 default: 421 return false; 422 } 423 } else { 424 return false; 425 } 426 427 unsigned TakenIdx = 0, NonTakenIdx = 1; 428 429 if (!isProb) 430 std::swap(TakenIdx, NonTakenIdx); 431 432 setEdgeWeight(BB, TakenIdx, ZH_TAKEN_WEIGHT); 433 setEdgeWeight(BB, NonTakenIdx, ZH_NONTAKEN_WEIGHT); 434 435 return true; 436 } 437 438 bool BranchProbabilityInfo::calcFloatingPointHeuristics(BasicBlock *BB) { 439 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); 440 if (!BI || !BI->isConditional()) 441 return false; 442 443 Value *Cond = BI->getCondition(); 444 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond); 445 if (!FCmp) 446 return false; 447 448 bool isProb; 449 if (FCmp->isEquality()) { 450 // f1 == f2 -> Unlikely 451 // f1 != f2 -> Likely 452 isProb = !FCmp->isTrueWhenEqual(); 453 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) { 454 // !isnan -> Likely 455 isProb = true; 456 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) { 457 // isnan -> Unlikely 458 isProb = false; 459 } else { 460 return false; 461 } 462 463 unsigned TakenIdx = 0, NonTakenIdx = 1; 464 465 if (!isProb) 466 std::swap(TakenIdx, NonTakenIdx); 467 468 setEdgeWeight(BB, TakenIdx, FPH_TAKEN_WEIGHT); 469 setEdgeWeight(BB, NonTakenIdx, FPH_NONTAKEN_WEIGHT); 470 471 return true; 472 } 473 474 bool BranchProbabilityInfo::calcInvokeHeuristics(BasicBlock *BB) { 475 InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()); 476 if (!II) 477 return false; 478 479 setEdgeWeight(BB, 0/*Index for Normal*/, IH_TAKEN_WEIGHT); 480 setEdgeWeight(BB, 1/*Index for Unwind*/, IH_NONTAKEN_WEIGHT); 481 return true; 482 } 483 484 void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const { 485 AU.addRequired<LoopInfo>(); 486 AU.setPreservesAll(); 487 } 488 489 bool BranchProbabilityInfo::runOnFunction(Function &F) { 490 DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName() 491 << " ----\n\n"); 492 LastF = &F; // Store the last function we ran on for printing. 493 LI = &getAnalysis<LoopInfo>(); 494 assert(PostDominatedByUnreachable.empty()); 495 assert(PostDominatedByColdCall.empty()); 496 497 // Walk the basic blocks in post-order so that we can build up state about 498 // the successors of a block iteratively. 499 for (po_iterator<BasicBlock *> I = po_begin(&F.getEntryBlock()), 500 E = po_end(&F.getEntryBlock()); 501 I != E; ++I) { 502 DEBUG(dbgs() << "Computing probabilities for " << I->getName() << "\n"); 503 if (calcUnreachableHeuristics(*I)) 504 continue; 505 if (calcMetadataWeights(*I)) 506 continue; 507 if (calcColdCallHeuristics(*I)) 508 continue; 509 if (calcLoopBranchHeuristics(*I)) 510 continue; 511 if (calcPointerHeuristics(*I)) 512 continue; 513 if (calcZeroHeuristics(*I)) 514 continue; 515 if (calcFloatingPointHeuristics(*I)) 516 continue; 517 calcInvokeHeuristics(*I); 518 } 519 520 PostDominatedByUnreachable.clear(); 521 PostDominatedByColdCall.clear(); 522 return false; 523 } 524 525 void BranchProbabilityInfo::print(raw_ostream &OS, const Module *) const { 526 OS << "---- Branch Probabilities ----\n"; 527 // We print the probabilities from the last function the analysis ran over, 528 // or the function it is currently running over. 529 assert(LastF && "Cannot print prior to running over a function"); 530 for (Function::const_iterator BI = LastF->begin(), BE = LastF->end(); 531 BI != BE; ++BI) { 532 for (succ_const_iterator SI = succ_begin(BI), SE = succ_end(BI); 533 SI != SE; ++SI) { 534 printEdgeProbability(OS << " ", BI, *SI); 535 } 536 } 537 } 538 539 uint32_t BranchProbabilityInfo::getSumForBlock(const BasicBlock *BB) const { 540 uint32_t Sum = 0; 541 542 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) { 543 uint32_t Weight = getEdgeWeight(BB, I.getSuccessorIndex()); 544 uint32_t PrevSum = Sum; 545 546 Sum += Weight; 547 assert(Sum > PrevSum); (void) PrevSum; 548 } 549 550 return Sum; 551 } 552 553 bool BranchProbabilityInfo:: 554 isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const { 555 // Hot probability is at least 4/5 = 80% 556 // FIXME: Compare against a static "hot" BranchProbability. 557 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5); 558 } 559 560 BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const { 561 uint32_t Sum = 0; 562 uint32_t MaxWeight = 0; 563 BasicBlock *MaxSucc = nullptr; 564 565 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) { 566 BasicBlock *Succ = *I; 567 uint32_t Weight = getEdgeWeight(BB, Succ); 568 uint32_t PrevSum = Sum; 569 570 Sum += Weight; 571 assert(Sum > PrevSum); (void) PrevSum; 572 573 if (Weight > MaxWeight) { 574 MaxWeight = Weight; 575 MaxSucc = Succ; 576 } 577 } 578 579 // Hot probability is at least 4/5 = 80% 580 if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5)) 581 return MaxSucc; 582 583 return nullptr; 584 } 585 586 /// Get the raw edge weight for the edge. If can't find it, return 587 /// DEFAULT_WEIGHT value. Here an edge is specified using PredBlock and an index 588 /// to the successors. 589 uint32_t BranchProbabilityInfo:: 590 getEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors) const { 591 DenseMap<Edge, uint32_t>::const_iterator I = 592 Weights.find(std::make_pair(Src, IndexInSuccessors)); 593 594 if (I != Weights.end()) 595 return I->second; 596 597 return DEFAULT_WEIGHT; 598 } 599 600 uint32_t BranchProbabilityInfo::getEdgeWeight(const BasicBlock *Src, 601 succ_const_iterator Dst) const { 602 return getEdgeWeight(Src, Dst.getSuccessorIndex()); 603 } 604 605 /// Get the raw edge weight calculated for the block pair. This returns the sum 606 /// of all raw edge weights from Src to Dst. 607 uint32_t BranchProbabilityInfo:: 608 getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) const { 609 uint32_t Weight = 0; 610 DenseMap<Edge, uint32_t>::const_iterator MapI; 611 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I) 612 if (*I == Dst) { 613 MapI = Weights.find(std::make_pair(Src, I.getSuccessorIndex())); 614 if (MapI != Weights.end()) 615 Weight += MapI->second; 616 } 617 return (Weight == 0) ? DEFAULT_WEIGHT : Weight; 618 } 619 620 /// Set the edge weight for a given edge specified by PredBlock and an index 621 /// to the successors. 622 void BranchProbabilityInfo:: 623 setEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors, 624 uint32_t Weight) { 625 Weights[std::make_pair(Src, IndexInSuccessors)] = Weight; 626 DEBUG(dbgs() << "set edge " << Src->getName() << " -> " 627 << IndexInSuccessors << " successor weight to " 628 << Weight << "\n"); 629 } 630 631 /// Get an edge's probability, relative to other out-edges from Src. 632 BranchProbability BranchProbabilityInfo:: 633 getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const { 634 uint32_t N = getEdgeWeight(Src, IndexInSuccessors); 635 uint32_t D = getSumForBlock(Src); 636 637 return BranchProbability(N, D); 638 } 639 640 /// Get the probability of going from Src to Dst. It returns the sum of all 641 /// probabilities for edges from Src to Dst. 642 BranchProbability BranchProbabilityInfo:: 643 getEdgeProbability(const BasicBlock *Src, const BasicBlock *Dst) const { 644 645 uint32_t N = getEdgeWeight(Src, Dst); 646 uint32_t D = getSumForBlock(Src); 647 648 return BranchProbability(N, D); 649 } 650 651 raw_ostream & 652 BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS, 653 const BasicBlock *Src, 654 const BasicBlock *Dst) const { 655 656 const BranchProbability Prob = getEdgeProbability(Src, Dst); 657 OS << "edge " << Src->getName() << " -> " << Dst->getName() 658 << " probability is " << Prob 659 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n"); 660 661 return OS; 662 } 663