]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Analysis/BranchProbabilityInfo.h
Import zstandard 1.1.4 in base
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / Analysis / BranchProbabilityInfo.h
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   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.
178 class BranchProbabilityAnalysis
179     : public AnalysisInfoMixin<BranchProbabilityAnalysis> {
180   friend AnalysisInfoMixin<BranchProbabilityAnalysis>;
181   static AnalysisKey Key;
182
183 public:
184   /// \brief Provide the result typedef for this analysis pass.
185   typedef BranchProbabilityInfo Result;
186
187   /// \brief Run the analysis pass over a function and produce BPI.
188   BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM);
189 };
190
191 /// \brief Printer pass for the \c BranchProbabilityAnalysis results.
192 class BranchProbabilityPrinterPass
193     : public PassInfoMixin<BranchProbabilityPrinterPass> {
194   raw_ostream &OS;
195
196 public:
197   explicit BranchProbabilityPrinterPass(raw_ostream &OS) : OS(OS) {}
198   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
199 };
200
201 /// \brief Legacy analysis pass which computes \c BranchProbabilityInfo.
202 class BranchProbabilityInfoWrapperPass : public FunctionPass {
203   BranchProbabilityInfo BPI;
204
205 public:
206   static char ID;
207
208   BranchProbabilityInfoWrapperPass() : FunctionPass(ID) {
209     initializeBranchProbabilityInfoWrapperPassPass(
210         *PassRegistry::getPassRegistry());
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