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 void BlockFrequencyInfo::setBlockFreqAndScale(
184     const BasicBlock *ReferenceBB, uint64_t Freq,
185     SmallPtrSetImpl<BasicBlock *> &BlocksToScale) {
186   assert(BFI && "Expected analysis to be available");
187   // Use 128 bits APInt to avoid overflow.
188   APInt NewFreq(128, Freq);
189   APInt OldFreq(128, BFI->getBlockFreq(ReferenceBB).getFrequency());
190   APInt BBFreq(128, 0);
191   for (auto *BB : BlocksToScale) {
192     BBFreq = BFI->getBlockFreq(BB).getFrequency();
193     // Multiply first by NewFreq and then divide by OldFreq
194     // to minimize loss of precision.
195     BBFreq *= NewFreq;
196     // udiv is an expensive operation in the general case. If this ends up being
197     // a hot spot, one of the options proposed in
198     // https://reviews.llvm.org/D28535#650071 could be used to avoid this.
199     BBFreq = BBFreq.udiv(OldFreq);
200     BFI->setBlockFreq(BB, BBFreq.getLimitedValue());
201   }
202   BFI->setBlockFreq(ReferenceBB, Freq);
203 }
204 
205 /// Pop up a ghostview window with the current block frequency propagation
206 /// rendered using dot.
207 void BlockFrequencyInfo::view() const {
208 // This code is only for debugging.
209 #ifndef NDEBUG
210   ViewGraph(const_cast<BlockFrequencyInfo *>(this), "BlockFrequencyDAGs");
211 #else
212   errs() << "BlockFrequencyInfo::view is only available in debug builds on "
213             "systems with Graphviz or gv!\n";
214 #endif // NDEBUG
215 }
216 
217 const Function *BlockFrequencyInfo::getFunction() const {
218   return BFI ? BFI->getFunction() : nullptr;
219 }
220 
221 const BranchProbabilityInfo *BlockFrequencyInfo::getBPI() const {
222   return BFI ? &BFI->getBPI() : nullptr;
223 }
224 
225 raw_ostream &BlockFrequencyInfo::
226 printBlockFreq(raw_ostream &OS, const BlockFrequency Freq) const {
227   return BFI ? BFI->printBlockFreq(OS, Freq) : OS;
228 }
229 
230 raw_ostream &
231 BlockFrequencyInfo::printBlockFreq(raw_ostream &OS,
232                                    const BasicBlock *BB) const {
233   return BFI ? BFI->printBlockFreq(OS, BB) : OS;
234 }
235 
236 uint64_t BlockFrequencyInfo::getEntryFreq() const {
237   return BFI ? BFI->getEntryFreq() : 0;
238 }
239 
240 void BlockFrequencyInfo::releaseMemory() { BFI.reset(); }
241 
242 void BlockFrequencyInfo::print(raw_ostream &OS) const {
243   if (BFI)
244     BFI->print(OS);
245 }
246 
247 
248 INITIALIZE_PASS_BEGIN(BlockFrequencyInfoWrapperPass, "block-freq",
249                       "Block Frequency Analysis", true, true)
250 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
251 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
252 INITIALIZE_PASS_END(BlockFrequencyInfoWrapperPass, "block-freq",
253                     "Block Frequency Analysis", true, true)
254 
255 char BlockFrequencyInfoWrapperPass::ID = 0;
256 
257 
258 BlockFrequencyInfoWrapperPass::BlockFrequencyInfoWrapperPass()
259     : FunctionPass(ID) {
260   initializeBlockFrequencyInfoWrapperPassPass(*PassRegistry::getPassRegistry());
261 }
262 
263 BlockFrequencyInfoWrapperPass::~BlockFrequencyInfoWrapperPass() {}
264 
265 void BlockFrequencyInfoWrapperPass::print(raw_ostream &OS,
266                                           const Module *) const {
267   BFI.print(OS);
268 }
269 
270 void BlockFrequencyInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
271   AU.addRequired<BranchProbabilityInfoWrapperPass>();
272   AU.addRequired<LoopInfoWrapperPass>();
273   AU.setPreservesAll();
274 }
275 
276 void BlockFrequencyInfoWrapperPass::releaseMemory() { BFI.releaseMemory(); }
277 
278 bool BlockFrequencyInfoWrapperPass::runOnFunction(Function &F) {
279   BranchProbabilityInfo &BPI =
280       getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
281   LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
282   BFI.calculate(F, BPI, LI);
283   return false;
284 }
285 
286 AnalysisKey BlockFrequencyAnalysis::Key;
287 BlockFrequencyInfo BlockFrequencyAnalysis::run(Function &F,
288                                                FunctionAnalysisManager &AM) {
289   BlockFrequencyInfo BFI;
290   BFI.calculate(F, AM.getResult<BranchProbabilityAnalysis>(F),
291                 AM.getResult<LoopAnalysis>(F));
292   return BFI;
293 }
294 
295 PreservedAnalyses
296 BlockFrequencyPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
297   OS << "Printing analysis results of BFI for function "
298      << "'" << F.getName() << "':"
299      << "\n";
300   AM.getResult<BlockFrequencyAnalysis>(F).print(OS);
301   return PreservedAnalyses::all();
302 }
303