LLVM  5.0.0
BranchProbabilityInfo.h
Go to the documentation of this file.
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"
26 
27 namespace llvm {
28 class LoopInfo;
29 class TargetLibraryInfo;
30 class raw_ostream;
31 
32 /// \brief Analysis providing branch probability information.
33 ///
34 /// This is a function analysis which provides information on the relative
35 /// probabilities of each "edge" in the function's CFG where such an edge is
36 /// defined by a pair (PredBlock and an index in the successors). The
37 /// probability of an edge from one block is always relative to the
38 /// probabilities of other edges from the block. The probabilites of all edges
39 /// from a block sum to exactly one (100%).
40 /// We use a pair (PredBlock and an index in the successors) to uniquely
41 /// identify an edge, since we can have multiple edges from Src to Dst.
42 /// As an example, we can have a switch which jumps to Dst with value 0 and
43 /// value 10.
45 public:
48  const TargetLibraryInfo *TLI = nullptr) {
49  calculate(F, LI, TLI);
50  }
51 
53  : Probs(std::move(Arg.Probs)), LastF(Arg.LastF),
54  PostDominatedByUnreachable(std::move(Arg.PostDominatedByUnreachable)),
55  PostDominatedByColdCall(std::move(Arg.PostDominatedByColdCall)) {}
56 
58  releaseMemory();
59  Probs = std::move(RHS.Probs);
60  PostDominatedByColdCall = std::move(RHS.PostDominatedByColdCall);
61  PostDominatedByUnreachable = std::move(RHS.PostDominatedByUnreachable);
62  return *this;
63  }
64 
65  void releaseMemory();
66 
67  void print(raw_ostream &OS) const;
68 
69  /// \brief Get an edge's probability, relative to other out-edges of the Src.
70  ///
71  /// This routine provides access to the fractional probability between zero
72  /// (0%) and one (100%) of this edge executing, relative to other edges
73  /// leaving the 'Src' block. The returned probability is never zero, and can
74  /// only be one if the source block has only one successor.
76  unsigned IndexInSuccessors) const;
77 
78  /// \brief Get the probability of going from Src to Dst.
79  ///
80  /// It returns the sum of all probabilities for edges from Src to Dst.
82  const BasicBlock *Dst) const;
83 
85  succ_const_iterator Dst) const;
86 
87  /// \brief Test if an edge is hot relative to other out-edges of the Src.
88  ///
89  /// Check whether this edge out of the source block is 'hot'. We define hot
90  /// as having a relative probability >= 80%.
91  bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
92 
93  /// \brief Retrieve the hot successor of a block if one exists.
94  ///
95  /// Given a basic block, look through its successors and if one exists for
96  /// which \see isEdgeHot would return true, return that successor block.
97  const BasicBlock *getHotSucc(const BasicBlock *BB) const;
98 
99  /// \brief Print an edge's probability.
100  ///
101  /// Retrieves an edge's probability similarly to \see getEdgeProbability, but
102  /// then prints that probability to the provided stream. That stream is then
103  /// returned.
105  const BasicBlock *Dst) const;
106 
107  /// \brief Set the raw edge probability for the given edge.
108  ///
109  /// This allows a pass to explicitly set the edge probability for an edge. It
110  /// can be used when updating the CFG to update and preserve the branch
111  /// probability information. Read the implementation of how these edge
112  /// probabilities are calculated carefully before using!
113  void setEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors,
114  BranchProbability Prob);
115 
117  static const BranchProbability LikelyProb((1u << 20) - 1, 1u << 20);
118  return IsLikely ? LikelyProb : LikelyProb.getCompl();
119  }
120 
121  void calculate(const Function &F, const LoopInfo &LI,
122  const TargetLibraryInfo *TLI = nullptr);
123 
124  /// Forget analysis results for the given basic block.
125  void eraseBlock(const BasicBlock *BB);
126 
127 private:
128  void operator=(const BranchProbabilityInfo &) = delete;
130 
131  // We need to store CallbackVH's in order to correctly handle basic block
132  // removal.
133  class BasicBlockCallbackVH final : public CallbackVH {
135  void deleted() override {
136  assert(BPI != nullptr);
137  BPI->eraseBlock(cast<BasicBlock>(getValPtr()));
138  BPI->Handles.erase(*this);
139  }
140 
141  public:
142  BasicBlockCallbackVH(const Value *V, BranchProbabilityInfo *BPI=nullptr)
143  : CallbackVH(const_cast<Value *>(V)), BPI(BPI) {}
144  };
145  DenseSet<BasicBlockCallbackVH, DenseMapInfo<Value*>> Handles;
146 
147  // Since we allow duplicate edges from one basic block to another, we use
148  // a pair (PredBlock and an index in the successors) to specify an edge.
149  typedef std::pair<const BasicBlock *, unsigned> Edge;
150 
151  // Default weight value. Used when we don't have information about the edge.
152  // TODO: DEFAULT_WEIGHT makes sense during static predication, when none of
153  // the successors have a weight yet. But it doesn't make sense when providing
154  // weight to an edge that may have siblings with non-zero weights. This can
155  // be handled various ways, but it's probably fine for an edge with unknown
156  // weight to just "inherit" the non-zero weight of an adjacent successor.
157  static const uint32_t DEFAULT_WEIGHT = 16;
158 
159  DenseMap<Edge, BranchProbability> Probs;
160 
161  /// \brief Track the last function we run over for printing.
162  const Function *LastF;
163 
164  /// \brief Track the set of blocks directly succeeded by a returning block.
165  SmallPtrSet<const BasicBlock *, 16> PostDominatedByUnreachable;
166 
167  /// \brief Track the set of blocks that always lead to a cold call.
168  SmallPtrSet<const BasicBlock *, 16> PostDominatedByColdCall;
169 
170  void updatePostDominatedByUnreachable(const BasicBlock *BB);
171  void updatePostDominatedByColdCall(const BasicBlock *BB);
172  bool calcUnreachableHeuristics(const BasicBlock *BB);
173  bool calcMetadataWeights(const BasicBlock *BB);
174  bool calcColdCallHeuristics(const BasicBlock *BB);
175  bool calcPointerHeuristics(const BasicBlock *BB);
176  bool calcLoopBranchHeuristics(const BasicBlock *BB, const LoopInfo &LI);
177  bool calcZeroHeuristics(const BasicBlock *BB, const TargetLibraryInfo *TLI);
178  bool calcFloatingPointHeuristics(const BasicBlock *BB);
179  bool calcInvokeHeuristics(const BasicBlock *BB);
180 };
181 
182 /// \brief Analysis pass which computes \c BranchProbabilityInfo.
184  : public AnalysisInfoMixin<BranchProbabilityAnalysis> {
186  static AnalysisKey Key;
187 
188 public:
189  /// \brief Provide the result typedef for this analysis pass.
191 
192  /// \brief Run the analysis pass over a function and produce BPI.
194 };
195 
196 /// \brief Printer pass for the \c BranchProbabilityAnalysis results.
198  : public PassInfoMixin<BranchProbabilityPrinterPass> {
199  raw_ostream &OS;
200 
201 public:
202  explicit BranchProbabilityPrinterPass(raw_ostream &OS) : OS(OS) {}
204 };
205 
206 /// \brief Legacy analysis pass which computes \c BranchProbabilityInfo.
209 
210 public:
211  static char ID;
212 
216  }
217 
218  BranchProbabilityInfo &getBPI() { return BPI; }
219  const BranchProbabilityInfo &getBPI() const { return BPI; }
220 
221  void getAnalysisUsage(AnalysisUsage &AU) const override;
222  bool runOnFunction(Function &F) override;
223  void releaseMemory() override;
224  void print(raw_ostream &OS, const Module *M = nullptr) const override;
225 };
226 
227 }
228 
229 #endif
BranchProbabilityInfo & operator=(BranchProbabilityInfo &&RHS)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
raw_ostream & printEdgeProbability(raw_ostream &OS, const BasicBlock *Src, const BasicBlock *Dst) const
Print an edge's probability.
const BasicBlock * getHotSucc(const BasicBlock *BB) const
Retrieve the hot successor of a block if one exists.
Various leaf nodes.
Definition: ISDOpcodes.h:60
BranchProbabilityInfo(const Function &F, const LoopInfo &LI, const TargetLibraryInfo *TLI=nullptr)
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
void calculate(const Function &F, const LoopInfo &LI, const TargetLibraryInfo *TLI=nullptr)
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
const BranchProbabilityInfo & getBPI() const
Analysis pass which computes BranchProbabilityInfo.
#define F(x, y, z)
Definition: MD5.cpp:55
BranchProbabilityInfo(BranchProbabilityInfo &&Arg)
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:365
Legacy analysis pass which computes BranchProbabilityInfo.
Printer pass for the BranchProbabilityAnalysis results.
void initializeBranchProbabilityInfoWrapperPassPass(PassRegistry &)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:382
void eraseBlock(const BasicBlock *BB)
Forget analysis results for the given basic block.
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce BPI.
Provides information about what library functions are available for the current target.
void setEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors, BranchProbability Prob)
Set the raw edge probability for the given edge.
bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const
Test if an edge is hot relative to other out-edges of the Src.
void print(raw_ostream &OS) const
Analysis providing branch probability information.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
Value handle with callbacks on RAUW and destruction.
Definition: ValueHandle.h:389
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
BranchProbabilityInfo Result
Provide the result typedef for this analysis pass.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
static BranchProbability getBranchProbStackProtector(bool IsLikely)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
BranchProbability getCompl() const