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 bool BlockFrequencyInfo::invalidate(Function &F, const PreservedAnalyses &PA,
136                                     FunctionAnalysisManager::Invalidator &) {
137   // Check whether the analysis, all analyses on functions, or the function's
138   // CFG have been preserved.
139   auto PAC = PA.getChecker<BlockFrequencyAnalysis>();
140   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
141            PAC.preservedSet<CFGAnalyses>());
142 }
143 
144 void BlockFrequencyInfo::calculate(const Function &F,
145                                    const BranchProbabilityInfo &BPI,
146                                    const LoopInfo &LI) {
147   if (!BFI)
148     BFI.reset(new ImplType);
149   BFI->calculate(F, BPI, LI);
150 #ifndef NDEBUG
151   if (ViewBlockFreqPropagationDAG != GVDT_None &&
152       (ViewBlockFreqFuncName.empty() ||
153        F.getName().equals(ViewBlockFreqFuncName))) {
154     view();
155   }
156 #endif
157 }
158 
159 BlockFrequency BlockFrequencyInfo::getBlockFreq(const BasicBlock *BB) const {
160   return BFI ? BFI->getBlockFreq(BB) : 0;
161 }
162 
163 Optional<uint64_t>
164 BlockFrequencyInfo::getBlockProfileCount(const BasicBlock *BB) const {
165   if (!BFI)
166     return None;
167 
168   return BFI->getBlockProfileCount(*getFunction(), BB);
169 }
170 
171 Optional<uint64_t>
172 BlockFrequencyInfo::getProfileCountFromFreq(uint64_t Freq) const {
173   if (!BFI)
174     return None;
175   return BFI->getProfileCountFromFreq(*getFunction(), Freq);
176 }
177 
178 void BlockFrequencyInfo::setBlockFreq(const BasicBlock *BB, uint64_t Freq) {
179   assert(BFI && "Expected analysis to be available");
180   BFI->setBlockFreq(BB, Freq);
181 }
182 
183 /// Pop up a ghostview window with the current block frequency propagation
184 /// rendered using dot.
185 void BlockFrequencyInfo::view() const {
186 // This code is only for debugging.
187 #ifndef NDEBUG
188   ViewGraph(const_cast<BlockFrequencyInfo *>(this), "BlockFrequencyDAGs");
189 #else
190   errs() << "BlockFrequencyInfo::view is only available in debug builds on "
191             "systems with Graphviz or gv!\n";
192 #endif // NDEBUG
193 }
194 
195 const Function *BlockFrequencyInfo::getFunction() const {
196   return BFI ? BFI->getFunction() : nullptr;
197 }
198 
199 const BranchProbabilityInfo *BlockFrequencyInfo::getBPI() const {
200   return BFI ? &BFI->getBPI() : nullptr;
201 }
202 
203 raw_ostream &BlockFrequencyInfo::
204 printBlockFreq(raw_ostream &OS, const BlockFrequency Freq) const {
205   return BFI ? BFI->printBlockFreq(OS, Freq) : OS;
206 }
207 
208 raw_ostream &
209 BlockFrequencyInfo::printBlockFreq(raw_ostream &OS,
210                                    const BasicBlock *BB) const {
211   return BFI ? BFI->printBlockFreq(OS, BB) : OS;
212 }
213 
214 uint64_t BlockFrequencyInfo::getEntryFreq() const {
215   return BFI ? BFI->getEntryFreq() : 0;
216 }
217 
218 void BlockFrequencyInfo::releaseMemory() { BFI.reset(); }
219 
220 void BlockFrequencyInfo::print(raw_ostream &OS) const {
221   if (BFI)
222     BFI->print(OS);
223 }
224 
225 
226 INITIALIZE_PASS_BEGIN(BlockFrequencyInfoWrapperPass, "block-freq",
227                       "Block Frequency Analysis", true, true)
228 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
229 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
230 INITIALIZE_PASS_END(BlockFrequencyInfoWrapperPass, "block-freq",
231                     "Block Frequency Analysis", true, true)
232 
233 char BlockFrequencyInfoWrapperPass::ID = 0;
234 
235 
236 BlockFrequencyInfoWrapperPass::BlockFrequencyInfoWrapperPass()
237     : FunctionPass(ID) {
238   initializeBlockFrequencyInfoWrapperPassPass(*PassRegistry::getPassRegistry());
239 }
240 
241 BlockFrequencyInfoWrapperPass::~BlockFrequencyInfoWrapperPass() {}
242 
243 void BlockFrequencyInfoWrapperPass::print(raw_ostream &OS,
244                                           const Module *) const {
245   BFI.print(OS);
246 }
247 
248 void BlockFrequencyInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
249   AU.addRequired<BranchProbabilityInfoWrapperPass>();
250   AU.addRequired<LoopInfoWrapperPass>();
251   AU.setPreservesAll();
252 }
253 
254 void BlockFrequencyInfoWrapperPass::releaseMemory() { BFI.releaseMemory(); }
255 
256 bool BlockFrequencyInfoWrapperPass::runOnFunction(Function &F) {
257   BranchProbabilityInfo &BPI =
258       getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
259   LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
260   BFI.calculate(F, BPI, LI);
261   return false;
262 }
263 
264 AnalysisKey BlockFrequencyAnalysis::Key;
265 BlockFrequencyInfo BlockFrequencyAnalysis::run(Function &F,
266                                                FunctionAnalysisManager &AM) {
267   BlockFrequencyInfo BFI;
268   BFI.calculate(F, AM.getResult<BranchProbabilityAnalysis>(F),
269                 AM.getResult<LoopAnalysis>(F));
270   return BFI;
271 }
272 
273 PreservedAnalyses
274 BlockFrequencyPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
275   OS << "Printing analysis results of BFI for function "
276      << "'" << F.getName() << "':"
277      << "\n";
278   AM.getResult<BlockFrequencyAnalysis>(F).print(OS);
279   return PreservedAnalyses::all();
280 }
281