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