LLVM  4.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 
29 #ifndef NDEBUG
31  "view-block-freq-propagation-dags", cl::Hidden,
32  cl::desc("Pop up a window to show a dag displaying how block "
33  "frequencies propagation through the CFG."),
34  cl::values(clEnumValN(GVDT_None, "none", "do not display graphs."),
35  clEnumValN(GVDT_Fraction, "fraction",
36  "display a graph using the "
37  "fractional block frequency representation."),
38  clEnumValN(GVDT_Integer, "integer",
39  "display a graph using the raw "
40  "integer fractional block frequency representation."),
41  clEnumValN(GVDT_Count, "count", "display a graph using the real "
42  "profile count if available.")));
43 
45  ViewBlockFreqFuncName("view-bfi-func-name", cl::Hidden,
46  cl::desc("The option to specify "
47  "the name of the function "
48  "whose CFG will be displayed."));
49 
51  ViewHotFreqPercent("view-hot-freq-percent", cl::init(10), cl::Hidden,
52  cl::desc("An integer in percent used to specify "
53  "the hot blocks/edges to be displayed "
54  "in red: a block or edge whose frequency "
55  "is no less than the max frequency of the "
56  "function multiplied by this percent."));
57 
58 namespace llvm {
59 
60 template <>
62  typedef const BasicBlock *NodeRef;
65 
66  static NodeRef getEntryNode(const BlockFrequencyInfo *G) {
67  return &G->getFunction()->front();
68  }
69  static ChildIteratorType child_begin(const NodeRef N) {
70  return succ_begin(N);
71  }
72  static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
73  static nodes_iterator nodes_begin(const BlockFrequencyInfo *G) {
74  return nodes_iterator(G->getFunction()->begin());
75  }
76  static nodes_iterator nodes_end(const BlockFrequencyInfo *G) {
77  return nodes_iterator(G->getFunction()->end());
78  }
79 };
80 
83 
84 template <>
86  explicit DOTGraphTraits(bool isSimple = false)
88 
89  std::string getNodeLabel(const BasicBlock *Node,
90  const BlockFrequencyInfo *Graph) {
91 
92  return BFIDOTGTraitsBase::getNodeLabel(Node, Graph,
94  }
95 
96  std::string getNodeAttributes(const BasicBlock *Node,
97  const BlockFrequencyInfo *Graph) {
98  return BFIDOTGTraitsBase::getNodeAttributes(Node, Graph,
100  }
101 
102  std::string getEdgeAttributes(const BasicBlock *Node, EdgeIter EI,
103  const BlockFrequencyInfo *BFI) {
104  return BFIDOTGTraitsBase::getEdgeAttributes(Node, EI, BFI, BFI->getBPI(),
106  }
107 };
108 
109 } // end namespace llvm
110 #endif
111 
113 
115  const BranchProbabilityInfo &BPI,
116  const LoopInfo &LI) {
117  calculate(F, BPI, LI);
118 }
119 
121  : BFI(std::move(Arg.BFI)) {}
122 
123 BlockFrequencyInfo &BlockFrequencyInfo::operator=(BlockFrequencyInfo &&RHS) {
124  releaseMemory();
125  BFI = std::move(RHS.BFI);
126  return *this;
127 }
128 
129 // Explicitly define the default constructor otherwise it would be implicitly
130 // defined at the first ODR-use which is the BFI member in the
131 // LazyBlockFrequencyInfo header. The dtor needs the BlockFrequencyInfoImpl
132 // template instantiated which is not available in the header.
134 
136  const BranchProbabilityInfo &BPI,
137  const LoopInfo &LI) {
138  if (!BFI)
139  BFI.reset(new ImplType);
140  BFI->calculate(F, BPI, LI);
141 #ifndef NDEBUG
143  (ViewBlockFreqFuncName.empty() ||
145  view();
146  }
147 #endif
148 }
149 
151  return BFI ? BFI->getBlockFreq(BB) : 0;
152 }
153 
156  if (!BFI)
157  return None;
158 
159  return BFI->getBlockProfileCount(*getFunction(), BB);
160 }
161 
164  if (!BFI)
165  return None;
166  return BFI->getProfileCountFromFreq(*getFunction(), Freq);
167 }
168 
169 void BlockFrequencyInfo::setBlockFreq(const BasicBlock *BB, uint64_t Freq) {
170  assert(BFI && "Expected analysis to be available");
171  BFI->setBlockFreq(BB, Freq);
172 }
173 
174 /// Pop up a ghostview window with the current block frequency propagation
175 /// rendered using dot.
177 // This code is only for debugging.
178 #ifndef NDEBUG
179  ViewGraph(const_cast<BlockFrequencyInfo *>(this), "BlockFrequencyDAGs");
180 #else
181  errs() << "BlockFrequencyInfo::view is only available in debug builds on "
182  "systems with Graphviz or gv!\n";
183 #endif // NDEBUG
184 }
185 
187  return BFI ? BFI->getFunction() : nullptr;
188 }
189 
191  return BFI ? &BFI->getBPI() : nullptr;
192 }
193 
195 printBlockFreq(raw_ostream &OS, const BlockFrequency Freq) const {
196  return BFI ? BFI->printBlockFreq(OS, Freq) : OS;
197 }
198 
199 raw_ostream &
201  const BasicBlock *BB) const {
202  return BFI ? BFI->printBlockFreq(OS, BB) : OS;
203 }
204 
206  return BFI ? BFI->getEntryFreq() : 0;
207 }
208 
210 
212  if (BFI)
213  BFI->print(OS);
214 }
215 
216 
218  "Block Frequency Analysis", true, true)
222  "Block Frequency Analysis", true, true)
223 
224 char BlockFrequencyInfoWrapperPass::ID = 0;
225 
226 
227 BlockFrequencyInfoWrapperPass::BlockFrequencyInfoWrapperPass()
228  : FunctionPass(ID) {
230 }
231 
233 
235  const Module *) const {
236  BFI.print(OS);
237 }
238 
242  AU.setPreservesAll();
243 }
244 
246 
248  BranchProbabilityInfo &BPI =
249  getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
250  LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
251  BFI.calculate(F, BPI, LI);
252  return false;
253 }
254 
255 AnalysisKey BlockFrequencyAnalysis::Key;
260  AM.getResult<LoopAnalysis>(F));
261  return BFI;
262 }
263 
266  OS << "Printing analysis results of BFI for function "
267  << "'" << F.getName() << "':"
268  << "\n";
269  AM.getResult<BlockFrequencyAnalysis>(F).print(OS);
270  return PreservedAnalyses::all();
271 }
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 & errs()
This returns a reference to a raw_ostream for standard error.
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:52
iterator end()
Definition: Function.h:537
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)
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:191
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:53
void initializeBlockFrequencyInfoWrapperPassPass(PassRegistry &)
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:166
Legacy analysis pass which computes BlockFrequencyInfo.
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:806
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:51
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)
std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfoT *Graph, GVDAGType GType)
iterator begin()
Definition: Function.h:535
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:615
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:653
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
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.
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:339
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:113
std::string getEdgeAttributes(NodeRef Node, EdgeIter EI, const BlockFrequencyInfoT *BFI, const BranchProbabilityInfoT *BPI, unsigned HotPercentThreshold=0)
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.
GTraits::ChildIteratorType EdgeIter
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
void setBlockFreq(const BasicBlock *BB, uint64_t Freq)
void print(raw_ostream &OS) const
const BranchProbabilityInfo * getBPI() const
void setPreservesAll()
Set by analyses that do not transform their input at all.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:590
Analysis providing branch probability information.
block Block Frequency Analysis
const Function * getFunction() const
#define N
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...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
Definition: Function.h:542
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:831
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:64
BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
static nodes_iterator nodes_end(const BlockFrequencyInfo *G)