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 
14 #include "llvm/Analysis/BlockFrequencyInfo.h"
15 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
16 #include "llvm/Analysis/BranchProbabilityInfo.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/IR/CFG.h"
20 #include "llvm/InitializePasses.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/GraphWriter.h"
24 
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "block-freq"
28 
29 #ifndef NDEBUG
30 static cl::opt<GVDAGType> ViewBlockFreqPropagationDAG(
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 
44 cl::opt<std::string>
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 
50 cl::opt<unsigned>
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 <>
61 struct GraphTraits<BlockFrequencyInfo *> {
62   typedef const BasicBlock *NodeRef;
63   typedef succ_const_iterator ChildIteratorType;
64   typedef pointer_iterator<Function::const_iterator> nodes_iterator;
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 
81 typedef BFIDOTGraphTraitsBase<BlockFrequencyInfo, BranchProbabilityInfo>
82     BFIDOTGTraitsBase;
83 
84 template <>
85 struct DOTGraphTraits<BlockFrequencyInfo *> : public BFIDOTGTraitsBase {
86   explicit DOTGraphTraits(bool isSimple = false)
87       : BFIDOTGTraitsBase(isSimple) {}
88 
89   std::string getNodeLabel(const BasicBlock *Node,
90                            const BlockFrequencyInfo *Graph) {
91 
92     return BFIDOTGTraitsBase::getNodeLabel(Node, Graph,
93                                            ViewBlockFreqPropagationDAG);
94   }
95 
96   std::string getNodeAttributes(const BasicBlock *Node,
97                                 const BlockFrequencyInfo *Graph) {
98     return BFIDOTGTraitsBase::getNodeAttributes(Node, Graph,
99                                                 ViewHotFreqPercent);
100   }
101 
102   std::string getEdgeAttributes(const BasicBlock *Node, EdgeIter EI,
103                                 const BlockFrequencyInfo *BFI) {
104     return BFIDOTGTraitsBase::getEdgeAttributes(Node, EI, BFI, BFI->getBPI(),
105                                                 ViewHotFreqPercent);
106   }
107 };
108 
109 } // end namespace llvm
110 #endif
111 
112 BlockFrequencyInfo::BlockFrequencyInfo() {}
113 
114 BlockFrequencyInfo::BlockFrequencyInfo(const Function &F,
115                                        const BranchProbabilityInfo &BPI,
116                                        const LoopInfo &LI) {
117   calculate(F, BPI, LI);
118 }
119 
120 BlockFrequencyInfo::BlockFrequencyInfo(BlockFrequencyInfo &&Arg)
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.
133 BlockFrequencyInfo::~BlockFrequencyInfo() {}
134 
135 void BlockFrequencyInfo::calculate(const Function &F,
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
142   if (ViewBlockFreqPropagationDAG != GVDT_None &&
143       (ViewBlockFreqFuncName.empty() ||
144        F.getName().equals(ViewBlockFreqFuncName))) {
145     view();
146   }
147 #endif
148 }
149 
150 BlockFrequency BlockFrequencyInfo::getBlockFreq(const BasicBlock *BB) const {
151   return BFI ? BFI->getBlockFreq(BB) : 0;
152 }
153 
154 Optional<uint64_t>
155 BlockFrequencyInfo::getBlockProfileCount(const BasicBlock *BB) const {
156   if (!BFI)
157     return None;
158 
159   return BFI->getBlockProfileCount(*getFunction(), BB);
160 }
161 
162 Optional<uint64_t>
163 BlockFrequencyInfo::getProfileCountFromFreq(uint64_t Freq) const {
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.
176 void BlockFrequencyInfo::view() const {
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 
186 const Function *BlockFrequencyInfo::getFunction() const {
187   return BFI ? BFI->getFunction() : nullptr;
188 }
189 
190 const BranchProbabilityInfo *BlockFrequencyInfo::getBPI() const {
191   return BFI ? &BFI->getBPI() : nullptr;
192 }
193 
194 raw_ostream &BlockFrequencyInfo::
195 printBlockFreq(raw_ostream &OS, const BlockFrequency Freq) const {
196   return BFI ? BFI->printBlockFreq(OS, Freq) : OS;
197 }
198 
199 raw_ostream &
200 BlockFrequencyInfo::printBlockFreq(raw_ostream &OS,
201                                    const BasicBlock *BB) const {
202   return BFI ? BFI->printBlockFreq(OS, BB) : OS;
203 }
204 
205 uint64_t BlockFrequencyInfo::getEntryFreq() const {
206   return BFI ? BFI->getEntryFreq() : 0;
207 }
208 
209 void BlockFrequencyInfo::releaseMemory() { BFI.reset(); }
210 
211 void BlockFrequencyInfo::print(raw_ostream &OS) const {
212   if (BFI)
213     BFI->print(OS);
214 }
215 
216 
217 INITIALIZE_PASS_BEGIN(BlockFrequencyInfoWrapperPass, "block-freq",
218                       "Block Frequency Analysis", true, true)
219 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
220 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
221 INITIALIZE_PASS_END(BlockFrequencyInfoWrapperPass, "block-freq",
222                     "Block Frequency Analysis", true, true)
223 
224 char BlockFrequencyInfoWrapperPass::ID = 0;
225 
226 
227 BlockFrequencyInfoWrapperPass::BlockFrequencyInfoWrapperPass()
228     : FunctionPass(ID) {
229   initializeBlockFrequencyInfoWrapperPassPass(*PassRegistry::getPassRegistry());
230 }
231 
232 BlockFrequencyInfoWrapperPass::~BlockFrequencyInfoWrapperPass() {}
233 
234 void BlockFrequencyInfoWrapperPass::print(raw_ostream &OS,
235                                           const Module *) const {
236   BFI.print(OS);
237 }
238 
239 void BlockFrequencyInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
240   AU.addRequired<BranchProbabilityInfoWrapperPass>();
241   AU.addRequired<LoopInfoWrapperPass>();
242   AU.setPreservesAll();
243 }
244 
245 void BlockFrequencyInfoWrapperPass::releaseMemory() { BFI.releaseMemory(); }
246 
247 bool BlockFrequencyInfoWrapperPass::runOnFunction(Function &F) {
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 char BlockFrequencyAnalysis::PassID;
256 BlockFrequencyInfo BlockFrequencyAnalysis::run(Function &F,
257                                                FunctionAnalysisManager &AM) {
258   BlockFrequencyInfo BFI;
259   BFI.calculate(F, AM.getResult<BranchProbabilityAnalysis>(F),
260                 AM.getResult<LoopAnalysis>(F));
261   return BFI;
262 }
263 
264 PreservedAnalyses
265 BlockFrequencyPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
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 }
272