blob: 8175aa07d15afd8766e61a758c7554c59faecf8c [file] [log] [blame]
Duncan P. N. Exon Smith689a5072014-04-11 23:20:58 +00001//===- BlockFrequencyInfo.cpp - Block Frequency Analysis ------------------===//
Jakub Staszak668c6fa2011-06-23 21:56:59 +00002//
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
Jakub Staszak875ebd52011-07-25 19:25:40 +000014#include "llvm/Analysis/BlockFrequencyInfo.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/iterator.h"
Duncan P. N. Exon Smith689a5072014-04-11 23:20:58 +000018#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/BranchProbabilityInfo.h"
Jakub Staszak668c6fa2011-06-23 21:56:59 +000020#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000021#include "llvm/IR/CFG.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000022#include "llvm/IR/Function.h"
23#include "llvm/IR/PassManager.h"
24#include "llvm/Pass.h"
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000025#include "llvm/Support/CommandLine.h"
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000026#include "llvm/Support/GraphWriter.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000027#include "llvm/Support/raw_ostream.h"
28#include <algorithm>
29#include <cassert>
30#include <string>
Jakub Staszak668c6fa2011-06-23 21:56:59 +000031
32using namespace llvm;
33
Chandler Carruthf1221bd2014-04-22 02:48:03 +000034#define DEBUG_TYPE "block-freq"
35
Xinliang David Li8dd5ce92016-06-28 04:07:03 +000036static cl::opt<GVDAGType> ViewBlockFreqPropagationDAG(
37 "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(clEnumValN(GVDT_None, "none", "do not display graphs."),
41 clEnumValN(GVDT_Fraction, "fraction",
42 "display a graph using the "
43 "fractional block frequency representation."),
44 clEnumValN(GVDT_Integer, "integer",
45 "display a graph using the raw "
46 "integer fractional block frequency representation."),
47 clEnumValN(GVDT_Count, "count", "display a graph using the real "
Mehdi Amini732afdd2016-10-08 19:41:06 +000048 "profile count if available.")));
Xinliang David Li8dd5ce92016-06-28 04:07:03 +000049
Xinliang David Li3e176c72016-06-28 06:58:21 +000050cl::opt<std::string>
51 ViewBlockFreqFuncName("view-bfi-func-name", cl::Hidden,
52 cl::desc("The option to specify "
53 "the name of the function "
54 "whose CFG will be displayed."));
55
56cl::opt<unsigned>
57 ViewHotFreqPercent("view-hot-freq-percent", cl::init(10), cl::Hidden,
58 cl::desc("An integer in percent used to specify "
59 "the hot blocks/edges to be displayed "
60 "in red: a block or edge whose frequency "
61 "is no less than the max frequency of the "
62 "function multiplied by this percent."));
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000063
Xinliang David Licb253ce2017-01-23 18:58:24 +000064// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +000065cl::opt<bool>
66 PGOViewCounts("pgo-view-counts", cl::init(false), cl::Hidden,
67 cl::desc("A boolean option to show CFG dag with "
68 "block profile counts and branch probabilities "
69 "right after PGO profile annotation step. The "
70 "profile counts are computed using branch "
71 "probabilities from the runtime profile data and "
72 "block frequency propagation algorithm. To view "
73 "the raw counts from the profile, use option "
74 "-pgo-view-raw-counts instead. To limit graph "
75 "display to only one function, use filtering option "
76 "-view-bfi-func-name."));
Xinliang David Licb253ce2017-01-23 18:58:24 +000077
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000078namespace llvm {
79
Xinliang David Licb253ce2017-01-23 18:58:24 +000080static GVDAGType getGVDT() {
Xinliang David Licb253ce2017-01-23 18:58:24 +000081 if (PGOViewCounts)
82 return GVDT_Count;
83 return ViewBlockFreqPropagationDAG;
84}
85
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000086template <>
87struct GraphTraits<BlockFrequencyInfo *> {
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000088 using NodeRef = const BasicBlock *;
89 using ChildIteratorType = succ_const_iterator;
90 using nodes_iterator = pointer_iterator<Function::const_iterator>;
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000091
Tim Shen48f814e2016-08-31 16:48:13 +000092 static NodeRef getEntryNode(const BlockFrequencyInfo *G) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +000093 return &G->getFunction()->front();
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000094 }
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000095
Tim Shenf2187ed2016-08-22 21:09:30 +000096 static ChildIteratorType child_begin(const NodeRef N) {
Michael Gottesmanfd8aee72013-11-14 02:27:46 +000097 return succ_begin(N);
98 }
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000099
Tim Shenf2187ed2016-08-22 21:09:30 +0000100 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000101
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000102 static nodes_iterator nodes_begin(const BlockFrequencyInfo *G) {
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000103 return nodes_iterator(G->getFunction()->begin());
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000104 }
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000105
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000106 static nodes_iterator nodes_end(const BlockFrequencyInfo *G) {
Tim Shenb5e0f5a2016-08-19 21:20:13 +0000107 return nodes_iterator(G->getFunction()->end());
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000108 }
109};
110
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000111using BFIDOTGTraitsBase =
112 BFIDOTGraphTraitsBase<BlockFrequencyInfo, BranchProbabilityInfo>;
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000113
Xinliang David Li55415f22016-06-28 03:41:29 +0000114template <>
115struct DOTGraphTraits<BlockFrequencyInfo *> : public BFIDOTGTraitsBase {
116 explicit DOTGraphTraits(bool isSimple = false)
117 : BFIDOTGTraitsBase(isSimple) {}
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000118
119 std::string getNodeLabel(const BasicBlock *Node,
120 const BlockFrequencyInfo *Graph) {
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000121
Xinliang David Licb253ce2017-01-23 18:58:24 +0000122 return BFIDOTGTraitsBase::getNodeLabel(Node, Graph, getGVDT());
Xinliang David Li55415f22016-06-28 03:41:29 +0000123 }
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000124
Xinliang David Li3e176c72016-06-28 06:58:21 +0000125 std::string getNodeAttributes(const BasicBlock *Node,
126 const BlockFrequencyInfo *Graph) {
127 return BFIDOTGTraitsBase::getNodeAttributes(Node, Graph,
128 ViewHotFreqPercent);
129 }
130
Xinliang David Li55415f22016-06-28 03:41:29 +0000131 std::string getEdgeAttributes(const BasicBlock *Node, EdgeIter EI,
132 const BlockFrequencyInfo *BFI) {
Xinliang David Li3e176c72016-06-28 06:58:21 +0000133 return BFIDOTGTraitsBase::getEdgeAttributes(Node, EI, BFI, BFI->getBPI(),
134 ViewHotFreqPercent);
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000135 }
136};
137
138} // end namespace llvm
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000139
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000140BlockFrequencyInfo::BlockFrequencyInfo() = default;
Cong Hou9b4f6b22015-07-16 23:23:35 +0000141
142BlockFrequencyInfo::BlockFrequencyInfo(const Function &F,
143 const BranchProbabilityInfo &BPI,
144 const LoopInfo &LI) {
145 calculate(F, BPI, LI);
146}
147
Xinliang David Li28a93272016-05-05 21:13:27 +0000148BlockFrequencyInfo::BlockFrequencyInfo(BlockFrequencyInfo &&Arg)
149 : BFI(std::move(Arg.BFI)) {}
150
151BlockFrequencyInfo &BlockFrequencyInfo::operator=(BlockFrequencyInfo &&RHS) {
152 releaseMemory();
153 BFI = std::move(RHS.BFI);
154 return *this;
155}
156
Adam Nemetc2f791d2016-07-13 05:01:48 +0000157// Explicitly define the default constructor otherwise it would be implicitly
158// defined at the first ODR-use which is the BFI member in the
159// LazyBlockFrequencyInfo header. The dtor needs the BlockFrequencyInfoImpl
160// template instantiated which is not available in the header.
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000161BlockFrequencyInfo::~BlockFrequencyInfo() = default;
Adam Nemetc2f791d2016-07-13 05:01:48 +0000162
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000163bool BlockFrequencyInfo::invalidate(Function &F, const PreservedAnalyses &PA,
164 FunctionAnalysisManager::Invalidator &) {
165 // Check whether the analysis, all analyses on functions, or the function's
166 // CFG have been preserved.
167 auto PAC = PA.getChecker<BlockFrequencyAnalysis>();
168 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
169 PAC.preservedSet<CFGAnalyses>());
170}
171
Wei Mideee61e2015-07-14 23:40:50 +0000172void BlockFrequencyInfo::calculate(const Function &F,
173 const BranchProbabilityInfo &BPI,
174 const LoopInfo &LI) {
Duncan P. N. Exon Smith3dbe1052014-03-25 18:01:38 +0000175 if (!BFI)
176 BFI.reset(new ImplType);
Cong Hou5e67b662015-07-15 19:58:26 +0000177 BFI->calculate(F, BPI, LI);
Xinliang David Li8dd5ce92016-06-28 04:07:03 +0000178 if (ViewBlockFreqPropagationDAG != GVDT_None &&
179 (ViewBlockFreqFuncName.empty() ||
180 F.getName().equals(ViewBlockFreqFuncName))) {
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000181 view();
Xinliang David Li8dd5ce92016-06-28 04:07:03 +0000182 }
Chandler Carruth343fad42011-10-19 10:12:41 +0000183}
184
Jakub Staszak96f8c552011-12-20 20:03:10 +0000185BlockFrequency BlockFrequencyInfo::getBlockFreq(const BasicBlock *BB) const {
Duncan P. N. Exon Smith3dbe1052014-03-25 18:01:38 +0000186 return BFI ? BFI->getBlockFreq(BB) : 0;
Jakub Staszak668c6fa2011-06-23 21:56:59 +0000187}
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000188
Easwaran Raman12b79aa2016-03-23 18:18:26 +0000189Optional<uint64_t>
190BlockFrequencyInfo::getBlockProfileCount(const BasicBlock *BB) const {
Xinliang David Lib12b3532016-06-22 17:12:12 +0000191 if (!BFI)
Easwaran Raman12b79aa2016-03-23 18:18:26 +0000192 return None;
Xinliang David Lib12b3532016-06-22 17:12:12 +0000193
194 return BFI->getBlockProfileCount(*getFunction(), BB);
Easwaran Raman12b79aa2016-03-23 18:18:26 +0000195}
196
Sean Silvaf8015752016-08-02 02:15:45 +0000197Optional<uint64_t>
198BlockFrequencyInfo::getProfileCountFromFreq(uint64_t Freq) const {
199 if (!BFI)
200 return None;
201 return BFI->getProfileCountFromFreq(*getFunction(), Freq);
202}
203
Xinliang David Lib12b3532016-06-22 17:12:12 +0000204void BlockFrequencyInfo::setBlockFreq(const BasicBlock *BB, uint64_t Freq) {
Manman Ren72d44b12015-10-15 14:59:40 +0000205 assert(BFI && "Expected analysis to be available");
206 BFI->setBlockFreq(BB, Freq);
207}
208
Easwaran Raman6c8f5112017-01-19 18:53:16 +0000209void BlockFrequencyInfo::setBlockFreqAndScale(
210 const BasicBlock *ReferenceBB, uint64_t Freq,
211 SmallPtrSetImpl<BasicBlock *> &BlocksToScale) {
212 assert(BFI && "Expected analysis to be available");
213 // Use 128 bits APInt to avoid overflow.
214 APInt NewFreq(128, Freq);
215 APInt OldFreq(128, BFI->getBlockFreq(ReferenceBB).getFrequency());
216 APInt BBFreq(128, 0);
217 for (auto *BB : BlocksToScale) {
218 BBFreq = BFI->getBlockFreq(BB).getFrequency();
219 // Multiply first by NewFreq and then divide by OldFreq
220 // to minimize loss of precision.
221 BBFreq *= NewFreq;
222 // udiv is an expensive operation in the general case. If this ends up being
223 // a hot spot, one of the options proposed in
224 // https://reviews.llvm.org/D28535#650071 could be used to avoid this.
225 BBFreq = BBFreq.udiv(OldFreq);
226 BFI->setBlockFreq(BB, BBFreq.getLimitedValue());
227 }
228 BFI->setBlockFreq(ReferenceBB, Freq);
229}
230
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000231/// Pop up a ghostview window with the current block frequency propagation
232/// rendered using dot.
233void BlockFrequencyInfo::view() const {
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000234 ViewGraph(const_cast<BlockFrequencyInfo *>(this), "BlockFrequencyDAGs");
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000235}
236
237const Function *BlockFrequencyInfo::getFunction() const {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000238 return BFI ? BFI->getFunction() : nullptr;
Michael Gottesmanfd8aee72013-11-14 02:27:46 +0000239}
Michael Gottesmanfd5c4b22013-12-14 00:06:03 +0000240
Xinliang David Li55415f22016-06-28 03:41:29 +0000241const BranchProbabilityInfo *BlockFrequencyInfo::getBPI() const {
242 return BFI ? &BFI->getBPI() : nullptr;
243}
244
Michael Gottesmanfd5c4b22013-12-14 00:06:03 +0000245raw_ostream &BlockFrequencyInfo::
246printBlockFreq(raw_ostream &OS, const BlockFrequency Freq) const {
Duncan P. N. Exon Smith3dbe1052014-03-25 18:01:38 +0000247 return BFI ? BFI->printBlockFreq(OS, Freq) : OS;
Michael Gottesmanfd5c4b22013-12-14 00:06:03 +0000248}
249
250raw_ostream &
251BlockFrequencyInfo::printBlockFreq(raw_ostream &OS,
252 const BasicBlock *BB) const {
Duncan P. N. Exon Smith3dbe1052014-03-25 18:01:38 +0000253 return BFI ? BFI->printBlockFreq(OS, BB) : OS;
Michael Gottesmanfd5c4b22013-12-14 00:06:03 +0000254}
Yuchen Wu5947c8f2013-12-20 22:11:11 +0000255
256uint64_t BlockFrequencyInfo::getEntryFreq() const {
Duncan P. N. Exon Smith3dbe1052014-03-25 18:01:38 +0000257 return BFI ? BFI->getEntryFreq() : 0;
Yuchen Wu5947c8f2013-12-20 22:11:11 +0000258}
Wei Mideee61e2015-07-14 23:40:50 +0000259
260void BlockFrequencyInfo::releaseMemory() { BFI.reset(); }
261
262void BlockFrequencyInfo::print(raw_ostream &OS) const {
263 if (BFI)
264 BFI->print(OS);
265}
266
Wei Mideee61e2015-07-14 23:40:50 +0000267INITIALIZE_PASS_BEGIN(BlockFrequencyInfoWrapperPass, "block-freq",
268 "Block Frequency Analysis", true, true)
Cong Houab23bfb2015-07-15 22:48:29 +0000269INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Wei Mideee61e2015-07-14 23:40:50 +0000270INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
271INITIALIZE_PASS_END(BlockFrequencyInfoWrapperPass, "block-freq",
272 "Block Frequency Analysis", true, true)
273
274char BlockFrequencyInfoWrapperPass::ID = 0;
275
Wei Mideee61e2015-07-14 23:40:50 +0000276BlockFrequencyInfoWrapperPass::BlockFrequencyInfoWrapperPass()
277 : FunctionPass(ID) {
278 initializeBlockFrequencyInfoWrapperPassPass(*PassRegistry::getPassRegistry());
279}
280
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000281BlockFrequencyInfoWrapperPass::~BlockFrequencyInfoWrapperPass() = default;
Wei Mideee61e2015-07-14 23:40:50 +0000282
283void BlockFrequencyInfoWrapperPass::print(raw_ostream &OS,
284 const Module *) const {
285 BFI.print(OS);
286}
287
288void BlockFrequencyInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Cong Houab23bfb2015-07-15 22:48:29 +0000289 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Wei Mideee61e2015-07-14 23:40:50 +0000290 AU.addRequired<LoopInfoWrapperPass>();
291 AU.setPreservesAll();
292}
293
294void BlockFrequencyInfoWrapperPass::releaseMemory() { BFI.releaseMemory(); }
295
296bool BlockFrequencyInfoWrapperPass::runOnFunction(Function &F) {
Cong Houab23bfb2015-07-15 22:48:29 +0000297 BranchProbabilityInfo &BPI =
298 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Wei Mideee61e2015-07-14 23:40:50 +0000299 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
300 BFI.calculate(F, BPI, LI);
301 return false;
302}
Xinliang David Li28a93272016-05-05 21:13:27 +0000303
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000304AnalysisKey BlockFrequencyAnalysis::Key;
Xinliang David Li28a93272016-05-05 21:13:27 +0000305BlockFrequencyInfo BlockFrequencyAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000306 FunctionAnalysisManager &AM) {
Xinliang David Li28a93272016-05-05 21:13:27 +0000307 BlockFrequencyInfo BFI;
308 BFI.calculate(F, AM.getResult<BranchProbabilityAnalysis>(F),
309 AM.getResult<LoopAnalysis>(F));
310 return BFI;
311}
312
313PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +0000314BlockFrequencyPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li28a93272016-05-05 21:13:27 +0000315 OS << "Printing analysis results of BFI for function "
316 << "'" << F.getName() << "':"
317 << "\n";
318 AM.getResult<BlockFrequencyAnalysis>(F).print(OS);
319 return PreservedAnalyses::all();
320}