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 enum GVDAGType {
31   GVDT_None,
32   GVDT_Fraction,
33   GVDT_Integer
34 };
35 
36 static cl::opt<GVDAGType>
37 ViewBlockFreqPropagationDAG("view-block-freq-propagation-dags", cl::Hidden,
38           cl::desc("Pop up a window to show a dag displaying how block "
39                    "frequencies propagation through the CFG."),
40           cl::values(
41             clEnumValN(GVDT_None, "none",
42                        "do not display graphs."),
43             clEnumValN(GVDT_Fraction, "fraction", "display a graph using the "
44                        "fractional block frequency representation."),
45             clEnumValN(GVDT_Integer, "integer", "display a graph using the raw "
46                        "integer fractional block frequency representation."),
47             clEnumValEnd));
48 
49 namespace llvm {
50 
51 template <>
52 struct GraphTraits<BlockFrequencyInfo *> {
53   typedef const BasicBlock NodeType;
54   typedef succ_const_iterator ChildIteratorType;
55   typedef Function::const_iterator nodes_iterator;
56 
57   static inline const NodeType *getEntryNode(const BlockFrequencyInfo *G) {
58     return &G->getFunction()->front();
59   }
60   static ChildIteratorType child_begin(const NodeType *N) {
61     return succ_begin(N);
62   }
63   static ChildIteratorType child_end(const NodeType *N) {
64     return succ_end(N);
65   }
66   static nodes_iterator nodes_begin(const BlockFrequencyInfo *G) {
67     return G->getFunction()->begin();
68   }
69   static nodes_iterator nodes_end(const BlockFrequencyInfo *G) {
70     return G->getFunction()->end();
71   }
72 };
73 
74 template<>
75 struct DOTGraphTraits<BlockFrequencyInfo*> : public DefaultDOTGraphTraits {
76   explicit DOTGraphTraits(bool isSimple=false) :
77     DefaultDOTGraphTraits(isSimple) {}
78 
79   static std::string getGraphName(const BlockFrequencyInfo *G) {
80     return G->getFunction()->getName();
81   }
82 
83   std::string getNodeLabel(const BasicBlock *Node,
84                            const BlockFrequencyInfo *Graph) {
85     std::string Result;
86     raw_string_ostream OS(Result);
87 
88     OS << Node->getName() << ":";
89     switch (ViewBlockFreqPropagationDAG) {
90     case GVDT_Fraction:
91       Graph->printBlockFreq(OS, Node);
92       break;
93     case GVDT_Integer:
94       OS << Graph->getBlockFreq(Node).getFrequency();
95       break;
96     case GVDT_None:
97       llvm_unreachable("If we are not supposed to render a graph we should "
98                        "never reach this point.");
99     }
100 
101     return Result;
102   }
103 };
104 
105 } // end namespace llvm
106 #endif
107 
108 BlockFrequencyInfo::BlockFrequencyInfo() {}
109 
110 BlockFrequencyInfo::BlockFrequencyInfo(const Function &F,
111                                        const BranchProbabilityInfo &BPI,
112                                        const LoopInfo &LI) {
113   calculate(F, BPI, LI);
114 }
115 
116 BlockFrequencyInfo::BlockFrequencyInfo(BlockFrequencyInfo &&Arg)
117     : BFI(std::move(Arg.BFI)) {}
118 
119 BlockFrequencyInfo &BlockFrequencyInfo::operator=(BlockFrequencyInfo &&RHS) {
120   releaseMemory();
121   BFI = std::move(RHS.BFI);
122   return *this;
123 }
124 
125 void BlockFrequencyInfo::calculate(const Function &F,
126                                    const BranchProbabilityInfo &BPI,
127                                    const LoopInfo &LI) {
128   if (!BFI)
129     BFI.reset(new ImplType);
130   BFI->calculate(F, BPI, LI);
131 #ifndef NDEBUG
132   if (ViewBlockFreqPropagationDAG != GVDT_None)
133     view();
134 #endif
135 }
136 
137 BlockFrequency BlockFrequencyInfo::getBlockFreq(const BasicBlock *BB) const {
138   return BFI ? BFI->getBlockFreq(BB) : 0;
139 }
140 
141 Optional<uint64_t>
142 BlockFrequencyInfo::getBlockProfileCount(const BasicBlock *BB) const {
143   auto EntryCount = getFunction()->getEntryCount();
144   if (!EntryCount)
145     return None;
146   // Use 128 bit APInt to do the arithmetic to avoid overflow.
147   APInt BlockCount(128, EntryCount.getValue());
148   APInt BlockFreq(128, getBlockFreq(BB).getFrequency());
149   APInt EntryFreq(128, getEntryFreq());
150   BlockCount *= BlockFreq;
151   BlockCount = BlockCount.udiv(EntryFreq);
152   return BlockCount.getLimitedValue();
153 }
154 
155 void BlockFrequencyInfo::setBlockFreq(const BasicBlock *BB,
156                                       uint64_t Freq) {
157   assert(BFI && "Expected analysis to be available");
158   BFI->setBlockFreq(BB, Freq);
159 }
160 
161 /// Pop up a ghostview window with the current block frequency propagation
162 /// rendered using dot.
163 void BlockFrequencyInfo::view() const {
164 // This code is only for debugging.
165 #ifndef NDEBUG
166   ViewGraph(const_cast<BlockFrequencyInfo *>(this), "BlockFrequencyDAGs");
167 #else
168   errs() << "BlockFrequencyInfo::view is only available in debug builds on "
169             "systems with Graphviz or gv!\n";
170 #endif // NDEBUG
171 }
172 
173 const Function *BlockFrequencyInfo::getFunction() const {
174   return BFI ? BFI->getFunction() : nullptr;
175 }
176 
177 raw_ostream &BlockFrequencyInfo::
178 printBlockFreq(raw_ostream &OS, const BlockFrequency Freq) const {
179   return BFI ? BFI->printBlockFreq(OS, Freq) : OS;
180 }
181 
182 raw_ostream &
183 BlockFrequencyInfo::printBlockFreq(raw_ostream &OS,
184                                    const BasicBlock *BB) const {
185   return BFI ? BFI->printBlockFreq(OS, BB) : OS;
186 }
187 
188 uint64_t BlockFrequencyInfo::getEntryFreq() const {
189   return BFI ? BFI->getEntryFreq() : 0;
190 }
191 
192 void BlockFrequencyInfo::releaseMemory() { BFI.reset(); }
193 
194 void BlockFrequencyInfo::print(raw_ostream &OS) const {
195   if (BFI)
196     BFI->print(OS);
197 }
198 
199 
200 INITIALIZE_PASS_BEGIN(BlockFrequencyInfoWrapperPass, "block-freq",
201                       "Block Frequency Analysis", true, true)
202 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
203 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
204 INITIALIZE_PASS_END(BlockFrequencyInfoWrapperPass, "block-freq",
205                     "Block Frequency Analysis", true, true)
206 
207 char BlockFrequencyInfoWrapperPass::ID = 0;
208 
209 
210 BlockFrequencyInfoWrapperPass::BlockFrequencyInfoWrapperPass()
211     : FunctionPass(ID) {
212   initializeBlockFrequencyInfoWrapperPassPass(*PassRegistry::getPassRegistry());
213 }
214 
215 BlockFrequencyInfoWrapperPass::~BlockFrequencyInfoWrapperPass() {}
216 
217 void BlockFrequencyInfoWrapperPass::print(raw_ostream &OS,
218                                           const Module *) const {
219   BFI.print(OS);
220 }
221 
222 void BlockFrequencyInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
223   AU.addRequired<BranchProbabilityInfoWrapperPass>();
224   AU.addRequired<LoopInfoWrapperPass>();
225   AU.setPreservesAll();
226 }
227 
228 void BlockFrequencyInfoWrapperPass::releaseMemory() { BFI.releaseMemory(); }
229 
230 bool BlockFrequencyInfoWrapperPass::runOnFunction(Function &F) {
231   BranchProbabilityInfo &BPI =
232       getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
233   LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
234   BFI.calculate(F, BPI, LI);
235   return false;
236 }
237 
238 char BlockFrequencyAnalysis::PassID;
239 BlockFrequencyInfo BlockFrequencyAnalysis::run(Function &F,
240                                                AnalysisManager<Function> &AM) {
241   BlockFrequencyInfo BFI;
242   BFI.calculate(F, AM.getResult<BranchProbabilityAnalysis>(F),
243                 AM.getResult<LoopAnalysis>(F));
244   return BFI;
245 }
246 
247 PreservedAnalyses
248 BlockFrequencyPrinterPass::run(Function &F, AnalysisManager<Function> &AM) {
249   OS << "Printing analysis results of BFI for function "
250      << "'" << F.getName() << "':"
251      << "\n";
252   AM.getResult<BlockFrequencyAnalysis>(F).print(OS);
253   return PreservedAnalyses::all();
254 }
255