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