Home | History | Annotate | Download | only in Analysis
      1 //===--- BranchProbabilityInfo.h - Branch Probability Analysis --*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This pass is used to evaluate branch probabilties.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
     15 #define LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
     16 
     17 #include "llvm/ADT/DenseMap.h"
     18 #include "llvm/ADT/DenseSet.h"
     19 #include "llvm/ADT/SmallPtrSet.h"
     20 #include "llvm/IR/CFG.h"
     21 #include "llvm/IR/PassManager.h"
     22 #include "llvm/IR/ValueHandle.h"
     23 #include "llvm/InitializePasses.h"
     24 #include "llvm/Pass.h"
     25 #include "llvm/Support/BranchProbability.h"
     26 
     27 namespace llvm {
     28 class LoopInfo;
     29 class raw_ostream;
     30 
     31 /// \brief Analysis providing branch probability information.
     32 ///
     33 /// This is a function analysis which provides information on the relative
     34 /// probabilities of each "edge" in the function's CFG where such an edge is
     35 /// defined by a pair (PredBlock and an index in the successors). The
     36 /// probability of an edge from one block is always relative to the
     37 /// probabilities of other edges from the block. The probabilites of all edges
     38 /// from a block sum to exactly one (100%).
     39 /// We use a pair (PredBlock and an index in the successors) to uniquely
     40 /// identify an edge, since we can have multiple edges from Src to Dst.
     41 /// As an example, we can have a switch which jumps to Dst with value 0 and
     42 /// value 10.
     43 class BranchProbabilityInfo {
     44 public:
     45   BranchProbabilityInfo() {}
     46   BranchProbabilityInfo(const Function &F, const LoopInfo &LI) {
     47     calculate(F, LI);
     48   }
     49 
     50   BranchProbabilityInfo(BranchProbabilityInfo &&Arg)
     51       : Probs(std::move(Arg.Probs)), LastF(Arg.LastF),
     52         PostDominatedByUnreachable(std::move(Arg.PostDominatedByUnreachable)),
     53         PostDominatedByColdCall(std::move(Arg.PostDominatedByColdCall)) {}
     54 
     55   BranchProbabilityInfo &operator=(BranchProbabilityInfo &&RHS) {
     56     releaseMemory();
     57     Probs = std::move(RHS.Probs);
     58     PostDominatedByColdCall = std::move(RHS.PostDominatedByColdCall);
     59     PostDominatedByUnreachable = std::move(RHS.PostDominatedByUnreachable);
     60     return *this;
     61   }
     62 
     63   void releaseMemory();
     64 
     65   void print(raw_ostream &OS) const;
     66 
     67   /// \brief Get an edge's probability, relative to other out-edges of the Src.
     68   ///
     69   /// This routine provides access to the fractional probability between zero
     70   /// (0%) and one (100%) of this edge executing, relative to other edges
     71   /// leaving the 'Src' block. The returned probability is never zero, and can
     72   /// only be one if the source block has only one successor.
     73   BranchProbability getEdgeProbability(const BasicBlock *Src,
     74                                        unsigned IndexInSuccessors) const;
     75 
     76   /// \brief Get the probability of going from Src to Dst.
     77   ///
     78   /// It returns the sum of all probabilities for edges from Src to Dst.
     79   BranchProbability getEdgeProbability(const BasicBlock *Src,
     80                                        const BasicBlock *Dst) const;
     81 
     82   BranchProbability getEdgeProbability(const BasicBlock *Src,
     83                                        succ_const_iterator Dst) const;
     84 
     85   /// \brief Test if an edge is hot relative to other out-edges of the Src.
     86   ///
     87   /// Check whether this edge out of the source block is 'hot'. We define hot
     88   /// as having a relative probability >= 80%.
     89   bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
     90 
     91   /// \brief Retrieve the hot successor of a block if one exists.
     92   ///
     93   /// Given a basic block, look through its successors and if one exists for
     94   /// which \see isEdgeHot would return true, return that successor block.
     95   const BasicBlock *getHotSucc(const BasicBlock *BB) const;
     96 
     97   /// \brief Print an edge's probability.
     98   ///
     99   /// Retrieves an edge's probability similarly to \see getEdgeProbability, but
    100   /// then prints that probability to the provided stream. That stream is then
    101   /// returned.
    102   raw_ostream &printEdgeProbability(raw_ostream &OS, const BasicBlock *Src,
    103                                     const BasicBlock *Dst) const;
    104 
    105   /// \brief Set the raw edge probability for the given edge.
    106   ///
    107   /// This allows a pass to explicitly set the edge probability for an edge. It
    108   /// can be used when updating the CFG to update and preserve the branch
    109   /// probability information. Read the implementation of how these edge
    110   /// probabilities are calculated carefully before using!
    111   void setEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors,
    112                           BranchProbability Prob);
    113 
    114   static BranchProbability getBranchProbStackProtector(bool IsLikely) {
    115     static const BranchProbability LikelyProb((1u << 20) - 1, 1u << 20);
    116     return IsLikely ? LikelyProb : LikelyProb.getCompl();
    117   }
    118 
    119   void calculate(const Function &F, const LoopInfo &LI);
    120 
    121   /// Forget analysis results for the given basic block.
    122   void eraseBlock(const BasicBlock *BB);
    123 
    124 private:
    125   void operator=(const BranchProbabilityInfo &) = delete;
    126   BranchProbabilityInfo(const BranchProbabilityInfo &) = delete;
    127 
    128   // We need to store CallbackVH's in order to correctly handle basic block
    129   // removal.
    130   class BasicBlockCallbackVH final : public CallbackVH {
    131     BranchProbabilityInfo *BPI;
    132     void deleted() override {
    133       assert(BPI != nullptr);
    134       BPI->eraseBlock(cast<BasicBlock>(getValPtr()));
    135       BPI->Handles.erase(*this);
    136     }
    137 
    138   public:
    139     BasicBlockCallbackVH(const Value *V, BranchProbabilityInfo *BPI=nullptr)
    140         : CallbackVH(const_cast<Value *>(V)), BPI(BPI) {}
    141   };
    142   DenseSet<BasicBlockCallbackVH, DenseMapInfo<Value*>> Handles;
    143 
    144   // Since we allow duplicate edges from one basic block to another, we use
    145   // a pair (PredBlock and an index in the successors) to specify an edge.
    146   typedef std::pair<const BasicBlock *, unsigned> Edge;
    147 
    148   // Default weight value. Used when we don't have information about the edge.
    149   // TODO: DEFAULT_WEIGHT makes sense during static predication, when none of
    150   // the successors have a weight yet. But it doesn't make sense when providing
    151   // weight to an edge that may have siblings with non-zero weights. This can
    152   // be handled various ways, but it's probably fine for an edge with unknown
    153   // weight to just "inherit" the non-zero weight of an adjacent successor.
    154   static const uint32_t DEFAULT_WEIGHT = 16;
    155 
    156   DenseMap<Edge, BranchProbability> Probs;
    157 
    158   /// \brief Track the last function we run over for printing.
    159   const Function *LastF;
    160 
    161   /// \brief Track the set of blocks directly succeeded by a returning block.
    162   SmallPtrSet<const BasicBlock *, 16> PostDominatedByUnreachable;
    163 
    164   /// \brief Track the set of blocks that always lead to a cold call.
    165   SmallPtrSet<const BasicBlock *, 16> PostDominatedByColdCall;
    166 
    167   void updatePostDominatedByUnreachable(const BasicBlock *BB);
    168   void updatePostDominatedByColdCall(const BasicBlock *BB);
    169   bool calcUnreachableHeuristics(const BasicBlock *BB);
    170   bool calcMetadataWeights(const BasicBlock *BB);
    171   bool calcColdCallHeuristics(const BasicBlock *BB);
    172   bool calcPointerHeuristics(const BasicBlock *BB);
    173   bool calcLoopBranchHeuristics(const BasicBlock *BB, const LoopInfo &LI);
    174   bool calcZeroHeuristics(const BasicBlock *BB);
    175   bool calcFloatingPointHeuristics(const BasicBlock *BB);
    176   bool calcInvokeHeuristics(const BasicBlock *BB);
    177 };
    178 
    179 /// \brief Analysis pass which computes \c BranchProbabilityInfo.
    180 class BranchProbabilityAnalysis
    181     : public AnalysisInfoMixin<BranchProbabilityAnalysis> {
    182   friend AnalysisInfoMixin<BranchProbabilityAnalysis>;
    183   static AnalysisKey Key;
    184 
    185 public:
    186   /// \brief Provide the result typedef for this analysis pass.
    187   typedef BranchProbabilityInfo Result;
    188 
    189   /// \brief Run the analysis pass over a function and produce BPI.
    190   BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM);
    191 };
    192 
    193 /// \brief Printer pass for the \c BranchProbabilityAnalysis results.
    194 class BranchProbabilityPrinterPass
    195     : public PassInfoMixin<BranchProbabilityPrinterPass> {
    196   raw_ostream &OS;
    197 
    198 public:
    199   explicit BranchProbabilityPrinterPass(raw_ostream &OS) : OS(OS) {}
    200   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
    201 };
    202 
    203 /// \brief Legacy analysis pass which computes \c BranchProbabilityInfo.
    204 class BranchProbabilityInfoWrapperPass : public FunctionPass {
    205   BranchProbabilityInfo BPI;
    206 
    207 public:
    208   static char ID;
    209 
    210   BranchProbabilityInfoWrapperPass() : FunctionPass(ID) {
    211     initializeBranchProbabilityInfoWrapperPassPass(
    212         *PassRegistry::getPassRegistry());
    213   }
    214 
    215   BranchProbabilityInfo &getBPI() { return BPI; }
    216   const BranchProbabilityInfo &getBPI() const { return BPI; }
    217 
    218   void getAnalysisUsage(AnalysisUsage &AU) const override;
    219   bool runOnFunction(Function &F) override;
    220   void releaseMemory() override;
    221   void print(raw_ostream &OS, const Module *M = nullptr) const override;
    222 };
    223 
    224 }
    225 
    226 #endif
    227