1//===- BlockFrequencyInfo.cpp - Block Frequency Analysis ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Loops should be simplified before this analysis.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Analysis/BlockFrequencyInfo.h"
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/iterator.h"
16#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
17#include "llvm/Analysis/BranchProbabilityInfo.h"
18#include "llvm/Analysis/CycleAnalysis.h"
19#include "llvm/IR/CFG.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/PassManager.h"
22#include "llvm/InitializePasses.h"
23#include "llvm/Pass.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/GraphWriter.h"
26#include "llvm/Support/raw_ostream.h"
27#include <cassert>
28#include <optional>
29#include <string>
30
31using namespace llvm;
32
33#define DEBUG_TYPE "block-freq"
34
35static cl::opt<GVDAGType> ViewBlockFreqPropagationDAG(
36 "view-block-freq-propagation-dags", cl::Hidden,
37 cl::desc("Pop up a window to show a dag displaying how block "
38 "frequencies propagation through the CFG."),
39 cl::values(clEnumValN(GVDT_None, "none", "do not display graphs."),
40 clEnumValN(GVDT_Fraction, "fraction",
41 "display a graph using the "
42 "fractional block frequency representation."),
43 clEnumValN(GVDT_Integer, "integer",
44 "display a graph using the raw "
45 "integer fractional block frequency representation."),
46 clEnumValN(GVDT_Count, "count", "display a graph using the real "
47 "profile count if available.")));
48
49namespace llvm {
50cl::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(Val: 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."));
63
64// Command line option to turn on CFG dot or text dump after profile annotation.
65cl::opt<PGOViewCountsType> PGOViewCounts(
66 "pgo-view-counts", cl::Hidden,
67 cl::desc("A boolean option to show CFG dag or text 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."),
77 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
78 clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
79 clEnumValN(PGOVCT_Text, "text", "show in text.")));
80
81static cl::opt<bool> PrintBFI("print-bfi", cl::init(Val: false), cl::Hidden,
82 cl::desc("Print the block frequency info."));
83
84cl::opt<std::string>
85 PrintBFIFuncName("print-bfi-func-name", cl::Hidden,
86 cl::desc("The option to specify the name of the function "
87 "whose block frequency info is printed."));
88} // namespace llvm
89
90namespace llvm {
91
92static GVDAGType getGVDT() {
93 if (PGOViewCounts == PGOVCT_Graph)
94 return GVDT_Count;
95 return ViewBlockFreqPropagationDAG;
96}
97
98template <>
99struct GraphTraits<BlockFrequencyInfo *> {
100 using NodeRef = const BasicBlock *;
101 using ChildIteratorType = const_succ_iterator;
102 using nodes_iterator = pointer_iterator<Function::const_iterator>;
103
104 static NodeRef getEntryNode(const BlockFrequencyInfo *G) {
105 return &G->getFunction()->front();
106 }
107
108 static ChildIteratorType child_begin(const NodeRef N) {
109 return succ_begin(BB: N);
110 }
111
112 static ChildIteratorType child_end(const NodeRef N) { return succ_end(BB: N); }
113
114 static nodes_iterator nodes_begin(const BlockFrequencyInfo *G) {
115 return nodes_iterator(G->getFunction()->begin());
116 }
117
118 static nodes_iterator nodes_end(const BlockFrequencyInfo *G) {
119 return nodes_iterator(G->getFunction()->end());
120 }
121};
122
123using BFIDOTGTraitsBase =
124 BFIDOTGraphTraitsBase<BlockFrequencyInfo, BranchProbabilityInfo>;
125
126template <>
127struct DOTGraphTraits<BlockFrequencyInfo *> : public BFIDOTGTraitsBase {
128 explicit DOTGraphTraits(bool isSimple = false)
129 : BFIDOTGTraitsBase(isSimple) {}
130
131 std::string getNodeLabel(const BasicBlock *Node,
132 const BlockFrequencyInfo *Graph) {
133
134 return BFIDOTGTraitsBase::getNodeLabel(Node, Graph, GType: getGVDT());
135 }
136
137 std::string getNodeAttributes(const BasicBlock *Node,
138 const BlockFrequencyInfo *Graph) {
139 return BFIDOTGTraitsBase::getNodeAttributes(Node, Graph,
140 HotPercentThreshold: ViewHotFreqPercent);
141 }
142
143 std::string getEdgeAttributes(const BasicBlock *Node, EdgeIter EI,
144 const BlockFrequencyInfo *BFI) {
145 return BFIDOTGTraitsBase::getEdgeAttributes(Node, EI, BFI, BPI: BFI->getBPI(),
146 HotPercentThreshold: ViewHotFreqPercent);
147 }
148};
149
150} // end namespace llvm
151
152BlockFrequencyInfo::BlockFrequencyInfo() = default;
153
154BlockFrequencyInfo::BlockFrequencyInfo(const Function &F,
155 const BranchProbabilityInfo &BPI,
156 const CycleInfo &CI) {
157 calculate(F, BPI, CI);
158}
159
160BlockFrequencyInfo::BlockFrequencyInfo(BlockFrequencyInfo &&Arg)
161 : BFI(std::move(Arg.BFI)) {}
162
163BlockFrequencyInfo &BlockFrequencyInfo::operator=(BlockFrequencyInfo &&RHS) {
164 releaseMemory();
165 BFI = std::move(RHS.BFI);
166 return *this;
167}
168
169// Explicitly define the default constructor otherwise it would be implicitly
170// defined at the first ODR-use which is the BFI member in the
171// LazyBlockFrequencyInfo header. The dtor needs the BlockFrequencyInfoImpl
172// template instantiated which is not available in the header.
173BlockFrequencyInfo::~BlockFrequencyInfo() = default;
174
175bool BlockFrequencyInfo::invalidate(Function &F, const PreservedAnalyses &PA,
176 FunctionAnalysisManager::Invalidator &) {
177 // Check whether the analysis, all analyses on functions, or the function's
178 // CFG have been preserved.
179 auto PAC = PA.getChecker<BlockFrequencyAnalysis>();
180 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
181 PAC.preservedSet<CFGAnalyses>());
182}
183
184void BlockFrequencyInfo::calculate(const Function &F,
185 const BranchProbabilityInfo &BPI,
186 const CycleInfo &CI) {
187 if (!BFI)
188 BFI.reset(p: new ImplType);
189 BFI->calculate(F, BPI, CI);
190 if (ViewBlockFreqPropagationDAG != GVDT_None &&
191 (ViewBlockFreqFuncName.empty() || F.getName() == ViewBlockFreqFuncName)) {
192 view();
193 }
194 if (PrintBFI &&
195 (PrintBFIFuncName.empty() || F.getName() == PrintBFIFuncName)) {
196 print(OS&: dbgs());
197 }
198}
199
200BlockFrequency BlockFrequencyInfo::getBlockFreq(const BasicBlock *BB) const {
201 return BFI ? BFI->getBlockFreq(BB) : BlockFrequency(0);
202}
203
204std::optional<uint64_t>
205BlockFrequencyInfo::getBlockProfileCount(const BasicBlock *BB) const {
206 if (!BFI)
207 return std::nullopt;
208
209 return BFI->getBlockProfileCount(F: *getFunction(), BB);
210}
211
212std::optional<uint64_t>
213BlockFrequencyInfo::getProfileCountFromFreq(BlockFrequency Freq) const {
214 if (!BFI)
215 return std::nullopt;
216 return BFI->getProfileCountFromFreq(F: *getFunction(), Freq);
217}
218
219bool BlockFrequencyInfo::isIrrLoopHeader(const BasicBlock *BB) {
220 assert(BFI && "Expected analysis to be available");
221 return BFI->isIrrLoopHeader(BB);
222}
223
224void BlockFrequencyInfo::setBlockFreq(const BasicBlock *BB,
225 BlockFrequency Freq) {
226 assert(BFI && "Expected analysis to be available");
227 BFI->setBlockFreq(BB, Freq);
228}
229
230void BlockFrequencyInfo::setBlockFreqAndScale(
231 const BasicBlock *ReferenceBB, BlockFrequency Freq,
232 SmallPtrSetImpl<BasicBlock *> &BlocksToScale) {
233 assert(BFI && "Expected analysis to be available");
234 // Use 128 bits APInt to avoid overflow.
235 APInt NewFreq(128, Freq.getFrequency());
236 APInt OldFreq(128, BFI->getBlockFreq(BB: ReferenceBB).getFrequency());
237 APInt BBFreq(128, 0);
238 for (auto *BB : BlocksToScale) {
239 BBFreq = BFI->getBlockFreq(BB).getFrequency();
240 // Multiply first by NewFreq and then divide by OldFreq
241 // to minimize loss of precision.
242 BBFreq *= NewFreq;
243 // udiv is an expensive operation in the general case. If this ends up being
244 // a hot spot, one of the options proposed in
245 // https://reviews.llvm.org/D28535#650071 could be used to avoid this.
246 BBFreq = BBFreq.udiv(RHS: OldFreq);
247 BFI->setBlockFreq(BB, Freq: BlockFrequency(BBFreq.getLimitedValue()));
248 }
249 BFI->setBlockFreq(BB: ReferenceBB, Freq);
250}
251
252/// Pop up a ghostview window with the current block frequency propagation
253/// rendered using dot.
254void BlockFrequencyInfo::view(StringRef title) const {
255 ViewGraph(G: const_cast<BlockFrequencyInfo *>(this), Name: title);
256}
257
258const Function *BlockFrequencyInfo::getFunction() const {
259 return BFI ? BFI->getFunction() : nullptr;
260}
261
262const BranchProbabilityInfo *BlockFrequencyInfo::getBPI() const {
263 return BFI ? &BFI->getBPI() : nullptr;
264}
265
266BlockFrequency BlockFrequencyInfo::getEntryFreq() const {
267 return BFI ? BFI->getEntryFreq() : BlockFrequency(0);
268}
269
270void BlockFrequencyInfo::releaseMemory() { BFI.reset(); }
271
272void BlockFrequencyInfo::print(raw_ostream &OS) const {
273 if (BFI)
274 BFI->print(OS);
275}
276
277void BlockFrequencyInfo::verifyMatch(BlockFrequencyInfo &Other) const {
278 if (BFI)
279 BFI->verifyMatch(Other&: *Other.BFI);
280}
281
282Printable llvm::printBlockFreq(const BlockFrequencyInfo &BFI,
283 BlockFrequency Freq) {
284 return Printable([&BFI, Freq](raw_ostream &OS) {
285 printRelativeBlockFreq(OS, EntryFreq: BFI.getEntryFreq(), Freq);
286 });
287}
288
289Printable llvm::printBlockFreq(const BlockFrequencyInfo &BFI,
290 const BasicBlock &BB) {
291 return printBlockFreq(BFI, Freq: BFI.getBlockFreq(BB: &BB));
292}
293
294INITIALIZE_PASS_BEGIN(BlockFrequencyInfoWrapperPass, "block-freq",
295 "Block Frequency Analysis", true, true)
296INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
297INITIALIZE_PASS_DEPENDENCY(CycleInfoWrapperPass)
298INITIALIZE_PASS_END(BlockFrequencyInfoWrapperPass, "block-freq",
299 "Block Frequency Analysis", true, true)
300
301char BlockFrequencyInfoWrapperPass::ID = 0;
302
303BlockFrequencyInfoWrapperPass::BlockFrequencyInfoWrapperPass()
304 : FunctionPass(ID) {}
305
306BlockFrequencyInfoWrapperPass::~BlockFrequencyInfoWrapperPass() = default;
307
308void BlockFrequencyInfoWrapperPass::print(raw_ostream &OS,
309 const Module *) const {
310 BFI.print(OS);
311}
312
313void BlockFrequencyInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
314 AU.addRequired<BranchProbabilityInfoWrapperPass>();
315 AU.addRequired<CycleInfoWrapperPass>();
316 AU.setPreservesAll();
317}
318
319void BlockFrequencyInfoWrapperPass::releaseMemory() { BFI.releaseMemory(); }
320
321bool BlockFrequencyInfoWrapperPass::runOnFunction(Function &F) {
322 BranchProbabilityInfo &BPI =
323 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
324 CycleInfo &LI = getAnalysis<CycleInfoWrapperPass>().getResult();
325 BFI.calculate(F, BPI, CI: LI);
326 return false;
327}
328
329AnalysisKey BlockFrequencyAnalysis::Key;
330BlockFrequencyInfo BlockFrequencyAnalysis::run(Function &F,
331 FunctionAnalysisManager &AM) {
332 auto &BP = AM.getResult<BranchProbabilityAnalysis>(IR&: F);
333 auto &LI = AM.getResult<CycleAnalysis>(IR&: F);
334 BlockFrequencyInfo BFI;
335 BFI.calculate(F, BPI: BP, CI: LI);
336 return BFI;
337}
338
339PreservedAnalyses
340BlockFrequencyPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
341 OS << "Printing analysis results of BFI for function "
342 << "'" << F.getName() << "':"
343 << "\n";
344 AM.getResult<BlockFrequencyAnalysis>(IR&: F).print(OS);
345 return PreservedAnalyses::all();
346}
347