xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/BranchProbabilityInfo.cpp (revision 8bcb0991864975618c09697b1aca10683346d9f0)
10b57cec5SDimitry Andric //===- BranchProbabilityInfo.cpp - Branch Probability Analysis ------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Loops should be simplified before this analysis.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
140b57cec5SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SCCIterator.h"
160b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
200b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
210b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
220b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
230b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
240b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
250b57cec5SDimitry Andric #include "llvm/IR/Function.h"
260b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
270b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
280b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
290b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
300b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
310b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
320b57cec5SDimitry Andric #include "llvm/IR/Type.h"
330b57cec5SDimitry Andric #include "llvm/IR/Value.h"
340b57cec5SDimitry Andric #include "llvm/Pass.h"
350b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h"
360b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
370b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
380b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
390b57cec5SDimitry Andric #include <cassert>
400b57cec5SDimitry Andric #include <cstdint>
410b57cec5SDimitry Andric #include <iterator>
420b57cec5SDimitry Andric #include <utility>
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric using namespace llvm;
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric #define DEBUG_TYPE "branch-prob"
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric static cl::opt<bool> PrintBranchProb(
490b57cec5SDimitry Andric     "print-bpi", cl::init(false), cl::Hidden,
500b57cec5SDimitry Andric     cl::desc("Print the branch probability info."));
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric cl::opt<std::string> PrintBranchProbFuncName(
530b57cec5SDimitry Andric     "print-bpi-func-name", cl::Hidden,
540b57cec5SDimitry Andric     cl::desc("The option to specify the name of the function "
550b57cec5SDimitry Andric              "whose branch probability info is printed."));
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob",
580b57cec5SDimitry Andric                       "Branch Probability Analysis", false, true)
590b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
600b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
610b57cec5SDimitry Andric INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob",
620b57cec5SDimitry Andric                     "Branch Probability Analysis", false, true)
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric char BranchProbabilityInfoWrapperPass::ID = 0;
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric // Weights are for internal use only. They are used by heuristics to help to
670b57cec5SDimitry Andric // estimate edges' probability. Example:
680b57cec5SDimitry Andric //
690b57cec5SDimitry Andric // Using "Loop Branch Heuristics" we predict weights of edges for the
700b57cec5SDimitry Andric // block BB2.
710b57cec5SDimitry Andric //         ...
720b57cec5SDimitry Andric //          |
730b57cec5SDimitry Andric //          V
740b57cec5SDimitry Andric //         BB1<-+
750b57cec5SDimitry Andric //          |   |
760b57cec5SDimitry Andric //          |   | (Weight = 124)
770b57cec5SDimitry Andric //          V   |
780b57cec5SDimitry Andric //         BB2--+
790b57cec5SDimitry Andric //          |
800b57cec5SDimitry Andric //          | (Weight = 4)
810b57cec5SDimitry Andric //          V
820b57cec5SDimitry Andric //         BB3
830b57cec5SDimitry Andric //
840b57cec5SDimitry Andric // Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
850b57cec5SDimitry Andric // Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
860b57cec5SDimitry Andric static const uint32_t LBH_TAKEN_WEIGHT = 124;
870b57cec5SDimitry Andric static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
880b57cec5SDimitry Andric // Unlikely edges within a loop are half as likely as other edges
890b57cec5SDimitry Andric static const uint32_t LBH_UNLIKELY_WEIGHT = 62;
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric /// Unreachable-terminating branch taken probability.
920b57cec5SDimitry Andric ///
930b57cec5SDimitry Andric /// This is the probability for a branch being taken to a block that terminates
940b57cec5SDimitry Andric /// (eventually) in unreachable. These are predicted as unlikely as possible.
950b57cec5SDimitry Andric /// All reachable probability will equally share the remaining part.
960b57cec5SDimitry Andric static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1);
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric /// Weight for a branch taken going into a cold block.
990b57cec5SDimitry Andric ///
1000b57cec5SDimitry Andric /// This is the weight for a branch taken toward a block marked
1010b57cec5SDimitry Andric /// cold.  A block is marked cold if it's postdominated by a
1020b57cec5SDimitry Andric /// block containing a call to a cold function.  Cold functions
1030b57cec5SDimitry Andric /// are those marked with attribute 'cold'.
1040b57cec5SDimitry Andric static const uint32_t CC_TAKEN_WEIGHT = 4;
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric /// Weight for a branch not-taken into a cold block.
1070b57cec5SDimitry Andric ///
1080b57cec5SDimitry Andric /// This is the weight for a branch not taken toward a block marked
1090b57cec5SDimitry Andric /// cold.
1100b57cec5SDimitry Andric static const uint32_t CC_NONTAKEN_WEIGHT = 64;
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric static const uint32_t PH_TAKEN_WEIGHT = 20;
1130b57cec5SDimitry Andric static const uint32_t PH_NONTAKEN_WEIGHT = 12;
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric static const uint32_t ZH_TAKEN_WEIGHT = 20;
1160b57cec5SDimitry Andric static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric static const uint32_t FPH_TAKEN_WEIGHT = 20;
1190b57cec5SDimitry Andric static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
1200b57cec5SDimitry Andric 
121*8bcb0991SDimitry Andric /// This is the probability for an ordered floating point comparison.
122*8bcb0991SDimitry Andric static const uint32_t FPH_ORD_WEIGHT = 1024 * 1024 - 1;
123*8bcb0991SDimitry Andric /// This is the probability for an unordered floating point comparison, it means
124*8bcb0991SDimitry Andric /// one or two of the operands are NaN. Usually it is used to test for an
125*8bcb0991SDimitry Andric /// exceptional case, so the result is unlikely.
126*8bcb0991SDimitry Andric static const uint32_t FPH_UNO_WEIGHT = 1;
127*8bcb0991SDimitry Andric 
1280b57cec5SDimitry Andric /// Invoke-terminating normal branch taken weight
1290b57cec5SDimitry Andric ///
1300b57cec5SDimitry Andric /// This is the weight for branching to the normal destination of an invoke
1310b57cec5SDimitry Andric /// instruction. We expect this to happen most of the time. Set the weight to an
1320b57cec5SDimitry Andric /// absurdly high value so that nested loops subsume it.
1330b57cec5SDimitry Andric static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric /// Invoke-terminating normal branch not-taken weight.
1360b57cec5SDimitry Andric ///
1370b57cec5SDimitry Andric /// This is the weight for branching to the unwind destination of an invoke
1380b57cec5SDimitry Andric /// instruction. This is essentially never taken.
1390b57cec5SDimitry Andric static const uint32_t IH_NONTAKEN_WEIGHT = 1;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric /// Add \p BB to PostDominatedByUnreachable set if applicable.
1420b57cec5SDimitry Andric void
1430b57cec5SDimitry Andric BranchProbabilityInfo::updatePostDominatedByUnreachable(const BasicBlock *BB) {
1440b57cec5SDimitry Andric   const Instruction *TI = BB->getTerminator();
1450b57cec5SDimitry Andric   if (TI->getNumSuccessors() == 0) {
1460b57cec5SDimitry Andric     if (isa<UnreachableInst>(TI) ||
1470b57cec5SDimitry Andric         // If this block is terminated by a call to
1480b57cec5SDimitry Andric         // @llvm.experimental.deoptimize then treat it like an unreachable since
1490b57cec5SDimitry Andric         // the @llvm.experimental.deoptimize call is expected to practically
1500b57cec5SDimitry Andric         // never execute.
1510b57cec5SDimitry Andric         BB->getTerminatingDeoptimizeCall())
1520b57cec5SDimitry Andric       PostDominatedByUnreachable.insert(BB);
1530b57cec5SDimitry Andric     return;
1540b57cec5SDimitry Andric   }
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   // If the terminator is an InvokeInst, check only the normal destination block
1570b57cec5SDimitry Andric   // as the unwind edge of InvokeInst is also very unlikely taken.
1580b57cec5SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TI)) {
1590b57cec5SDimitry Andric     if (PostDominatedByUnreachable.count(II->getNormalDest()))
1600b57cec5SDimitry Andric       PostDominatedByUnreachable.insert(BB);
1610b57cec5SDimitry Andric     return;
1620b57cec5SDimitry Andric   }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   for (auto *I : successors(BB))
1650b57cec5SDimitry Andric     // If any of successor is not post dominated then BB is also not.
1660b57cec5SDimitry Andric     if (!PostDominatedByUnreachable.count(I))
1670b57cec5SDimitry Andric       return;
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   PostDominatedByUnreachable.insert(BB);
1700b57cec5SDimitry Andric }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric /// Add \p BB to PostDominatedByColdCall set if applicable.
1730b57cec5SDimitry Andric void
1740b57cec5SDimitry Andric BranchProbabilityInfo::updatePostDominatedByColdCall(const BasicBlock *BB) {
1750b57cec5SDimitry Andric   assert(!PostDominatedByColdCall.count(BB));
1760b57cec5SDimitry Andric   const Instruction *TI = BB->getTerminator();
1770b57cec5SDimitry Andric   if (TI->getNumSuccessors() == 0)
1780b57cec5SDimitry Andric     return;
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   // If all of successor are post dominated then BB is also done.
1810b57cec5SDimitry Andric   if (llvm::all_of(successors(BB), [&](const BasicBlock *SuccBB) {
1820b57cec5SDimitry Andric         return PostDominatedByColdCall.count(SuccBB);
1830b57cec5SDimitry Andric       })) {
1840b57cec5SDimitry Andric     PostDominatedByColdCall.insert(BB);
1850b57cec5SDimitry Andric     return;
1860b57cec5SDimitry Andric   }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   // If the terminator is an InvokeInst, check only the normal destination
1890b57cec5SDimitry Andric   // block as the unwind edge of InvokeInst is also very unlikely taken.
1900b57cec5SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TI))
1910b57cec5SDimitry Andric     if (PostDominatedByColdCall.count(II->getNormalDest())) {
1920b57cec5SDimitry Andric       PostDominatedByColdCall.insert(BB);
1930b57cec5SDimitry Andric       return;
1940b57cec5SDimitry Andric     }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   // Otherwise, if the block itself contains a cold function, add it to the
1970b57cec5SDimitry Andric   // set of blocks post-dominated by a cold call.
1980b57cec5SDimitry Andric   for (auto &I : *BB)
1990b57cec5SDimitry Andric     if (const CallInst *CI = dyn_cast<CallInst>(&I))
2000b57cec5SDimitry Andric       if (CI->hasFnAttr(Attribute::Cold)) {
2010b57cec5SDimitry Andric         PostDominatedByColdCall.insert(BB);
2020b57cec5SDimitry Andric         return;
2030b57cec5SDimitry Andric       }
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric /// Calculate edge weights for successors lead to unreachable.
2070b57cec5SDimitry Andric ///
2080b57cec5SDimitry Andric /// Predict that a successor which leads necessarily to an
2090b57cec5SDimitry Andric /// unreachable-terminated block as extremely unlikely.
2100b57cec5SDimitry Andric bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
2110b57cec5SDimitry Andric   const Instruction *TI = BB->getTerminator();
2120b57cec5SDimitry Andric   (void) TI;
2130b57cec5SDimitry Andric   assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
2140b57cec5SDimitry Andric   assert(!isa<InvokeInst>(TI) &&
2150b57cec5SDimitry Andric          "Invokes should have already been handled by calcInvokeHeuristics");
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric   SmallVector<unsigned, 4> UnreachableEdges;
2180b57cec5SDimitry Andric   SmallVector<unsigned, 4> ReachableEdges;
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric   for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
2210b57cec5SDimitry Andric     if (PostDominatedByUnreachable.count(*I))
2220b57cec5SDimitry Andric       UnreachableEdges.push_back(I.getSuccessorIndex());
2230b57cec5SDimitry Andric     else
2240b57cec5SDimitry Andric       ReachableEdges.push_back(I.getSuccessorIndex());
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   // Skip probabilities if all were reachable.
2270b57cec5SDimitry Andric   if (UnreachableEdges.empty())
2280b57cec5SDimitry Andric     return false;
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric   if (ReachableEdges.empty()) {
2310b57cec5SDimitry Andric     BranchProbability Prob(1, UnreachableEdges.size());
2320b57cec5SDimitry Andric     for (unsigned SuccIdx : UnreachableEdges)
2330b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
2340b57cec5SDimitry Andric     return true;
2350b57cec5SDimitry Andric   }
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   auto UnreachableProb = UR_TAKEN_PROB;
2380b57cec5SDimitry Andric   auto ReachableProb =
2390b57cec5SDimitry Andric       (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
2400b57cec5SDimitry Andric       ReachableEdges.size();
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric   for (unsigned SuccIdx : UnreachableEdges)
2430b57cec5SDimitry Andric     setEdgeProbability(BB, SuccIdx, UnreachableProb);
2440b57cec5SDimitry Andric   for (unsigned SuccIdx : ReachableEdges)
2450b57cec5SDimitry Andric     setEdgeProbability(BB, SuccIdx, ReachableProb);
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric   return true;
2480b57cec5SDimitry Andric }
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric // Propagate existing explicit probabilities from either profile data or
2510b57cec5SDimitry Andric // 'expect' intrinsic processing. Examine metadata against unreachable
2520b57cec5SDimitry Andric // heuristic. The probability of the edge coming to unreachable block is
2530b57cec5SDimitry Andric // set to min of metadata and unreachable heuristic.
2540b57cec5SDimitry Andric bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
2550b57cec5SDimitry Andric   const Instruction *TI = BB->getTerminator();
2560b57cec5SDimitry Andric   assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
2570b57cec5SDimitry Andric   if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI)))
2580b57cec5SDimitry Andric     return false;
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
2610b57cec5SDimitry Andric   if (!WeightsNode)
2620b57cec5SDimitry Andric     return false;
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   // Check that the number of successors is manageable.
2650b57cec5SDimitry Andric   assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   // Ensure there are weights for all of the successors. Note that the first
2680b57cec5SDimitry Andric   // operand to the metadata node is a name, not a weight.
2690b57cec5SDimitry Andric   if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
2700b57cec5SDimitry Andric     return false;
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   // Build up the final weights that will be used in a temporary buffer.
2730b57cec5SDimitry Andric   // Compute the sum of all weights to later decide whether they need to
2740b57cec5SDimitry Andric   // be scaled to fit in 32 bits.
2750b57cec5SDimitry Andric   uint64_t WeightSum = 0;
2760b57cec5SDimitry Andric   SmallVector<uint32_t, 2> Weights;
2770b57cec5SDimitry Andric   SmallVector<unsigned, 2> UnreachableIdxs;
2780b57cec5SDimitry Andric   SmallVector<unsigned, 2> ReachableIdxs;
2790b57cec5SDimitry Andric   Weights.reserve(TI->getNumSuccessors());
2800b57cec5SDimitry Andric   for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
2810b57cec5SDimitry Andric     ConstantInt *Weight =
2820b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i));
2830b57cec5SDimitry Andric     if (!Weight)
2840b57cec5SDimitry Andric       return false;
2850b57cec5SDimitry Andric     assert(Weight->getValue().getActiveBits() <= 32 &&
2860b57cec5SDimitry Andric            "Too many bits for uint32_t");
2870b57cec5SDimitry Andric     Weights.push_back(Weight->getZExtValue());
2880b57cec5SDimitry Andric     WeightSum += Weights.back();
2890b57cec5SDimitry Andric     if (PostDominatedByUnreachable.count(TI->getSuccessor(i - 1)))
2900b57cec5SDimitry Andric       UnreachableIdxs.push_back(i - 1);
2910b57cec5SDimitry Andric     else
2920b57cec5SDimitry Andric       ReachableIdxs.push_back(i - 1);
2930b57cec5SDimitry Andric   }
2940b57cec5SDimitry Andric   assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric   // If the sum of weights does not fit in 32 bits, scale every weight down
2970b57cec5SDimitry Andric   // accordingly.
2980b57cec5SDimitry Andric   uint64_t ScalingFactor =
2990b57cec5SDimitry Andric       (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   if (ScalingFactor > 1) {
3020b57cec5SDimitry Andric     WeightSum = 0;
3030b57cec5SDimitry Andric     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
3040b57cec5SDimitry Andric       Weights[i] /= ScalingFactor;
3050b57cec5SDimitry Andric       WeightSum += Weights[i];
3060b57cec5SDimitry Andric     }
3070b57cec5SDimitry Andric   }
3080b57cec5SDimitry Andric   assert(WeightSum <= UINT32_MAX &&
3090b57cec5SDimitry Andric          "Expected weights to scale down to 32 bits");
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   if (WeightSum == 0 || ReachableIdxs.size() == 0) {
3120b57cec5SDimitry Andric     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
3130b57cec5SDimitry Andric       Weights[i] = 1;
3140b57cec5SDimitry Andric     WeightSum = TI->getNumSuccessors();
3150b57cec5SDimitry Andric   }
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric   // Set the probability.
3180b57cec5SDimitry Andric   SmallVector<BranchProbability, 2> BP;
3190b57cec5SDimitry Andric   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
3200b57cec5SDimitry Andric     BP.push_back({ Weights[i], static_cast<uint32_t>(WeightSum) });
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric   // Examine the metadata against unreachable heuristic.
3230b57cec5SDimitry Andric   // If the unreachable heuristic is more strong then we use it for this edge.
3240b57cec5SDimitry Andric   if (UnreachableIdxs.size() > 0 && ReachableIdxs.size() > 0) {
3250b57cec5SDimitry Andric     auto ToDistribute = BranchProbability::getZero();
3260b57cec5SDimitry Andric     auto UnreachableProb = UR_TAKEN_PROB;
3270b57cec5SDimitry Andric     for (auto i : UnreachableIdxs)
3280b57cec5SDimitry Andric       if (UnreachableProb < BP[i]) {
3290b57cec5SDimitry Andric         ToDistribute += BP[i] - UnreachableProb;
3300b57cec5SDimitry Andric         BP[i] = UnreachableProb;
3310b57cec5SDimitry Andric       }
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric     // If we modified the probability of some edges then we must distribute
3340b57cec5SDimitry Andric     // the difference between reachable blocks.
3350b57cec5SDimitry Andric     if (ToDistribute > BranchProbability::getZero()) {
3360b57cec5SDimitry Andric       BranchProbability PerEdge = ToDistribute / ReachableIdxs.size();
3370b57cec5SDimitry Andric       for (auto i : ReachableIdxs)
3380b57cec5SDimitry Andric         BP[i] += PerEdge;
3390b57cec5SDimitry Andric     }
3400b57cec5SDimitry Andric   }
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
3430b57cec5SDimitry Andric     setEdgeProbability(BB, i, BP[i]);
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   return true;
3460b57cec5SDimitry Andric }
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric /// Calculate edge weights for edges leading to cold blocks.
3490b57cec5SDimitry Andric ///
3500b57cec5SDimitry Andric /// A cold block is one post-dominated by  a block with a call to a
3510b57cec5SDimitry Andric /// cold function.  Those edges are unlikely to be taken, so we give
3520b57cec5SDimitry Andric /// them relatively low weight.
3530b57cec5SDimitry Andric ///
3540b57cec5SDimitry Andric /// Return true if we could compute the weights for cold edges.
3550b57cec5SDimitry Andric /// Return false, otherwise.
3560b57cec5SDimitry Andric bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
3570b57cec5SDimitry Andric   const Instruction *TI = BB->getTerminator();
3580b57cec5SDimitry Andric   (void) TI;
3590b57cec5SDimitry Andric   assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
3600b57cec5SDimitry Andric   assert(!isa<InvokeInst>(TI) &&
3610b57cec5SDimitry Andric          "Invokes should have already been handled by calcInvokeHeuristics");
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric   // Determine which successors are post-dominated by a cold block.
3640b57cec5SDimitry Andric   SmallVector<unsigned, 4> ColdEdges;
3650b57cec5SDimitry Andric   SmallVector<unsigned, 4> NormalEdges;
3660b57cec5SDimitry Andric   for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
3670b57cec5SDimitry Andric     if (PostDominatedByColdCall.count(*I))
3680b57cec5SDimitry Andric       ColdEdges.push_back(I.getSuccessorIndex());
3690b57cec5SDimitry Andric     else
3700b57cec5SDimitry Andric       NormalEdges.push_back(I.getSuccessorIndex());
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric   // Skip probabilities if no cold edges.
3730b57cec5SDimitry Andric   if (ColdEdges.empty())
3740b57cec5SDimitry Andric     return false;
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric   if (NormalEdges.empty()) {
3770b57cec5SDimitry Andric     BranchProbability Prob(1, ColdEdges.size());
3780b57cec5SDimitry Andric     for (unsigned SuccIdx : ColdEdges)
3790b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
3800b57cec5SDimitry Andric     return true;
3810b57cec5SDimitry Andric   }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   auto ColdProb = BranchProbability::getBranchProbability(
3840b57cec5SDimitry Andric       CC_TAKEN_WEIGHT,
3850b57cec5SDimitry Andric       (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
3860b57cec5SDimitry Andric   auto NormalProb = BranchProbability::getBranchProbability(
3870b57cec5SDimitry Andric       CC_NONTAKEN_WEIGHT,
3880b57cec5SDimitry Andric       (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   for (unsigned SuccIdx : ColdEdges)
3910b57cec5SDimitry Andric     setEdgeProbability(BB, SuccIdx, ColdProb);
3920b57cec5SDimitry Andric   for (unsigned SuccIdx : NormalEdges)
3930b57cec5SDimitry Andric     setEdgeProbability(BB, SuccIdx, NormalProb);
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   return true;
3960b57cec5SDimitry Andric }
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric // Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
3990b57cec5SDimitry Andric // between two pointer or pointer and NULL will fail.
4000b57cec5SDimitry Andric bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
4010b57cec5SDimitry Andric   const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
4020b57cec5SDimitry Andric   if (!BI || !BI->isConditional())
4030b57cec5SDimitry Andric     return false;
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   Value *Cond = BI->getCondition();
4060b57cec5SDimitry Andric   ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
4070b57cec5SDimitry Andric   if (!CI || !CI->isEquality())
4080b57cec5SDimitry Andric     return false;
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   Value *LHS = CI->getOperand(0);
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric   if (!LHS->getType()->isPointerTy())
4130b57cec5SDimitry Andric     return false;
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric   assert(CI->getOperand(1)->getType()->isPointerTy());
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   // p != 0   ->   isProb = true
4180b57cec5SDimitry Andric   // p == 0   ->   isProb = false
4190b57cec5SDimitry Andric   // p != q   ->   isProb = true
4200b57cec5SDimitry Andric   // p == q   ->   isProb = false;
4210b57cec5SDimitry Andric   unsigned TakenIdx = 0, NonTakenIdx = 1;
4220b57cec5SDimitry Andric   bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
4230b57cec5SDimitry Andric   if (!isProb)
4240b57cec5SDimitry Andric     std::swap(TakenIdx, NonTakenIdx);
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   BranchProbability TakenProb(PH_TAKEN_WEIGHT,
4270b57cec5SDimitry Andric                               PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
4280b57cec5SDimitry Andric   setEdgeProbability(BB, TakenIdx, TakenProb);
4290b57cec5SDimitry Andric   setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
4300b57cec5SDimitry Andric   return true;
4310b57cec5SDimitry Andric }
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric static int getSCCNum(const BasicBlock *BB,
4340b57cec5SDimitry Andric                      const BranchProbabilityInfo::SccInfo &SccI) {
4350b57cec5SDimitry Andric   auto SccIt = SccI.SccNums.find(BB);
4360b57cec5SDimitry Andric   if (SccIt == SccI.SccNums.end())
4370b57cec5SDimitry Andric     return -1;
4380b57cec5SDimitry Andric   return SccIt->second;
4390b57cec5SDimitry Andric }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric // Consider any block that is an entry point to the SCC as a header.
4420b57cec5SDimitry Andric static bool isSCCHeader(const BasicBlock *BB, int SccNum,
4430b57cec5SDimitry Andric                         BranchProbabilityInfo::SccInfo &SccI) {
4440b57cec5SDimitry Andric   assert(getSCCNum(BB, SccI) == SccNum);
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   // Lazily compute the set of headers for a given SCC and cache the results
4470b57cec5SDimitry Andric   // in the SccHeaderMap.
4480b57cec5SDimitry Andric   if (SccI.SccHeaders.size() <= static_cast<unsigned>(SccNum))
4490b57cec5SDimitry Andric     SccI.SccHeaders.resize(SccNum + 1);
4500b57cec5SDimitry Andric   auto &HeaderMap = SccI.SccHeaders[SccNum];
4510b57cec5SDimitry Andric   bool Inserted;
4520b57cec5SDimitry Andric   BranchProbabilityInfo::SccHeaderMap::iterator HeaderMapIt;
4530b57cec5SDimitry Andric   std::tie(HeaderMapIt, Inserted) = HeaderMap.insert(std::make_pair(BB, false));
4540b57cec5SDimitry Andric   if (Inserted) {
4550b57cec5SDimitry Andric     bool IsHeader = llvm::any_of(make_range(pred_begin(BB), pred_end(BB)),
4560b57cec5SDimitry Andric                                  [&](const BasicBlock *Pred) {
4570b57cec5SDimitry Andric                                    return getSCCNum(Pred, SccI) != SccNum;
4580b57cec5SDimitry Andric                                  });
4590b57cec5SDimitry Andric     HeaderMapIt->second = IsHeader;
4600b57cec5SDimitry Andric     return IsHeader;
4610b57cec5SDimitry Andric   } else
4620b57cec5SDimitry Andric     return HeaderMapIt->second;
4630b57cec5SDimitry Andric }
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric // Compute the unlikely successors to the block BB in the loop L, specifically
4660b57cec5SDimitry Andric // those that are unlikely because this is a loop, and add them to the
4670b57cec5SDimitry Andric // UnlikelyBlocks set.
4680b57cec5SDimitry Andric static void
4690b57cec5SDimitry Andric computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
4700b57cec5SDimitry Andric                           SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
4710b57cec5SDimitry Andric   // Sometimes in a loop we have a branch whose condition is made false by
4720b57cec5SDimitry Andric   // taking it. This is typically something like
4730b57cec5SDimitry Andric   //  int n = 0;
4740b57cec5SDimitry Andric   //  while (...) {
4750b57cec5SDimitry Andric   //    if (++n >= MAX) {
4760b57cec5SDimitry Andric   //      n = 0;
4770b57cec5SDimitry Andric   //    }
4780b57cec5SDimitry Andric   //  }
4790b57cec5SDimitry Andric   // In this sort of situation taking the branch means that at the very least it
4800b57cec5SDimitry Andric   // won't be taken again in the next iteration of the loop, so we should
4810b57cec5SDimitry Andric   // consider it less likely than a typical branch.
4820b57cec5SDimitry Andric   //
4830b57cec5SDimitry Andric   // We detect this by looking back through the graph of PHI nodes that sets the
4840b57cec5SDimitry Andric   // value that the condition depends on, and seeing if we can reach a successor
4850b57cec5SDimitry Andric   // block which can be determined to make the condition false.
4860b57cec5SDimitry Andric   //
4870b57cec5SDimitry Andric   // FIXME: We currently consider unlikely blocks to be half as likely as other
4880b57cec5SDimitry Andric   // blocks, but if we consider the example above the likelyhood is actually
4890b57cec5SDimitry Andric   // 1/MAX. We could therefore be more precise in how unlikely we consider
4900b57cec5SDimitry Andric   // blocks to be, but it would require more careful examination of the form
4910b57cec5SDimitry Andric   // of the comparison expression.
4920b57cec5SDimitry Andric   const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
4930b57cec5SDimitry Andric   if (!BI || !BI->isConditional())
4940b57cec5SDimitry Andric     return;
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   // Check if the branch is based on an instruction compared with a constant
4970b57cec5SDimitry Andric   CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
4980b57cec5SDimitry Andric   if (!CI || !isa<Instruction>(CI->getOperand(0)) ||
4990b57cec5SDimitry Andric       !isa<Constant>(CI->getOperand(1)))
5000b57cec5SDimitry Andric     return;
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   // Either the instruction must be a PHI, or a chain of operations involving
5030b57cec5SDimitry Andric   // constants that ends in a PHI which we can then collapse into a single value
5040b57cec5SDimitry Andric   // if the PHI value is known.
5050b57cec5SDimitry Andric   Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0));
5060b57cec5SDimitry Andric   PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
5070b57cec5SDimitry Andric   Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1));
5080b57cec5SDimitry Andric   // Collect the instructions until we hit a PHI
5090b57cec5SDimitry Andric   SmallVector<BinaryOperator *, 1> InstChain;
5100b57cec5SDimitry Andric   while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
5110b57cec5SDimitry Andric          isa<Constant>(CmpLHS->getOperand(1))) {
5120b57cec5SDimitry Andric     // Stop if the chain extends outside of the loop
5130b57cec5SDimitry Andric     if (!L->contains(CmpLHS))
5140b57cec5SDimitry Andric       return;
5150b57cec5SDimitry Andric     InstChain.push_back(cast<BinaryOperator>(CmpLHS));
5160b57cec5SDimitry Andric     CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
5170b57cec5SDimitry Andric     if (CmpLHS)
5180b57cec5SDimitry Andric       CmpPHI = dyn_cast<PHINode>(CmpLHS);
5190b57cec5SDimitry Andric   }
5200b57cec5SDimitry Andric   if (!CmpPHI || !L->contains(CmpPHI))
5210b57cec5SDimitry Andric     return;
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   // Trace the phi node to find all values that come from successors of BB
5240b57cec5SDimitry Andric   SmallPtrSet<PHINode*, 8> VisitedInsts;
5250b57cec5SDimitry Andric   SmallVector<PHINode*, 8> WorkList;
5260b57cec5SDimitry Andric   WorkList.push_back(CmpPHI);
5270b57cec5SDimitry Andric   VisitedInsts.insert(CmpPHI);
5280b57cec5SDimitry Andric   while (!WorkList.empty()) {
5290b57cec5SDimitry Andric     PHINode *P = WorkList.back();
5300b57cec5SDimitry Andric     WorkList.pop_back();
5310b57cec5SDimitry Andric     for (BasicBlock *B : P->blocks()) {
5320b57cec5SDimitry Andric       // Skip blocks that aren't part of the loop
5330b57cec5SDimitry Andric       if (!L->contains(B))
5340b57cec5SDimitry Andric         continue;
5350b57cec5SDimitry Andric       Value *V = P->getIncomingValueForBlock(B);
5360b57cec5SDimitry Andric       // If the source is a PHI add it to the work list if we haven't
5370b57cec5SDimitry Andric       // already visited it.
5380b57cec5SDimitry Andric       if (PHINode *PN = dyn_cast<PHINode>(V)) {
5390b57cec5SDimitry Andric         if (VisitedInsts.insert(PN).second)
5400b57cec5SDimitry Andric           WorkList.push_back(PN);
5410b57cec5SDimitry Andric         continue;
5420b57cec5SDimitry Andric       }
5430b57cec5SDimitry Andric       // If this incoming value is a constant and B is a successor of BB, then
5440b57cec5SDimitry Andric       // we can constant-evaluate the compare to see if it makes the branch be
5450b57cec5SDimitry Andric       // taken or not.
5460b57cec5SDimitry Andric       Constant *CmpLHSConst = dyn_cast<Constant>(V);
5470b57cec5SDimitry Andric       if (!CmpLHSConst ||
5480b57cec5SDimitry Andric           std::find(succ_begin(BB), succ_end(BB), B) == succ_end(BB))
5490b57cec5SDimitry Andric         continue;
5500b57cec5SDimitry Andric       // First collapse InstChain
5510b57cec5SDimitry Andric       for (Instruction *I : llvm::reverse(InstChain)) {
5520b57cec5SDimitry Andric         CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst,
5530b57cec5SDimitry Andric                                         cast<Constant>(I->getOperand(1)), true);
5540b57cec5SDimitry Andric         if (!CmpLHSConst)
5550b57cec5SDimitry Andric           break;
5560b57cec5SDimitry Andric       }
5570b57cec5SDimitry Andric       if (!CmpLHSConst)
5580b57cec5SDimitry Andric         continue;
5590b57cec5SDimitry Andric       // Now constant-evaluate the compare
5600b57cec5SDimitry Andric       Constant *Result = ConstantExpr::getCompare(CI->getPredicate(),
5610b57cec5SDimitry Andric                                                   CmpLHSConst, CmpConst, true);
5620b57cec5SDimitry Andric       // If the result means we don't branch to the block then that block is
5630b57cec5SDimitry Andric       // unlikely.
5640b57cec5SDimitry Andric       if (Result &&
5650b57cec5SDimitry Andric           ((Result->isZeroValue() && B == BI->getSuccessor(0)) ||
5660b57cec5SDimitry Andric            (Result->isOneValue() && B == BI->getSuccessor(1))))
5670b57cec5SDimitry Andric         UnlikelyBlocks.insert(B);
5680b57cec5SDimitry Andric     }
5690b57cec5SDimitry Andric   }
5700b57cec5SDimitry Andric }
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric // Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
5730b57cec5SDimitry Andric // as taken, exiting edges as not-taken.
5740b57cec5SDimitry Andric bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
5750b57cec5SDimitry Andric                                                      const LoopInfo &LI,
5760b57cec5SDimitry Andric                                                      SccInfo &SccI) {
5770b57cec5SDimitry Andric   int SccNum;
5780b57cec5SDimitry Andric   Loop *L = LI.getLoopFor(BB);
5790b57cec5SDimitry Andric   if (!L) {
5800b57cec5SDimitry Andric     SccNum = getSCCNum(BB, SccI);
5810b57cec5SDimitry Andric     if (SccNum < 0)
5820b57cec5SDimitry Andric       return false;
5830b57cec5SDimitry Andric   }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks;
5860b57cec5SDimitry Andric   if (L)
5870b57cec5SDimitry Andric     computeUnlikelySuccessors(BB, L, UnlikelyBlocks);
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   SmallVector<unsigned, 8> BackEdges;
5900b57cec5SDimitry Andric   SmallVector<unsigned, 8> ExitingEdges;
5910b57cec5SDimitry Andric   SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
5920b57cec5SDimitry Andric   SmallVector<unsigned, 8> UnlikelyEdges;
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
5950b57cec5SDimitry Andric     // Use LoopInfo if we have it, otherwise fall-back to SCC info to catch
5960b57cec5SDimitry Andric     // irreducible loops.
5970b57cec5SDimitry Andric     if (L) {
5980b57cec5SDimitry Andric       if (UnlikelyBlocks.count(*I) != 0)
5990b57cec5SDimitry Andric         UnlikelyEdges.push_back(I.getSuccessorIndex());
6000b57cec5SDimitry Andric       else if (!L->contains(*I))
6010b57cec5SDimitry Andric         ExitingEdges.push_back(I.getSuccessorIndex());
6020b57cec5SDimitry Andric       else if (L->getHeader() == *I)
6030b57cec5SDimitry Andric         BackEdges.push_back(I.getSuccessorIndex());
6040b57cec5SDimitry Andric       else
6050b57cec5SDimitry Andric         InEdges.push_back(I.getSuccessorIndex());
6060b57cec5SDimitry Andric     } else {
6070b57cec5SDimitry Andric       if (getSCCNum(*I, SccI) != SccNum)
6080b57cec5SDimitry Andric         ExitingEdges.push_back(I.getSuccessorIndex());
6090b57cec5SDimitry Andric       else if (isSCCHeader(*I, SccNum, SccI))
6100b57cec5SDimitry Andric         BackEdges.push_back(I.getSuccessorIndex());
6110b57cec5SDimitry Andric       else
6120b57cec5SDimitry Andric         InEdges.push_back(I.getSuccessorIndex());
6130b57cec5SDimitry Andric     }
6140b57cec5SDimitry Andric   }
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric   if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty())
6170b57cec5SDimitry Andric     return false;
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric   // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
6200b57cec5SDimitry Andric   // normalize them so that they sum up to one.
6210b57cec5SDimitry Andric   unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
6220b57cec5SDimitry Andric                    (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
6230b57cec5SDimitry Andric                    (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) +
6240b57cec5SDimitry Andric                    (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   if (uint32_t numBackEdges = BackEdges.size()) {
6270b57cec5SDimitry Andric     BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
6280b57cec5SDimitry Andric     auto Prob = TakenProb / numBackEdges;
6290b57cec5SDimitry Andric     for (unsigned SuccIdx : BackEdges)
6300b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
6310b57cec5SDimitry Andric   }
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   if (uint32_t numInEdges = InEdges.size()) {
6340b57cec5SDimitry Andric     BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
6350b57cec5SDimitry Andric     auto Prob = TakenProb / numInEdges;
6360b57cec5SDimitry Andric     for (unsigned SuccIdx : InEdges)
6370b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
6380b57cec5SDimitry Andric   }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   if (uint32_t numExitingEdges = ExitingEdges.size()) {
6410b57cec5SDimitry Andric     BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT,
6420b57cec5SDimitry Andric                                                        Denom);
6430b57cec5SDimitry Andric     auto Prob = NotTakenProb / numExitingEdges;
6440b57cec5SDimitry Andric     for (unsigned SuccIdx : ExitingEdges)
6450b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
6460b57cec5SDimitry Andric   }
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric   if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) {
6490b57cec5SDimitry Andric     BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT,
6500b57cec5SDimitry Andric                                                        Denom);
6510b57cec5SDimitry Andric     auto Prob = UnlikelyProb / numUnlikelyEdges;
6520b57cec5SDimitry Andric     for (unsigned SuccIdx : UnlikelyEdges)
6530b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
6540b57cec5SDimitry Andric   }
6550b57cec5SDimitry Andric 
6560b57cec5SDimitry Andric   return true;
6570b57cec5SDimitry Andric }
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
6600b57cec5SDimitry Andric                                                const TargetLibraryInfo *TLI) {
6610b57cec5SDimitry Andric   const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
6620b57cec5SDimitry Andric   if (!BI || !BI->isConditional())
6630b57cec5SDimitry Andric     return false;
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   Value *Cond = BI->getCondition();
6660b57cec5SDimitry Andric   ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
6670b57cec5SDimitry Andric   if (!CI)
6680b57cec5SDimitry Andric     return false;
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   auto GetConstantInt = [](Value *V) {
6710b57cec5SDimitry Andric     if (auto *I = dyn_cast<BitCastInst>(V))
6720b57cec5SDimitry Andric       return dyn_cast<ConstantInt>(I->getOperand(0));
6730b57cec5SDimitry Andric     return dyn_cast<ConstantInt>(V);
6740b57cec5SDimitry Andric   };
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   Value *RHS = CI->getOperand(1);
6770b57cec5SDimitry Andric   ConstantInt *CV = GetConstantInt(RHS);
6780b57cec5SDimitry Andric   if (!CV)
6790b57cec5SDimitry Andric     return false;
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric   // If the LHS is the result of AND'ing a value with a single bit bitmask,
6820b57cec5SDimitry Andric   // we don't have information about probabilities.
6830b57cec5SDimitry Andric   if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
6840b57cec5SDimitry Andric     if (LHS->getOpcode() == Instruction::And)
6850b57cec5SDimitry Andric       if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
6860b57cec5SDimitry Andric         if (AndRHS->getValue().isPowerOf2())
6870b57cec5SDimitry Andric           return false;
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   // Check if the LHS is the return value of a library function
6900b57cec5SDimitry Andric   LibFunc Func = NumLibFuncs;
6910b57cec5SDimitry Andric   if (TLI)
6920b57cec5SDimitry Andric     if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
6930b57cec5SDimitry Andric       if (Function *CalledFn = Call->getCalledFunction())
6940b57cec5SDimitry Andric         TLI->getLibFunc(*CalledFn, Func);
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric   bool isProb;
6970b57cec5SDimitry Andric   if (Func == LibFunc_strcasecmp ||
6980b57cec5SDimitry Andric       Func == LibFunc_strcmp ||
6990b57cec5SDimitry Andric       Func == LibFunc_strncasecmp ||
7000b57cec5SDimitry Andric       Func == LibFunc_strncmp ||
7010b57cec5SDimitry Andric       Func == LibFunc_memcmp) {
7020b57cec5SDimitry Andric     // strcmp and similar functions return zero, negative, or positive, if the
7030b57cec5SDimitry Andric     // first string is equal, less, or greater than the second. We consider it
7040b57cec5SDimitry Andric     // likely that the strings are not equal, so a comparison with zero is
7050b57cec5SDimitry Andric     // probably false, but also a comparison with any other number is also
7060b57cec5SDimitry Andric     // probably false given that what exactly is returned for nonzero values is
7070b57cec5SDimitry Andric     // not specified. Any kind of comparison other than equality we know
7080b57cec5SDimitry Andric     // nothing about.
7090b57cec5SDimitry Andric     switch (CI->getPredicate()) {
7100b57cec5SDimitry Andric     case CmpInst::ICMP_EQ:
7110b57cec5SDimitry Andric       isProb = false;
7120b57cec5SDimitry Andric       break;
7130b57cec5SDimitry Andric     case CmpInst::ICMP_NE:
7140b57cec5SDimitry Andric       isProb = true;
7150b57cec5SDimitry Andric       break;
7160b57cec5SDimitry Andric     default:
7170b57cec5SDimitry Andric       return false;
7180b57cec5SDimitry Andric     }
7190b57cec5SDimitry Andric   } else if (CV->isZero()) {
7200b57cec5SDimitry Andric     switch (CI->getPredicate()) {
7210b57cec5SDimitry Andric     case CmpInst::ICMP_EQ:
7220b57cec5SDimitry Andric       // X == 0   ->  Unlikely
7230b57cec5SDimitry Andric       isProb = false;
7240b57cec5SDimitry Andric       break;
7250b57cec5SDimitry Andric     case CmpInst::ICMP_NE:
7260b57cec5SDimitry Andric       // X != 0   ->  Likely
7270b57cec5SDimitry Andric       isProb = true;
7280b57cec5SDimitry Andric       break;
7290b57cec5SDimitry Andric     case CmpInst::ICMP_SLT:
7300b57cec5SDimitry Andric       // X < 0   ->  Unlikely
7310b57cec5SDimitry Andric       isProb = false;
7320b57cec5SDimitry Andric       break;
7330b57cec5SDimitry Andric     case CmpInst::ICMP_SGT:
7340b57cec5SDimitry Andric       // X > 0   ->  Likely
7350b57cec5SDimitry Andric       isProb = true;
7360b57cec5SDimitry Andric       break;
7370b57cec5SDimitry Andric     default:
7380b57cec5SDimitry Andric       return false;
7390b57cec5SDimitry Andric     }
7400b57cec5SDimitry Andric   } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
7410b57cec5SDimitry Andric     // InstCombine canonicalizes X <= 0 into X < 1.
7420b57cec5SDimitry Andric     // X <= 0   ->  Unlikely
7430b57cec5SDimitry Andric     isProb = false;
7440b57cec5SDimitry Andric   } else if (CV->isMinusOne()) {
7450b57cec5SDimitry Andric     switch (CI->getPredicate()) {
7460b57cec5SDimitry Andric     case CmpInst::ICMP_EQ:
7470b57cec5SDimitry Andric       // X == -1  ->  Unlikely
7480b57cec5SDimitry Andric       isProb = false;
7490b57cec5SDimitry Andric       break;
7500b57cec5SDimitry Andric     case CmpInst::ICMP_NE:
7510b57cec5SDimitry Andric       // X != -1  ->  Likely
7520b57cec5SDimitry Andric       isProb = true;
7530b57cec5SDimitry Andric       break;
7540b57cec5SDimitry Andric     case CmpInst::ICMP_SGT:
7550b57cec5SDimitry Andric       // InstCombine canonicalizes X >= 0 into X > -1.
7560b57cec5SDimitry Andric       // X >= 0   ->  Likely
7570b57cec5SDimitry Andric       isProb = true;
7580b57cec5SDimitry Andric       break;
7590b57cec5SDimitry Andric     default:
7600b57cec5SDimitry Andric       return false;
7610b57cec5SDimitry Andric     }
7620b57cec5SDimitry Andric   } else {
7630b57cec5SDimitry Andric     return false;
7640b57cec5SDimitry Andric   }
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric   unsigned TakenIdx = 0, NonTakenIdx = 1;
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   if (!isProb)
7690b57cec5SDimitry Andric     std::swap(TakenIdx, NonTakenIdx);
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric   BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
7720b57cec5SDimitry Andric                               ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
7730b57cec5SDimitry Andric   setEdgeProbability(BB, TakenIdx, TakenProb);
7740b57cec5SDimitry Andric   setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
7750b57cec5SDimitry Andric   return true;
7760b57cec5SDimitry Andric }
7770b57cec5SDimitry Andric 
7780b57cec5SDimitry Andric bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
7790b57cec5SDimitry Andric   const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
7800b57cec5SDimitry Andric   if (!BI || !BI->isConditional())
7810b57cec5SDimitry Andric     return false;
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric   Value *Cond = BI->getCondition();
7840b57cec5SDimitry Andric   FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
7850b57cec5SDimitry Andric   if (!FCmp)
7860b57cec5SDimitry Andric     return false;
7870b57cec5SDimitry Andric 
788*8bcb0991SDimitry Andric   uint32_t TakenWeight = FPH_TAKEN_WEIGHT;
789*8bcb0991SDimitry Andric   uint32_t NontakenWeight = FPH_NONTAKEN_WEIGHT;
7900b57cec5SDimitry Andric   bool isProb;
7910b57cec5SDimitry Andric   if (FCmp->isEquality()) {
7920b57cec5SDimitry Andric     // f1 == f2 -> Unlikely
7930b57cec5SDimitry Andric     // f1 != f2 -> Likely
7940b57cec5SDimitry Andric     isProb = !FCmp->isTrueWhenEqual();
7950b57cec5SDimitry Andric   } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
7960b57cec5SDimitry Andric     // !isnan -> Likely
7970b57cec5SDimitry Andric     isProb = true;
798*8bcb0991SDimitry Andric     TakenWeight = FPH_ORD_WEIGHT;
799*8bcb0991SDimitry Andric     NontakenWeight = FPH_UNO_WEIGHT;
8000b57cec5SDimitry Andric   } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
8010b57cec5SDimitry Andric     // isnan -> Unlikely
8020b57cec5SDimitry Andric     isProb = false;
803*8bcb0991SDimitry Andric     TakenWeight = FPH_ORD_WEIGHT;
804*8bcb0991SDimitry Andric     NontakenWeight = FPH_UNO_WEIGHT;
8050b57cec5SDimitry Andric   } else {
8060b57cec5SDimitry Andric     return false;
8070b57cec5SDimitry Andric   }
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric   unsigned TakenIdx = 0, NonTakenIdx = 1;
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric   if (!isProb)
8120b57cec5SDimitry Andric     std::swap(TakenIdx, NonTakenIdx);
8130b57cec5SDimitry Andric 
814*8bcb0991SDimitry Andric   BranchProbability TakenProb(TakenWeight, TakenWeight + NontakenWeight);
8150b57cec5SDimitry Andric   setEdgeProbability(BB, TakenIdx, TakenProb);
8160b57cec5SDimitry Andric   setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
8170b57cec5SDimitry Andric   return true;
8180b57cec5SDimitry Andric }
8190b57cec5SDimitry Andric 
8200b57cec5SDimitry Andric bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
8210b57cec5SDimitry Andric   const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
8220b57cec5SDimitry Andric   if (!II)
8230b57cec5SDimitry Andric     return false;
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   BranchProbability TakenProb(IH_TAKEN_WEIGHT,
8260b57cec5SDimitry Andric                               IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
8270b57cec5SDimitry Andric   setEdgeProbability(BB, 0 /*Index for Normal*/, TakenProb);
8280b57cec5SDimitry Andric   setEdgeProbability(BB, 1 /*Index for Unwind*/, TakenProb.getCompl());
8290b57cec5SDimitry Andric   return true;
8300b57cec5SDimitry Andric }
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric void BranchProbabilityInfo::releaseMemory() {
8330b57cec5SDimitry Andric   Probs.clear();
8340b57cec5SDimitry Andric }
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric void BranchProbabilityInfo::print(raw_ostream &OS) const {
8370b57cec5SDimitry Andric   OS << "---- Branch Probabilities ----\n";
8380b57cec5SDimitry Andric   // We print the probabilities from the last function the analysis ran over,
8390b57cec5SDimitry Andric   // or the function it is currently running over.
8400b57cec5SDimitry Andric   assert(LastF && "Cannot print prior to running over a function");
8410b57cec5SDimitry Andric   for (const auto &BI : *LastF) {
8420b57cec5SDimitry Andric     for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
8430b57cec5SDimitry Andric          ++SI) {
8440b57cec5SDimitry Andric       printEdgeProbability(OS << "  ", &BI, *SI);
8450b57cec5SDimitry Andric     }
8460b57cec5SDimitry Andric   }
8470b57cec5SDimitry Andric }
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric bool BranchProbabilityInfo::
8500b57cec5SDimitry Andric isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
8510b57cec5SDimitry Andric   // Hot probability is at least 4/5 = 80%
8520b57cec5SDimitry Andric   // FIXME: Compare against a static "hot" BranchProbability.
8530b57cec5SDimitry Andric   return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric const BasicBlock *
8570b57cec5SDimitry Andric BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
8580b57cec5SDimitry Andric   auto MaxProb = BranchProbability::getZero();
8590b57cec5SDimitry Andric   const BasicBlock *MaxSucc = nullptr;
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
8620b57cec5SDimitry Andric     const BasicBlock *Succ = *I;
8630b57cec5SDimitry Andric     auto Prob = getEdgeProbability(BB, Succ);
8640b57cec5SDimitry Andric     if (Prob > MaxProb) {
8650b57cec5SDimitry Andric       MaxProb = Prob;
8660b57cec5SDimitry Andric       MaxSucc = Succ;
8670b57cec5SDimitry Andric     }
8680b57cec5SDimitry Andric   }
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric   // Hot probability is at least 4/5 = 80%
8710b57cec5SDimitry Andric   if (MaxProb > BranchProbability(4, 5))
8720b57cec5SDimitry Andric     return MaxSucc;
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric   return nullptr;
8750b57cec5SDimitry Andric }
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric /// Get the raw edge probability for the edge. If can't find it, return a
8780b57cec5SDimitry Andric /// default probability 1/N where N is the number of successors. Here an edge is
8790b57cec5SDimitry Andric /// specified using PredBlock and an
8800b57cec5SDimitry Andric /// index to the successors.
8810b57cec5SDimitry Andric BranchProbability
8820b57cec5SDimitry Andric BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
8830b57cec5SDimitry Andric                                           unsigned IndexInSuccessors) const {
8840b57cec5SDimitry Andric   auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric   if (I != Probs.end())
8870b57cec5SDimitry Andric     return I->second;
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   return {1, static_cast<uint32_t>(succ_size(Src))};
8900b57cec5SDimitry Andric }
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric BranchProbability
8930b57cec5SDimitry Andric BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
8940b57cec5SDimitry Andric                                           succ_const_iterator Dst) const {
8950b57cec5SDimitry Andric   return getEdgeProbability(Src, Dst.getSuccessorIndex());
8960b57cec5SDimitry Andric }
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric /// Get the raw edge probability calculated for the block pair. This returns the
8990b57cec5SDimitry Andric /// sum of all raw edge probabilities from Src to Dst.
9000b57cec5SDimitry Andric BranchProbability
9010b57cec5SDimitry Andric BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
9020b57cec5SDimitry Andric                                           const BasicBlock *Dst) const {
9030b57cec5SDimitry Andric   auto Prob = BranchProbability::getZero();
9040b57cec5SDimitry Andric   bool FoundProb = false;
9050b57cec5SDimitry Andric   for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
9060b57cec5SDimitry Andric     if (*I == Dst) {
9070b57cec5SDimitry Andric       auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
9080b57cec5SDimitry Andric       if (MapI != Probs.end()) {
9090b57cec5SDimitry Andric         FoundProb = true;
9100b57cec5SDimitry Andric         Prob += MapI->second;
9110b57cec5SDimitry Andric       }
9120b57cec5SDimitry Andric     }
9130b57cec5SDimitry Andric   uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
9140b57cec5SDimitry Andric   return FoundProb ? Prob : BranchProbability(1, succ_num);
9150b57cec5SDimitry Andric }
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric /// Set the edge probability for a given edge specified by PredBlock and an
9180b57cec5SDimitry Andric /// index to the successors.
9190b57cec5SDimitry Andric void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
9200b57cec5SDimitry Andric                                                unsigned IndexInSuccessors,
9210b57cec5SDimitry Andric                                                BranchProbability Prob) {
9220b57cec5SDimitry Andric   Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
9230b57cec5SDimitry Andric   Handles.insert(BasicBlockCallbackVH(Src, this));
9240b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
9250b57cec5SDimitry Andric                     << IndexInSuccessors << " successor probability to " << Prob
9260b57cec5SDimitry Andric                     << "\n");
9270b57cec5SDimitry Andric }
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric raw_ostream &
9300b57cec5SDimitry Andric BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
9310b57cec5SDimitry Andric                                             const BasicBlock *Src,
9320b57cec5SDimitry Andric                                             const BasicBlock *Dst) const {
9330b57cec5SDimitry Andric   const BranchProbability Prob = getEdgeProbability(Src, Dst);
9340b57cec5SDimitry Andric   OS << "edge " << Src->getName() << " -> " << Dst->getName()
9350b57cec5SDimitry Andric      << " probability is " << Prob
9360b57cec5SDimitry Andric      << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   return OS;
9390b57cec5SDimitry Andric }
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
9420b57cec5SDimitry Andric   for (auto I = Probs.begin(), E = Probs.end(); I != E; ++I) {
9430b57cec5SDimitry Andric     auto Key = I->first;
9440b57cec5SDimitry Andric     if (Key.first == BB)
9450b57cec5SDimitry Andric       Probs.erase(Key);
9460b57cec5SDimitry Andric   }
9470b57cec5SDimitry Andric }
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
9500b57cec5SDimitry Andric                                       const TargetLibraryInfo *TLI) {
9510b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
9520b57cec5SDimitry Andric                     << " ----\n\n");
9530b57cec5SDimitry Andric   LastF = &F; // Store the last function we ran on for printing.
9540b57cec5SDimitry Andric   assert(PostDominatedByUnreachable.empty());
9550b57cec5SDimitry Andric   assert(PostDominatedByColdCall.empty());
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric   // Record SCC numbers of blocks in the CFG to identify irreducible loops.
9580b57cec5SDimitry Andric   // FIXME: We could only calculate this if the CFG is known to be irreducible
9590b57cec5SDimitry Andric   // (perhaps cache this info in LoopInfo if we can easily calculate it there?).
9600b57cec5SDimitry Andric   int SccNum = 0;
9610b57cec5SDimitry Andric   SccInfo SccI;
9620b57cec5SDimitry Andric   for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd();
9630b57cec5SDimitry Andric        ++It, ++SccNum) {
9640b57cec5SDimitry Andric     // Ignore single-block SCCs since they either aren't loops or LoopInfo will
9650b57cec5SDimitry Andric     // catch them.
9660b57cec5SDimitry Andric     const std::vector<const BasicBlock *> &Scc = *It;
9670b57cec5SDimitry Andric     if (Scc.size() == 1)
9680b57cec5SDimitry Andric       continue;
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "BPI: SCC " << SccNum << ":");
9710b57cec5SDimitry Andric     for (auto *BB : Scc) {
9720b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " " << BB->getName());
9730b57cec5SDimitry Andric       SccI.SccNums[BB] = SccNum;
9740b57cec5SDimitry Andric     }
9750b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
9760b57cec5SDimitry Andric   }
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric   // Walk the basic blocks in post-order so that we can build up state about
9790b57cec5SDimitry Andric   // the successors of a block iteratively.
9800b57cec5SDimitry Andric   for (auto BB : post_order(&F.getEntryBlock())) {
9810b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName()
9820b57cec5SDimitry Andric                       << "\n");
9830b57cec5SDimitry Andric     updatePostDominatedByUnreachable(BB);
9840b57cec5SDimitry Andric     updatePostDominatedByColdCall(BB);
9850b57cec5SDimitry Andric     // If there is no at least two successors, no sense to set probability.
9860b57cec5SDimitry Andric     if (BB->getTerminator()->getNumSuccessors() < 2)
9870b57cec5SDimitry Andric       continue;
9880b57cec5SDimitry Andric     if (calcMetadataWeights(BB))
9890b57cec5SDimitry Andric       continue;
9900b57cec5SDimitry Andric     if (calcInvokeHeuristics(BB))
9910b57cec5SDimitry Andric       continue;
9920b57cec5SDimitry Andric     if (calcUnreachableHeuristics(BB))
9930b57cec5SDimitry Andric       continue;
9940b57cec5SDimitry Andric     if (calcColdCallHeuristics(BB))
9950b57cec5SDimitry Andric       continue;
9960b57cec5SDimitry Andric     if (calcLoopBranchHeuristics(BB, LI, SccI))
9970b57cec5SDimitry Andric       continue;
9980b57cec5SDimitry Andric     if (calcPointerHeuristics(BB))
9990b57cec5SDimitry Andric       continue;
10000b57cec5SDimitry Andric     if (calcZeroHeuristics(BB, TLI))
10010b57cec5SDimitry Andric       continue;
10020b57cec5SDimitry Andric     if (calcFloatingPointHeuristics(BB))
10030b57cec5SDimitry Andric       continue;
10040b57cec5SDimitry Andric   }
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric   PostDominatedByUnreachable.clear();
10070b57cec5SDimitry Andric   PostDominatedByColdCall.clear();
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   if (PrintBranchProb &&
10100b57cec5SDimitry Andric       (PrintBranchProbFuncName.empty() ||
10110b57cec5SDimitry Andric        F.getName().equals(PrintBranchProbFuncName))) {
10120b57cec5SDimitry Andric     print(dbgs());
10130b57cec5SDimitry Andric   }
10140b57cec5SDimitry Andric }
10150b57cec5SDimitry Andric 
10160b57cec5SDimitry Andric void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
10170b57cec5SDimitry Andric     AnalysisUsage &AU) const {
10180b57cec5SDimitry Andric   // We require DT so it's available when LI is available. The LI updating code
10190b57cec5SDimitry Andric   // asserts that DT is also present so if we don't make sure that we have DT
10200b57cec5SDimitry Andric   // here, that assert will trigger.
10210b57cec5SDimitry Andric   AU.addRequired<DominatorTreeWrapperPass>();
10220b57cec5SDimitry Andric   AU.addRequired<LoopInfoWrapperPass>();
10230b57cec5SDimitry Andric   AU.addRequired<TargetLibraryInfoWrapperPass>();
10240b57cec5SDimitry Andric   AU.setPreservesAll();
10250b57cec5SDimitry Andric }
10260b57cec5SDimitry Andric 
10270b57cec5SDimitry Andric bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
10280b57cec5SDimitry Andric   const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1029*8bcb0991SDimitry Andric   const TargetLibraryInfo &TLI =
1030*8bcb0991SDimitry Andric       getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
10310b57cec5SDimitry Andric   BPI.calculate(F, LI, &TLI);
10320b57cec5SDimitry Andric   return false;
10330b57cec5SDimitry Andric }
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
10380b57cec5SDimitry Andric                                              const Module *) const {
10390b57cec5SDimitry Andric   BPI.print(OS);
10400b57cec5SDimitry Andric }
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric AnalysisKey BranchProbabilityAnalysis::Key;
10430b57cec5SDimitry Andric BranchProbabilityInfo
10440b57cec5SDimitry Andric BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
10450b57cec5SDimitry Andric   BranchProbabilityInfo BPI;
10460b57cec5SDimitry Andric   BPI.calculate(F, AM.getResult<LoopAnalysis>(F), &AM.getResult<TargetLibraryAnalysis>(F));
10470b57cec5SDimitry Andric   return BPI;
10480b57cec5SDimitry Andric }
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric PreservedAnalyses
10510b57cec5SDimitry Andric BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10520b57cec5SDimitry Andric   OS << "Printing analysis results of BPI for function "
10530b57cec5SDimitry Andric      << "'" << F.getName() << "':"
10540b57cec5SDimitry Andric      << "\n";
10550b57cec5SDimitry Andric   AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
10560b57cec5SDimitry Andric   return PreservedAnalyses::all();
10570b57cec5SDimitry Andric }
1058