LLVM  5.0.0
BlockFrequencyInfo.cpp
Go to the documentation of this file.
1 //===- BlockFrequencyInfo.cpp - Block Frequency Analysis ------------------===//
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 // Loops should be simplified before this analysis.
11 //
12 //===----------------------------------------------------------------------===//
13 
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/IR/CFG.h"
20 #include "llvm/InitializePasses.h"
22 #include "llvm/Support/Debug.h"
24 
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "block-freq"
28 
30  "view-block-freq-propagation-dags", cl::Hidden,
31  cl::desc("Pop up a window to show a dag displaying how block "
32  "frequencies propagation through the CFG."),
33  cl::values(clEnumValN(GVDT_None, "none", "do not display graphs."),
34  clEnumValN(GVDT_Fraction, "fraction",
35  "display a graph using the "
36  "fractional block frequency representation."),
37  clEnumValN(GVDT_Integer, "integer",
38  "display a graph using the raw "
39  "integer fractional block frequency representation."),
40  clEnumValN(GVDT_Count, "count", "display a graph using the real "
41  "profile count if available.")));
42 
44  ViewBlockFreqFuncName("view-bfi-func-name", cl::Hidden,
45  cl::desc("The option to specify "
46  "the name of the function "
47  "whose CFG will be displayed."));
48 
50  ViewHotFreqPercent("view-hot-freq-percent", cl::init(10), cl::Hidden,
51  cl::desc("An integer in percent used to specify "
52  "the hot blocks/edges to be displayed "
53  "in red: a block or edge whose frequency "
54  "is no less than the max frequency of the "
55  "function multiplied by this percent."));
56 
57 // Command line option to turn on CFG dot dump after profile annotation.
59  PGOViewCounts("pgo-view-counts", cl::init(false), cl::Hidden,
60  cl::desc("A boolean option to show CFG dag with "
61  "block profile counts and branch probabilities "
62  "right after PGO profile annotation step. The "
63  "profile counts are computed using branch "
64  "probabilities from the runtime profile data and "
65  "block frequency propagation algorithm. To view "
66  "the raw counts from the profile, use option "
67  "-pgo-view-raw-counts instead. To limit graph "
68  "display to only one function, use filtering option "
69  "-view-bfi-func-name."));
70 
71 namespace llvm {
72 
73 static GVDAGType getGVDT() {
74 
75  if (PGOViewCounts)
76  return GVDT_Count;
78 }
79 
80 template <>
82  typedef const BasicBlock *NodeRef;
85 
86  static NodeRef getEntryNode(const BlockFrequencyInfo *G) {
87  return &G->getFunction()->front();
88  }
89  static ChildIteratorType child_begin(const NodeRef N) {
90  return succ_begin(N);
91  }
92  static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
93  static nodes_iterator nodes_begin(const BlockFrequencyInfo *G) {
94  return nodes_iterator(G->getFunction()->begin());
95  }
96  static nodes_iterator nodes_end(const BlockFrequencyInfo *G) {
97  return nodes_iterator(G->getFunction()->end());
98  }
99 };
100 
103 
104 template <>
106  explicit DOTGraphTraits(bool isSimple = false)
108 
109  std::string getNodeLabel(const BasicBlock *Node,
110  const BlockFrequencyInfo *Graph) {
111 
112  return BFIDOTGTraitsBase::getNodeLabel(Node, Graph, getGVDT());
113  }
114 
115  std::string getNodeAttributes(const BasicBlock *Node,
116  const BlockFrequencyInfo *Graph) {
117  return BFIDOTGTraitsBase::getNodeAttributes(Node, Graph,
119  }
120 
121  std::string getEdgeAttributes(const BasicBlock *Node, EdgeIter EI,
122  const BlockFrequencyInfo *BFI) {
123  return BFIDOTGTraitsBase::getEdgeAttributes(Node, EI, BFI, BFI->getBPI(),
125  }
126 };
127 
128 } // end namespace llvm
129 
131 
133  const BranchProbabilityInfo &BPI,
134  const LoopInfo &LI) {
135  calculate(F, BPI, LI);
136 }
137 
139  : BFI(std::move(Arg.BFI)) {}
140 
141 BlockFrequencyInfo &BlockFrequencyInfo::operator=(BlockFrequencyInfo &&RHS) {
142  releaseMemory();
143  BFI = std::move(RHS.BFI);
144  return *this;
145 }
146 
147 // Explicitly define the default constructor otherwise it would be implicitly
148 // defined at the first ODR-use which is the BFI member in the
149 // LazyBlockFrequencyInfo header. The dtor needs the BlockFrequencyInfoImpl
150 // template instantiated which is not available in the header.
152 
155  // Check whether the analysis, all analyses on functions, or the function's
156  // CFG have been preserved.
157  auto PAC = PA.getChecker<BlockFrequencyAnalysis>();
158  return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
159  PAC.preservedSet<CFGAnalyses>());
160 }
161 
163  const BranchProbabilityInfo &BPI,
164  const LoopInfo &LI) {
165  if (!BFI)
166  BFI.reset(new ImplType);
167  BFI->calculate(F, BPI, LI);
169  (ViewBlockFreqFuncName.empty() ||
171  view();
172  }
173 }
174 
176  return BFI ? BFI->getBlockFreq(BB) : 0;
177 }
178 
181  if (!BFI)
182  return None;
183 
184  return BFI->getBlockProfileCount(*getFunction(), BB);
185 }
186 
189  if (!BFI)
190  return None;
191  return BFI->getProfileCountFromFreq(*getFunction(), Freq);
192 }
193 
194 void BlockFrequencyInfo::setBlockFreq(const BasicBlock *BB, uint64_t Freq) {
195  assert(BFI && "Expected analysis to be available");
196  BFI->setBlockFreq(BB, Freq);
197 }
198 
200  const BasicBlock *ReferenceBB, uint64_t Freq,
201  SmallPtrSetImpl<BasicBlock *> &BlocksToScale) {
202  assert(BFI && "Expected analysis to be available");
203  // Use 128 bits APInt to avoid overflow.
204  APInt NewFreq(128, Freq);
205  APInt OldFreq(128, BFI->getBlockFreq(ReferenceBB).getFrequency());
206  APInt BBFreq(128, 0);
207  for (auto *BB : BlocksToScale) {
208  BBFreq = BFI->getBlockFreq(BB).getFrequency();
209  // Multiply first by NewFreq and then divide by OldFreq
210  // to minimize loss of precision.
211  BBFreq *= NewFreq;
212  // udiv is an expensive operation in the general case. If this ends up being
213  // a hot spot, one of the options proposed in
214  // https://reviews.llvm.org/D28535#650071 could be used to avoid this.
215  BBFreq = BBFreq.udiv(OldFreq);
216  BFI->setBlockFreq(BB, BBFreq.getLimitedValue());
217  }
218  BFI->setBlockFreq(ReferenceBB, Freq);
219 }
220 
221 /// Pop up a ghostview window with the current block frequency propagation
222 /// rendered using dot.
224  ViewGraph(const_cast<BlockFrequencyInfo *>(this), "BlockFrequencyDAGs");
225 }
226 
228  return BFI ? BFI->getFunction() : nullptr;
229 }
230 
232  return BFI ? &BFI->getBPI() : nullptr;
233 }
234 
236 printBlockFreq(raw_ostream &OS, const BlockFrequency Freq) const {
237  return BFI ? BFI->printBlockFreq(OS, Freq) : OS;
238 }
239 
240 raw_ostream &
242  const BasicBlock *BB) const {
243  return BFI ? BFI->printBlockFreq(OS, BB) : OS;
244 }
245 
247  return BFI ? BFI->getEntryFreq() : 0;
248 }
249 
251 
253  if (BFI)
254  BFI->print(OS);
255 }
256 
257 
259  "Block Frequency Analysis", true, true)
263  "Block Frequency Analysis", true, true)
264 
265 char BlockFrequencyInfoWrapperPass::ID = 0;
266 
267 
268 BlockFrequencyInfoWrapperPass::BlockFrequencyInfoWrapperPass()
269  : FunctionPass(ID) {
271 }
272 
274 
276  const Module *) const {
277  BFI.print(OS);
278 }
279 
283  AU.setPreservesAll();
284 }
285 
287 
289  BranchProbabilityInfo &BPI =
290  getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
291  LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
292  BFI.calculate(F, BPI, LI);
293  return false;
294 }
295 
296 AnalysisKey BlockFrequencyAnalysis::Key;
301  AM.getResult<LoopAnalysis>(F));
302  return BFI;
303 }
304 
307  OS << "Printing analysis results of BFI for function "
308  << "'" << F.getName() << "':"
309  << "\n";
310  AM.getResult<BlockFrequencyAnalysis>(F).print(OS);
311  return PreservedAnalyses::all();
312 }
static NodeRef getEntryNode(const BlockFrequencyInfo *G)
Result run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce BFI.
block Block Frequency true
cl::opt< unsigned > ViewHotFreqPercent("view-hot-freq-percent", cl::init(10), cl::Hidden, cl::desc("An integer in percent used to specify ""the hot blocks/edges to be displayed ""in red: a block or edge whose frequency ""is no less than the max frequency of the ""function multiplied by this percent."))
std::string getNodeLabel(const BasicBlock *Node, const BlockFrequencyInfo *Graph)
raw_ostream & printBlockFreq(raw_ostream &OS, const BlockFrequency Freq) const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
iterator end()
Definition: Function.h:582
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static GVDAGType getGVDT()
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:345
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
void initializeBlockFrequencyInfoWrapperPassPass(PassRegistry &)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:687
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
Definition: StringRef.h:169
Legacy analysis pass which computes BlockFrequencyInfo.
void setBlockFreqAndScale(const BasicBlock *ReferenceBB, uint64_t Freq, SmallPtrSetImpl< BasicBlock * > &BlocksToScale)
Set the frequency of ReferenceBB to Freq and scale the frequencies of the blocks in BlocksToScale suc...
std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfoT *Graph, GVDAGType GType, int layout_order=-1)
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:820
std::string getNodeAttributes(const BasicBlock *Node, const BlockFrequencyInfo *Graph)
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:106
static bool isSimple(Instruction *I)
Analysis pass which computes BranchProbabilityInfo.
#define F(x, y, z)
Definition: MD5.cpp:55
static nodes_iterator nodes_begin(const BlockFrequencyInfo *G)
Optional< uint64_t > getProfileCountFromFreq(uint64_t Freq) const
Returns the estimated profile count of Freq.
static ChildIteratorType child_end(const NodeRef N)
iterator begin()
Definition: Function.h:580
Legacy analysis pass which computes BranchProbabilityInfo.
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:109
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:621
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
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
block freq
pointer_iterator< Function::const_iterator > nodes_iterator
static ChildIteratorType child_begin(const NodeRef N)
void calculate(const Function &F, const BranchProbabilityInfo &BPI, const LoopInfo &LI)
calculate - compute block frequency info for the given function.
Represent the analysis usage information of a pass.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: PassManager.h:304
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
BFIDOTGraphTraitsBase< BlockFrequencyInfo, BranchProbabilityInfo > BFIDOTGTraitsBase
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
Definition: GraphWriter.h:348
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
std::string getEdgeAttributes(NodeRef Node, EdgeIter EI, const BlockFrequencyInfoT *BFI, const BranchProbabilityInfoT *BPI, unsigned HotPercentThreshold=0)
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
std::string getNodeAttributes(NodeRef Node, const BlockFrequencyInfoT *Graph, unsigned HotPercentThreshold=0)
std::string getEdgeAttributes(const BasicBlock *Node, EdgeIter EI, const BlockFrequencyInfo *BFI)
Analysis pass which computes BlockFrequencyInfo.
cl::opt< bool > PGOViewCounts("pgo-view-counts", cl::init(false), cl::Hidden, cl::desc("A boolean option to show CFG dag with ""block profile counts and branch probabilities ""right after PGO profile annotation step. The ""profile counts are computed using branch ""probabilities from the runtime profile data and ""block frequency propagation algorithm. To view ""the raw counts from the profile, use option ""-pgo-view-raw-counts instead. To limit graph ""display to only one function, use filtering option ""-view-bfi-func-name."))
GTraits::ChildIteratorType EdgeIter
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
void setBlockFreq(const BasicBlock *BB, uint64_t Freq)
const size_t N
void print(raw_ostream &OS) const
Class for arbitrary precision integers.
Definition: APInt.h:69
const BranchProbabilityInfo * getBPI() const
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represents analyses that only rely on functions' control flow.
Definition: PassManager.h:114
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:596
Analysis providing branch probability information.
block Block Frequency Analysis
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1519
const Function * getFunction() const
INITIALIZE_PASS_BEGIN(BlockFrequencyInfoWrapperPass,"block-freq","Block Frequency Analysis", true, true) INITIALIZE_PASS_END(BlockFrequencyInfoWrapperPass
cl::opt< std::string > ViewBlockFreqFuncName("view-bfi-func-name", cl::Hidden, cl::desc("The option to specify ""the name of the function ""whose CFG will be displayed."))
void view() const
Pop up a ghostview window with the current block frequency propagation rendered using dot...
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:559
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over \<a particular IR unit\>" (e...
Definition: PassManager.h:91
const BasicBlock & front() const
Definition: Function.h:587
static cl::opt< GVDAGType > ViewBlockFreqPropagationDAG("view-block-freq-propagation-dags", cl::Hidden, cl::desc("Pop up a window to show a dag displaying how block ""frequencies propagation through the CFG."), cl::values(clEnumValN(GVDT_None,"none","do not display graphs."), clEnumValN(GVDT_Fraction,"fraction","display a graph using the ""fractional block frequency representation."), clEnumValN(GVDT_Integer,"integer","display a graph using the raw ""integer fractional block frequency representation."), clEnumValN(GVDT_Count,"count","display a graph using the real ""profile count if available.")))
void print(raw_ostream &OS, const Module *M) const override
print - Print out the internal state of the pass.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
The legacy pass manager's analysis pass to compute loop information.
Definition: LoopInfo.h:845
Shared implementation for block frequency analysis.
A container for analyses that lazily runs them and caches their results.
Optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
static nodes_iterator nodes_end(const BlockFrequencyInfo *G)