LLVM  4.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 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.
44 public:
47  calculate(F, LI);
48  }
49 
51  : Probs(std::move(Arg.Probs)), LastF(Arg.LastF),
52  PostDominatedByUnreachable(std::move(Arg.PostDominatedByUnreachable)),
53  PostDominatedByColdCall(std::move(Arg.PostDominatedByColdCall)) {}
54 
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.
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.
80  const BasicBlock *Dst) const;
81 
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.
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 
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;
127 
128  // We need to store CallbackVH's in order to correctly handle basic block
129  // removal.
130  class BasicBlockCallbackVH final : public CallbackVH {
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  bool calcUnreachableHeuristics(const BasicBlock *BB);
168  bool calcMetadataWeights(const BasicBlock *BB);
169  bool calcColdCallHeuristics(const BasicBlock *BB);
170  bool calcPointerHeuristics(const BasicBlock *BB);
171  bool calcLoopBranchHeuristics(const BasicBlock *BB, const LoopInfo &LI);
172  bool calcZeroHeuristics(const BasicBlock *BB);
173  bool calcFloatingPointHeuristics(const BasicBlock *BB);
174  bool calcInvokeHeuristics(const BasicBlock *BB);
175 };
176 
177 /// \brief Analysis pass which computes \c BranchProbabilityInfo.
179  : public AnalysisInfoMixin<BranchProbabilityAnalysis> {
181  static AnalysisKey Key;
182 
183 public:
184  /// \brief Provide the result typedef for this analysis pass.
186 
187  /// \brief Run the analysis pass over a function and produce BPI.
189 };
190 
191 /// \brief Printer pass for the \c BranchProbabilityAnalysis results.
193  : public PassInfoMixin<BranchProbabilityPrinterPass> {
194  raw_ostream &OS;
195 
196 public:
197  explicit BranchProbabilityPrinterPass(raw_ostream &OS) : OS(OS) {}
199 };
200 
201 /// \brief Legacy analysis pass which computes \c BranchProbabilityInfo.
204 
205 public:
206  static char ID;
207 
211  }
212 
213  BranchProbabilityInfo &getBPI() { return BPI; }
214  const BranchProbabilityInfo &getBPI() const { return BPI; }
215 
216  void getAnalysisUsage(AnalysisUsage &AU) const override;
217  bool runOnFunction(Function &F) override;
218  void releaseMemory() override;
219  void print(raw_ostream &OS, const Module *M = nullptr) const override;
220 };
221 
222 }
223 
224 #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
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
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:51
BranchProbabilityInfo(BranchProbabilityInfo &&Arg)
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:311
Legacy analysis pass which computes BranchProbabilityInfo.
Printer pass for the BranchProbabilityAnalysis results.
void initializeBranchProbabilityInfoWrapperPassPass(PassRegistry &)
BranchProbabilityInfo(const Function &F, const LoopInfo &LI)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:328
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.
void calculate(const Function &F, const LoopInfo &LI)
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:333
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:64
static BranchProbability getBranchProbStackProtector(bool IsLikely)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
BranchProbability getCompl() const