1 //===-- BlockFrequencyImpl.h - Block Frequency Implementation --*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Shared implementation of BlockFrequency for IR and Machine Instructions.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYIMPL_H
15 #define LLVM_ANALYSIS_BLOCKFREQUENCYIMPL_H
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/PostOrderIterator.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/Support/BlockFrequency.h"
23 #include "llvm/Support/BranchProbability.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
32 class BlockFrequencyInfo;
33 class MachineBlockFrequencyInfo;
35 /// BlockFrequencyImpl implements block frequency algorithm for IR and
36 /// Machine Instructions. Algorithm starts with value ENTRY_FREQ
37 /// for the entry block and then propagates frequencies using branch weights
38 /// from (Machine)BranchProbabilityInfo. LoopInfo is not required because
39 /// algorithm can find "backedges" by itself.
40 template<class BlockT, class FunctionT, class BlockProbInfoT>
41 class BlockFrequencyImpl {
43 DenseMap<const BlockT *, BlockFrequency> Freqs;
49 typedef GraphTraits< Inverse<BlockT *> > GT;
51 static const uint64_t EntryFreq = 1 << 14;
53 std::string getBlockName(BasicBlock *BB) const {
54 return BB->getName().str();
57 std::string getBlockName(MachineBasicBlock *MBB) const {
59 raw_string_ostream ss(str);
60 ss << "BB#" << MBB->getNumber();
62 if (const BasicBlock *BB = MBB->getBasicBlock())
63 ss << " derived from LLVM BB " << BB->getName();
68 void setBlockFreq(BlockT *BB, BlockFrequency Freq) {
70 DEBUG(dbgs() << "Frequency(" << getBlockName(BB) << ") = ";
71 printBlockFreq(dbgs(), Freq) << "\n");
74 /// getEdgeFreq - Return edge frequency based on SRC frequency and Src -> Dst
76 BlockFrequency getEdgeFreq(BlockT *Src, BlockT *Dst) const {
77 BranchProbability Prob = BPI->getEdgeProbability(Src, Dst);
78 return getBlockFreq(Src) * Prob;
81 /// incBlockFreq - Increase BB block frequency by FREQ.
83 void incBlockFreq(BlockT *BB, BlockFrequency Freq) {
85 DEBUG(dbgs() << "Frequency(" << getBlockName(BB) << ") += ";
86 printBlockFreq(dbgs(), Freq) << " --> ";
87 printBlockFreq(dbgs(), Freqs[BB]) << "\n");
90 // All blocks in postorder.
91 std::vector<BlockT *> POT;
93 // Map Block -> Position in reverse-postorder list.
94 DenseMap<BlockT *, unsigned> RPO;
96 // For each loop header, record the per-iteration probability of exiting the
97 // loop. This is the reciprocal of the expected number of loop iterations.
98 typedef DenseMap<BlockT*, BranchProbability> LoopExitProbMap;
99 LoopExitProbMap LoopExitProb;
101 // (reverse-)postorder traversal iterators.
102 typedef typename std::vector<BlockT *>::iterator pot_iterator;
103 typedef typename std::vector<BlockT *>::reverse_iterator rpot_iterator;
105 pot_iterator pot_begin() { return POT.begin(); }
106 pot_iterator pot_end() { return POT.end(); }
108 rpot_iterator rpot_begin() { return POT.rbegin(); }
109 rpot_iterator rpot_end() { return POT.rend(); }
111 rpot_iterator rpot_at(BlockT *BB) {
112 rpot_iterator I = rpot_begin();
113 unsigned idx = RPO.lookup(BB);
115 std::advance(I, idx - 1);
121 /// isBackedge - Return if edge Src -> Dst is a reachable backedge.
123 bool isBackedge(BlockT *Src, BlockT *Dst) const {
124 unsigned a = RPO.lookup(Src);
127 unsigned b = RPO.lookup(Dst);
128 assert(b && "Destination block should be reachable");
132 /// getSingleBlockPred - return single BB block predecessor or NULL if
133 /// BB has none or more predecessors.
134 BlockT *getSingleBlockPred(BlockT *BB) {
135 typename GT::ChildIteratorType
136 PI = GraphTraits< Inverse<BlockT *> >::child_begin(BB),
137 PE = GraphTraits< Inverse<BlockT *> >::child_end(BB);
151 void doBlock(BlockT *BB, BlockT *LoopHead,
152 SmallPtrSet<BlockT *, 8> &BlocksInLoop) {
154 DEBUG(dbgs() << "doBlock(" << getBlockName(BB) << ")\n");
157 if (BB == LoopHead) {
158 setBlockFreq(BB, EntryFreq);
162 if (BlockT *Pred = getSingleBlockPred(BB)) {
163 if (BlocksInLoop.count(Pred))
164 setBlockFreq(BB, getEdgeFreq(Pred, BB));
165 // TODO: else? irreducible, ignore it for now.
169 bool isInLoop = false;
170 bool isLoopHead = false;
172 for (typename GT::ChildIteratorType
173 PI = GraphTraits< Inverse<BlockT *> >::child_begin(BB),
174 PE = GraphTraits< Inverse<BlockT *> >::child_end(BB);
178 if (isBackedge(Pred, BB)) {
180 } else if (BlocksInLoop.count(Pred)) {
181 incBlockFreq(BB, getEdgeFreq(Pred, BB));
184 // TODO: else? irreducible.
193 // This block is a loop header, so boost its frequency by the expected
194 // number of loop iterations. The loop blocks will be revisited so they all
196 typename LoopExitProbMap::const_iterator I = LoopExitProb.find(BB);
197 assert(I != LoopExitProb.end() && "Loop header missing from table");
198 Freqs[BB] /= I->second;
199 DEBUG(dbgs() << "Loop header scaled to ";
200 printBlockFreq(dbgs(), Freqs[BB]) << ".\n");
203 /// doLoop - Propagate block frequency down through the loop.
204 void doLoop(BlockT *Head, BlockT *Tail) {
205 DEBUG(dbgs() << "doLoop(" << getBlockName(Head) << ", "
206 << getBlockName(Tail) << ")\n");
208 SmallPtrSet<BlockT *, 8> BlocksInLoop;
210 for (rpot_iterator I = rpot_at(Head), E = rpot_at(Tail); ; ++I) {
212 doBlock(BB, Head, BlocksInLoop);
214 BlocksInLoop.insert(BB);
219 // Compute loop's cyclic probability using backedges probabilities.
220 BlockFrequency BackFreq;
221 for (typename GT::ChildIteratorType
222 PI = GraphTraits< Inverse<BlockT *> >::child_begin(Head),
223 PE = GraphTraits< Inverse<BlockT *> >::child_end(Head);
227 if (isBackedge(Pred, Head))
228 BackFreq += getEdgeFreq(Pred, Head);
231 // The cyclic probability is freq(BackEdges) / freq(Head), where freq(Head)
232 // only counts edges entering the loop, not the loop backedges.
233 // The probability of leaving the loop on each iteration is:
235 // ExitProb = 1 - CyclicProb
237 // The Expected number of loop iterations is:
239 // Iterations = 1 / ExitProb
241 uint64_t D = std::max(getBlockFreq(Head).getFrequency(), UINT64_C(1));
242 uint64_t N = std::max(BackFreq.getFrequency(), UINT64_C(1));
246 // We'd expect N < D, but rounding and saturation means that can't be
250 // Now ExitProb = N / D, make sure it fits in an i32/i32 fraction.
252 if (D > UINT32_MAX) {
253 unsigned Shift = 32 - countLeadingZeros(D);
259 BranchProbability LEP = BranchProbability(N, D);
260 LoopExitProb.insert(std::make_pair(Head, LEP));
261 DEBUG(dbgs() << "LoopExitProb[" << getBlockName(Head) << "] = " << LEP
263 printBlockFreq(dbgs(), BackFreq) << " / ";
264 printBlockFreq(dbgs(), getBlockFreq(Head)) << ".\n");
267 friend class BlockFrequencyInfo;
268 friend class MachineBlockFrequencyInfo;
270 BlockFrequencyImpl() { }
272 void doFunction(FunctionT *fn, BlockProbInfoT *bpi) {
279 LoopExitProb.clear();
282 BlockT *EntryBlock = fn->begin();
284 std::copy(po_begin(EntryBlock), po_end(EntryBlock), std::back_inserter(POT));
287 for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
290 DEBUG(dbgs() << "RPO[" << getBlockName(BB) << "] = " << RPO[BB] << "\n");
293 // Travel over all blocks in postorder.
294 for (pot_iterator I = pot_begin(), E = pot_end(); I != E; ++I) {
296 BlockT *LastTail = 0;
297 DEBUG(dbgs() << "POT: " << getBlockName(BB) << "\n");
299 for (typename GT::ChildIteratorType
300 PI = GraphTraits< Inverse<BlockT *> >::child_begin(BB),
301 PE = GraphTraits< Inverse<BlockT *> >::child_end(BB);
305 if (isBackedge(Pred, BB) && (!LastTail || RPO[Pred] > RPO[LastTail]))
310 doLoop(BB, LastTail);
313 // At the end assume the whole function as a loop, and travel over it once
315 doLoop(*(rpot_begin()), *(pot_begin()));
320 uint64_t getEntryFreq() { return EntryFreq; }
322 /// getBlockFreq - Return block frequency. Return 0 if we don't have it.
323 BlockFrequency getBlockFreq(const BlockT *BB) const {
324 typename DenseMap<const BlockT *, BlockFrequency>::const_iterator
326 if (I != Freqs.end())
331 void print(raw_ostream &OS) const {
332 OS << "\n\n---- Block Freqs ----\n";
333 for (typename FunctionT::iterator I = Fn->begin(), E = Fn->end(); I != E;) {
335 OS << " " << getBlockName(BB) << " = ";
336 printBlockFreq(OS, getBlockFreq(BB)) << "\n";
338 for (typename GraphTraits<BlockT *>::ChildIteratorType
339 SI = GraphTraits<BlockT *>::child_begin(BB),
340 SE = GraphTraits<BlockT *>::child_end(BB); SI != SE; ++SI) {
342 OS << " " << getBlockName(BB) << " -> " << getBlockName(Succ)
343 << " = "; printBlockFreq(OS, getEdgeFreq(BB, Succ)) << "\n";
352 // Utility method that looks up the block frequency associated with BB and
354 raw_ostream &printBlockFreq(raw_ostream &OS,
356 return printBlockFreq(OS, getBlockFreq(BB));
359 raw_ostream &printBlockFreq(raw_ostream &OS,
360 const BlockFrequency &Freq) const {
361 // Convert fixed-point number to decimal.
362 uint64_t Frequency = Freq.getFrequency();
363 OS << Frequency / EntryFreq << ".";
364 uint64_t Rem = Frequency % EntryFreq;
369 OS << Rem / EntryFreq;
370 Rem = Rem % EntryFreq;
371 } while (Rem >= Eps/2);