1 //==- BlockFrequencyInfoImpl.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.
11 // See the documentation below for BlockFrequencyInfoImpl for details.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
16 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/iterator_range.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/ScaledNumber.h"
26 #include "llvm/Support/raw_ostream.h"
32 #define DEBUG_TYPE "block-freq"
37 class BranchProbabilityInfo
;
41 class MachineBasicBlock
;
42 class MachineBranchProbabilityInfo
;
43 class MachineFunction
;
45 class MachineLoopInfo
;
47 namespace bfi_detail
{
49 struct IrreducibleGraph
;
51 // This is part of a workaround for a GCC 4.7 crash on lambdas.
52 template <class BT
> struct BlockEdgesAdder
;
54 /// \brief Mass of a block.
56 /// This class implements a sort of fixed-point fraction always between 0.0 and
57 /// 1.0. getMass() == UINT64_MAX indicates a value of 1.0.
59 /// Masses can be added and subtracted. Simple saturation arithmetic is used,
60 /// so arithmetic operations never overflow or underflow.
62 /// Masses can be multiplied. Multiplication treats full mass as 1.0 and uses
63 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not
64 /// quite, maximum precision).
66 /// Masses can be scaled by \a BranchProbability at maximum precision.
71 BlockMass() : Mass(0) {}
72 explicit BlockMass(uint64_t Mass
) : Mass(Mass
) {}
74 static BlockMass
getEmpty() { return BlockMass(); }
75 static BlockMass
getFull() { return BlockMass(UINT64_MAX
); }
77 uint64_t getMass() const { return Mass
; }
79 bool isFull() const { return Mass
== UINT64_MAX
; }
80 bool isEmpty() const { return !Mass
; }
82 bool operator!() const { return isEmpty(); }
84 /// \brief Add another mass.
86 /// Adds another mass, saturating at \a isFull() rather than overflowing.
87 BlockMass
&operator+=(const BlockMass
&X
) {
88 uint64_t Sum
= Mass
+ X
.Mass
;
89 Mass
= Sum
< Mass
? UINT64_MAX
: Sum
;
93 /// \brief Subtract another mass.
95 /// Subtracts another mass, saturating at \a isEmpty() rather than
97 BlockMass
&operator-=(const BlockMass
&X
) {
98 uint64_t Diff
= Mass
- X
.Mass
;
99 Mass
= Diff
> Mass
? 0 : Diff
;
103 BlockMass
&operator*=(const BranchProbability
&P
) {
104 Mass
= P
.scale(Mass
);
108 bool operator==(const BlockMass
&X
) const { return Mass
== X
.Mass
; }
109 bool operator!=(const BlockMass
&X
) const { return Mass
!= X
.Mass
; }
110 bool operator<=(const BlockMass
&X
) const { return Mass
<= X
.Mass
; }
111 bool operator>=(const BlockMass
&X
) const { return Mass
>= X
.Mass
; }
112 bool operator<(const BlockMass
&X
) const { return Mass
< X
.Mass
; }
113 bool operator>(const BlockMass
&X
) const { return Mass
> X
.Mass
; }
115 /// \brief Convert to scaled number.
117 /// Convert to \a ScaledNumber. \a isFull() gives 1.0, while \a isEmpty()
118 /// gives slightly above 0.0.
119 ScaledNumber
<uint64_t> toScaled() const;
122 raw_ostream
&print(raw_ostream
&OS
) const;
125 inline BlockMass
operator+(const BlockMass
&L
, const BlockMass
&R
) {
126 return BlockMass(L
) += R
;
128 inline BlockMass
operator-(const BlockMass
&L
, const BlockMass
&R
) {
129 return BlockMass(L
) -= R
;
131 inline BlockMass
operator*(const BlockMass
&L
, const BranchProbability
&R
) {
132 return BlockMass(L
) *= R
;
134 inline BlockMass
operator*(const BranchProbability
&L
, const BlockMass
&R
) {
135 return BlockMass(R
) *= L
;
138 inline raw_ostream
&operator<<(raw_ostream
&OS
, const BlockMass
&X
) {
142 } // end namespace bfi_detail
144 template <> struct isPodLike
<bfi_detail::BlockMass
> {
145 static const bool value
= true;
148 /// \brief Base class for BlockFrequencyInfoImpl
150 /// BlockFrequencyInfoImplBase has supporting data structures and some
151 /// algorithms for BlockFrequencyInfoImplBase. Only algorithms that depend on
152 /// the block type (or that call such algorithms) are skipped here.
154 /// Nevertheless, the majority of the overall algorithm documention lives with
155 /// BlockFrequencyInfoImpl. See there for details.
156 class BlockFrequencyInfoImplBase
{
158 typedef ScaledNumber
<uint64_t> Scaled64
;
159 typedef bfi_detail::BlockMass BlockMass
;
161 /// \brief Representative of a block.
163 /// This is a simple wrapper around an index into the reverse-post-order
164 /// traversal of the blocks.
166 /// Unlike a block pointer, its order has meaning (location in the
167 /// topological sort) and it's class is the same regardless of block type.
169 typedef uint32_t IndexType
;
172 bool operator==(const BlockNode
&X
) const { return Index
== X
.Index
; }
173 bool operator!=(const BlockNode
&X
) const { return Index
!= X
.Index
; }
174 bool operator<=(const BlockNode
&X
) const { return Index
<= X
.Index
; }
175 bool operator>=(const BlockNode
&X
) const { return Index
>= X
.Index
; }
176 bool operator<(const BlockNode
&X
) const { return Index
< X
.Index
; }
177 bool operator>(const BlockNode
&X
) const { return Index
> X
.Index
; }
179 BlockNode() : Index(UINT32_MAX
) {}
180 BlockNode(IndexType Index
) : Index(Index
) {}
182 bool isValid() const { return Index
<= getMaxIndex(); }
183 static size_t getMaxIndex() { return UINT32_MAX
- 1; }
186 /// \brief Stats about a block itself.
187 struct FrequencyData
{
192 /// \brief Data about a loop.
194 /// Contains the data necessary to represent represent a loop as a
195 /// pseudo-node once it's packaged.
197 typedef SmallVector
<std::pair
<BlockNode
, BlockMass
>, 4> ExitMap
;
198 typedef SmallVector
<BlockNode
, 4> NodeList
;
199 LoopData
*Parent
; ///< The parent loop.
200 bool IsPackaged
; ///< Whether this has been packaged.
201 uint32_t NumHeaders
; ///< Number of headers.
202 ExitMap Exits
; ///< Successor edges (and weights).
203 NodeList Nodes
; ///< Header and the members of the loop.
204 BlockMass BackedgeMass
; ///< Mass returned to loop header.
208 LoopData(LoopData
*Parent
, const BlockNode
&Header
)
209 : Parent(Parent
), IsPackaged(false), NumHeaders(1), Nodes(1, Header
) {}
210 template <class It1
, class It2
>
211 LoopData(LoopData
*Parent
, It1 FirstHeader
, It1 LastHeader
, It2 FirstOther
,
213 : Parent(Parent
), IsPackaged(false), Nodes(FirstHeader
, LastHeader
) {
214 NumHeaders
= Nodes
.size();
215 Nodes
.insert(Nodes
.end(), FirstOther
, LastOther
);
217 bool isHeader(const BlockNode
&Node
) const {
219 return std::binary_search(Nodes
.begin(), Nodes
.begin() + NumHeaders
,
221 return Node
== Nodes
[0];
223 BlockNode
getHeader() const { return Nodes
[0]; }
224 bool isIrreducible() const { return NumHeaders
> 1; }
226 NodeList::const_iterator
members_begin() const {
227 return Nodes
.begin() + NumHeaders
;
229 NodeList::const_iterator
members_end() const { return Nodes
.end(); }
230 iterator_range
<NodeList::const_iterator
> members() const {
231 return make_range(members_begin(), members_end());
235 /// \brief Index of loop information.
237 BlockNode Node
; ///< This node.
238 LoopData
*Loop
; ///< The loop this block is inside.
239 BlockMass Mass
; ///< Mass distribution from the entry block.
241 WorkingData(const BlockNode
&Node
) : Node(Node
), Loop(nullptr) {}
243 bool isLoopHeader() const { return Loop
&& Loop
->isHeader(Node
); }
244 bool isDoubleLoopHeader() const {
245 return isLoopHeader() && Loop
->Parent
&& Loop
->Parent
->isIrreducible() &&
246 Loop
->Parent
->isHeader(Node
);
249 LoopData
*getContainingLoop() const {
252 if (!isDoubleLoopHeader())
254 return Loop
->Parent
->Parent
;
257 /// \brief Resolve a node to its representative.
259 /// Get the node currently representing Node, which could be a containing
262 /// This function should only be called when distributing mass. As long as
263 /// there are no irreducilbe edges to Node, then it will have complexity
264 /// O(1) in this context.
266 /// In general, the complexity is O(L), where L is the number of loop
267 /// headers Node has been packaged into. Since this method is called in
268 /// the context of distributing mass, L will be the number of loop headers
269 /// an early exit edge jumps out of.
270 BlockNode
getResolvedNode() const {
271 auto L
= getPackagedLoop();
272 return L
? L
->getHeader() : Node
;
274 LoopData
*getPackagedLoop() const {
275 if (!Loop
|| !Loop
->IsPackaged
)
278 while (L
->Parent
&& L
->Parent
->IsPackaged
)
283 /// \brief Get the appropriate mass for a node.
285 /// Get appropriate mass for Node. If Node is a loop-header (whose loop
286 /// has been packaged), returns the mass of its pseudo-node. If it's a
287 /// node inside a packaged loop, it returns the loop's mass.
288 BlockMass
&getMass() {
291 if (!isADoublePackage())
293 return Loop
->Parent
->Mass
;
296 /// \brief Has ContainingLoop been packaged up?
297 bool isPackaged() const { return getResolvedNode() != Node
; }
298 /// \brief Has Loop been packaged up?
299 bool isAPackage() const { return isLoopHeader() && Loop
->IsPackaged
; }
300 /// \brief Has Loop been packaged up twice?
301 bool isADoublePackage() const {
302 return isDoubleLoopHeader() && Loop
->Parent
->IsPackaged
;
306 /// \brief Unscaled probability weight.
308 /// Probability weight for an edge in the graph (including the
309 /// successor/target node).
311 /// All edges in the original function are 32-bit. However, exit edges from
312 /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
313 /// space in general.
315 /// In addition to the raw weight amount, Weight stores the type of the edge
316 /// in the current context (i.e., the context of the loop being processed).
317 /// Is this a local edge within the loop, an exit from the loop, or a
318 /// backedge to the loop header?
320 enum DistType
{ Local
, Exit
, Backedge
};
322 BlockNode TargetNode
;
324 Weight() : Type(Local
), Amount(0) {}
325 Weight(DistType Type
, BlockNode TargetNode
, uint64_t Amount
)
326 : Type(Type
), TargetNode(TargetNode
), Amount(Amount
) {}
329 /// \brief Distribution of unscaled probability weight.
331 /// Distribution of unscaled probability weight to a set of successors.
333 /// This class collates the successor edge weights for later processing.
335 /// \a DidOverflow indicates whether \a Total did overflow while adding to
336 /// the distribution. It should never overflow twice.
337 struct Distribution
{
338 typedef SmallVector
<Weight
, 4> WeightList
;
339 WeightList Weights
; ///< Individual successor weights.
340 uint64_t Total
; ///< Sum of all weights.
341 bool DidOverflow
; ///< Whether \a Total did overflow.
343 Distribution() : Total(0), DidOverflow(false) {}
344 void addLocal(const BlockNode
&Node
, uint64_t Amount
) {
345 add(Node
, Amount
, Weight::Local
);
347 void addExit(const BlockNode
&Node
, uint64_t Amount
) {
348 add(Node
, Amount
, Weight::Exit
);
350 void addBackedge(const BlockNode
&Node
, uint64_t Amount
) {
351 add(Node
, Amount
, Weight::Backedge
);
354 /// \brief Normalize the distribution.
356 /// Combines multiple edges to the same \a Weight::TargetNode and scales
357 /// down so that \a Total fits into 32-bits.
359 /// This is linear in the size of \a Weights. For the vast majority of
360 /// cases, adjacent edge weights are combined by sorting WeightList and
361 /// combining adjacent weights. However, for very large edge lists an
362 /// auxiliary hash table is used.
366 void add(const BlockNode
&Node
, uint64_t Amount
, Weight::DistType Type
);
369 /// \brief Data about each block. This is used downstream.
370 std::vector
<FrequencyData
> Freqs
;
372 /// \brief Loop data: see initializeLoops().
373 std::vector
<WorkingData
> Working
;
375 /// \brief Indexed information about loops.
376 std::list
<LoopData
> Loops
;
378 /// \brief Add all edges out of a packaged loop to the distribution.
380 /// Adds all edges from LocalLoopHead to Dist. Calls addToDist() to add each
383 /// \return \c true unless there's an irreducible backedge.
384 bool addLoopSuccessorsToDist(const LoopData
*OuterLoop
, LoopData
&Loop
,
387 /// \brief Add an edge to the distribution.
389 /// Adds an edge to Succ to Dist. If \c LoopHead.isValid(), then whether the
390 /// edge is local/exit/backedge is in the context of LoopHead. Otherwise,
391 /// every edge should be a local edge (since all the loops are packaged up).
393 /// \return \c true unless aborted due to an irreducible backedge.
394 bool addToDist(Distribution
&Dist
, const LoopData
*OuterLoop
,
395 const BlockNode
&Pred
, const BlockNode
&Succ
, uint64_t Weight
);
397 LoopData
&getLoopPackage(const BlockNode
&Head
) {
398 assert(Head
.Index
< Working
.size());
399 assert(Working
[Head
.Index
].isLoopHeader());
400 return *Working
[Head
.Index
].Loop
;
403 /// \brief Analyze irreducible SCCs.
405 /// Separate irreducible SCCs from \c G, which is an explict graph of \c
406 /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr).
407 /// Insert them into \a Loops before \c Insert.
409 /// \return the \c LoopData nodes representing the irreducible SCCs.
410 iterator_range
<std::list
<LoopData
>::iterator
>
411 analyzeIrreducible(const bfi_detail::IrreducibleGraph
&G
, LoopData
*OuterLoop
,
412 std::list
<LoopData
>::iterator Insert
);
414 /// \brief Update a loop after packaging irreducible SCCs inside of it.
416 /// Update \c OuterLoop. Before finding irreducible control flow, it was
417 /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a
418 /// LoopData::BackedgeMass need to be reset. Also, nodes that were packaged
419 /// up need to be removed from \a OuterLoop::Nodes.
420 void updateLoopWithIrreducible(LoopData
&OuterLoop
);
422 /// \brief Distribute mass according to a distribution.
424 /// Distributes the mass in Source according to Dist. If LoopHead.isValid(),
425 /// backedges and exits are stored in its entry in Loops.
427 /// Mass is distributed in parallel from two copies of the source mass.
428 void distributeMass(const BlockNode
&Source
, LoopData
*OuterLoop
,
431 /// \brief Compute the loop scale for a loop.
432 void computeLoopScale(LoopData
&Loop
);
434 /// \brief Package up a loop.
435 void packageLoop(LoopData
&Loop
);
437 /// \brief Unwrap loops.
440 /// \brief Finalize frequency metrics.
442 /// Calculates final frequencies and cleans up no-longer-needed data
444 void finalizeMetrics();
446 /// \brief Clear all memory.
449 virtual std::string
getBlockName(const BlockNode
&Node
) const;
450 std::string
getLoopName(const LoopData
&Loop
) const;
452 virtual raw_ostream
&print(raw_ostream
&OS
) const { return OS
; }
453 void dump() const { print(dbgs()); }
455 Scaled64
getFloatingBlockFreq(const BlockNode
&Node
) const;
457 BlockFrequency
getBlockFreq(const BlockNode
&Node
) const;
459 raw_ostream
&printBlockFreq(raw_ostream
&OS
, const BlockNode
&Node
) const;
460 raw_ostream
&printBlockFreq(raw_ostream
&OS
,
461 const BlockFrequency
&Freq
) const;
463 uint64_t getEntryFreq() const {
464 assert(!Freqs
.empty());
465 return Freqs
[0].Integer
;
467 /// \brief Virtual destructor.
469 /// Need a virtual destructor to mask the compiler warning about
471 virtual ~BlockFrequencyInfoImplBase() {}
474 namespace bfi_detail
{
475 template <class BlockT
> struct TypeMap
{};
476 template <> struct TypeMap
<BasicBlock
> {
477 typedef BasicBlock BlockT
;
478 typedef Function FunctionT
;
479 typedef BranchProbabilityInfo BranchProbabilityInfoT
;
481 typedef LoopInfo LoopInfoT
;
483 template <> struct TypeMap
<MachineBasicBlock
> {
484 typedef MachineBasicBlock BlockT
;
485 typedef MachineFunction FunctionT
;
486 typedef MachineBranchProbabilityInfo BranchProbabilityInfoT
;
487 typedef MachineLoop LoopT
;
488 typedef MachineLoopInfo LoopInfoT
;
491 /// \brief Get the name of a MachineBasicBlock.
493 /// Get the name of a MachineBasicBlock. It's templated so that including from
494 /// CodeGen is unnecessary (that would be a layering issue).
496 /// This is used mainly for debug output. The name is similar to
497 /// MachineBasicBlock::getFullName(), but skips the name of the function.
498 template <class BlockT
> std::string
getBlockName(const BlockT
*BB
) {
499 assert(BB
&& "Unexpected nullptr");
500 auto MachineName
= "BB" + Twine(BB
->getNumber());
501 if (BB
->getBasicBlock())
502 return (MachineName
+ "[" + BB
->getName() + "]").str();
503 return MachineName
.str();
505 /// \brief Get the name of a BasicBlock.
506 template <> inline std::string
getBlockName(const BasicBlock
*BB
) {
507 assert(BB
&& "Unexpected nullptr");
508 return BB
->getName().str();
511 /// \brief Graph of irreducible control flow.
513 /// This graph is used for determining the SCCs in a loop (or top-level
514 /// function) that has irreducible control flow.
516 /// During the block frequency algorithm, the local graphs are defined in a
517 /// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock
518 /// graphs for most edges, but getting others from \a LoopData::ExitMap. The
519 /// latter only has successor information.
521 /// \a IrreducibleGraph makes this graph explicit. It's in a form that can use
522 /// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator),
523 /// and it explicitly lists predecessors and successors. The initialization
524 /// that relies on \c MachineBasicBlock is defined in the header.
525 struct IrreducibleGraph
{
526 typedef BlockFrequencyInfoImplBase BFIBase
;
530 typedef BFIBase::BlockNode BlockNode
;
534 std::deque
<const IrrNode
*> Edges
;
535 IrrNode(const BlockNode
&Node
) : Node(Node
), NumIn(0) {}
537 typedef std::deque
<const IrrNode
*>::const_iterator iterator
;
538 iterator
pred_begin() const { return Edges
.begin(); }
539 iterator
succ_begin() const { return Edges
.begin() + NumIn
; }
540 iterator
pred_end() const { return succ_begin(); }
541 iterator
succ_end() const { return Edges
.end(); }
544 const IrrNode
*StartIrr
;
545 std::vector
<IrrNode
> Nodes
;
546 SmallDenseMap
<uint32_t, IrrNode
*, 4> Lookup
;
548 /// \brief Construct an explicit graph containing irreducible control flow.
550 /// Construct an explicit graph of the control flow in \c OuterLoop (or the
551 /// top-level function, if \c OuterLoop is \c nullptr). Uses \c
552 /// addBlockEdges to add block successors that have not been packaged into
555 /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected
557 template <class BlockEdgesAdder
>
558 IrreducibleGraph(BFIBase
&BFI
, const BFIBase::LoopData
*OuterLoop
,
559 BlockEdgesAdder addBlockEdges
)
560 : BFI(BFI
), StartIrr(nullptr) {
561 initialize(OuterLoop
, addBlockEdges
);
564 template <class BlockEdgesAdder
>
565 void initialize(const BFIBase::LoopData
*OuterLoop
,
566 BlockEdgesAdder addBlockEdges
);
567 void addNodesInLoop(const BFIBase::LoopData
&OuterLoop
);
568 void addNodesInFunction();
569 void addNode(const BlockNode
&Node
) {
570 Nodes
.emplace_back(Node
);
571 BFI
.Working
[Node
.Index
].getMass() = BlockMass::getEmpty();
574 template <class BlockEdgesAdder
>
575 void addEdges(const BlockNode
&Node
, const BFIBase::LoopData
*OuterLoop
,
576 BlockEdgesAdder addBlockEdges
);
577 void addEdge(IrrNode
&Irr
, const BlockNode
&Succ
,
578 const BFIBase::LoopData
*OuterLoop
);
580 template <class BlockEdgesAdder
>
581 void IrreducibleGraph::initialize(const BFIBase::LoopData
*OuterLoop
,
582 BlockEdgesAdder addBlockEdges
) {
584 addNodesInLoop(*OuterLoop
);
585 for (auto N
: OuterLoop
->Nodes
)
586 addEdges(N
, OuterLoop
, addBlockEdges
);
588 addNodesInFunction();
589 for (uint32_t Index
= 0; Index
< BFI
.Working
.size(); ++Index
)
590 addEdges(Index
, OuterLoop
, addBlockEdges
);
592 StartIrr
= Lookup
[Start
.Index
];
594 template <class BlockEdgesAdder
>
595 void IrreducibleGraph::addEdges(const BlockNode
&Node
,
596 const BFIBase::LoopData
*OuterLoop
,
597 BlockEdgesAdder addBlockEdges
) {
598 auto L
= Lookup
.find(Node
.Index
);
599 if (L
== Lookup
.end())
601 IrrNode
&Irr
= *L
->second
;
602 const auto &Working
= BFI
.Working
[Node
.Index
];
604 if (Working
.isAPackage())
605 for (const auto &I
: Working
.Loop
->Exits
)
606 addEdge(Irr
, I
.first
, OuterLoop
);
608 addBlockEdges(*this, Irr
, OuterLoop
);
612 /// \brief Shared implementation for block frequency analysis.
614 /// This is a shared implementation of BlockFrequencyInfo and
615 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
618 /// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block,
619 /// which is called the header. A given loop, L, can have sub-loops, which are
620 /// loops within the subgraph of L that exclude its header. (A "trivial" SCC
621 /// consists of a single block that does not have a self-edge.)
623 /// In addition to loops, this algorithm has limited support for irreducible
624 /// SCCs, which are SCCs with multiple entry blocks. Irreducible SCCs are
625 /// discovered on they fly, and modelled as loops with multiple headers.
627 /// The headers of irreducible sub-SCCs consist of its entry blocks and all
628 /// nodes that are targets of a backedge within it (excluding backedges within
629 /// true sub-loops). Block frequency calculations act as if a block is
630 /// inserted that intercepts all the edges to the headers. All backedges and
631 /// entries point to this block. Its successors are the headers, which split
632 /// the frequency evenly.
634 /// This algorithm leverages BlockMass and ScaledNumber to maintain precision,
635 /// separates mass distribution from loop scaling, and dithers to eliminate
636 /// probability mass loss.
638 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
639 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
640 /// BlockFrequencyInfoImplBase, which doesn't. The base class uses \a
641 /// BlockNode, a wrapper around a uint32_t. BlockNode is numbered from 0 in
642 /// reverse-post order. This gives two advantages: it's easy to compare the
643 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
646 /// This algorithm is O(V+E), unless there is irreducible control flow, in
647 /// which case it's O(V*E) in the worst case.
649 /// These are the main stages:
651 /// 0. Reverse post-order traversal (\a initializeRPOT()).
653 /// Run a single post-order traversal and save it (in reverse) in RPOT.
654 /// All other stages make use of this ordering. Save a lookup from BlockT
655 /// to BlockNode (the index into RPOT) in Nodes.
657 /// 1. Loop initialization (\a initializeLoops()).
659 /// Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
660 /// the algorithm. In particular, store the immediate members of each loop
661 /// in reverse post-order.
663 /// 2. Calculate mass and scale in loops (\a computeMassInLoops()).
665 /// For each loop (bottom-up), distribute mass through the DAG resulting
666 /// from ignoring backedges and treating sub-loops as a single pseudo-node.
667 /// Track the backedge mass distributed to the loop header, and use it to
668 /// calculate the loop scale (number of loop iterations). Immediate
669 /// members that represent sub-loops will already have been visited and
670 /// packaged into a pseudo-node.
672 /// Distributing mass in a loop is a reverse-post-order traversal through
673 /// the loop. Start by assigning full mass to the Loop header. For each
674 /// node in the loop:
676 /// - Fetch and categorize the weight distribution for its successors.
677 /// If this is a packaged-subloop, the weight distribution is stored
678 /// in \a LoopData::Exits. Otherwise, fetch it from
679 /// BranchProbabilityInfo.
681 /// - Each successor is categorized as \a Weight::Local, a local edge
682 /// within the current loop, \a Weight::Backedge, a backedge to the
683 /// loop header, or \a Weight::Exit, any successor outside the loop.
684 /// The weight, the successor, and its category are stored in \a
685 /// Distribution. There can be multiple edges to each successor.
687 /// - If there's a backedge to a non-header, there's an irreducible SCC.
688 /// The usual flow is temporarily aborted. \a
689 /// computeIrreducibleMass() finds the irreducible SCCs within the
690 /// loop, packages them up, and restarts the flow.
692 /// - Normalize the distribution: scale weights down so that their sum
693 /// is 32-bits, and coalesce multiple edges to the same node.
695 /// - Distribute the mass accordingly, dithering to minimize mass loss,
696 /// as described in \a distributeMass().
698 /// Finally, calculate the loop scale from the accumulated backedge mass.
700 /// 3. Distribute mass in the function (\a computeMassInFunction()).
702 /// Finally, distribute mass through the DAG resulting from packaging all
703 /// loops in the function. This uses the same algorithm as distributing
704 /// mass in a loop, except that there are no exit or backedge edges.
706 /// 4. Unpackage loops (\a unwrapLoops()).
708 /// Initialize each block's frequency to a floating point representation of
711 /// Visit loops top-down, scaling the frequencies of its immediate members
712 /// by the loop's pseudo-node's frequency.
714 /// 5. Convert frequencies to a 64-bit range (\a finalizeMetrics()).
716 /// Using the min and max frequencies as a guide, translate floating point
717 /// frequencies to an appropriate range in uint64_t.
719 /// It has some known flaws.
721 /// - Loop scale is limited to 4096 per loop (2^12) to avoid exhausting
722 /// BlockFrequency's 64-bit integer precision.
724 /// - The model of irreducible control flow is a rough approximation.
726 /// Modelling irreducible control flow exactly involves setting up and
727 /// solving a group of infinite geometric series. Such precision is
728 /// unlikely to be worthwhile, since most of our algorithms give up on
729 /// irreducible control flow anyway.
731 /// Nevertheless, we might find that we need to get closer. Here's a sort
732 /// of TODO list for the model with diminishing returns, to be completed as
735 /// - The headers for the \a LoopData representing an irreducible SCC
736 /// include non-entry blocks. When these extra blocks exist, they
737 /// indicate a self-contained irreducible sub-SCC. We could treat them
738 /// as sub-loops, rather than arbitrarily shoving the problematic
739 /// blocks into the headers of the main irreducible SCC.
741 /// - Backedge frequencies are assumed to be evenly split between the
742 /// headers of a given irreducible SCC. Instead, we could track the
743 /// backedge mass separately for each header, and adjust their relative
746 /// - Entry frequencies are assumed to be evenly split between the
747 /// headers of a given irreducible SCC, which is the only option if we
748 /// need to compute mass in the SCC before its parent loop. Instead,
749 /// we could partially compute mass in the parent loop, and stop when
750 /// we get to the SCC. Here, we have the correct ratio of entry
751 /// masses, which we can use to adjust their relative frequencies.
752 /// Compute mass in the SCC, and then continue propagation in the
755 /// - We can propagate mass iteratively through the SCC, for some fixed
756 /// number of iterations. Each iteration starts by assigning the entry
757 /// blocks their backedge mass from the prior iteration. The final
758 /// mass for each block (and each exit, and the total backedge mass
759 /// used for computing loop scale) is the sum of all iterations.
760 /// (Running this until fixed point would "solve" the geometric
761 /// series by simulation.)
762 template <class BT
> class BlockFrequencyInfoImpl
: BlockFrequencyInfoImplBase
{
763 typedef typename
bfi_detail::TypeMap
<BT
>::BlockT BlockT
;
764 typedef typename
bfi_detail::TypeMap
<BT
>::FunctionT FunctionT
;
765 typedef typename
bfi_detail::TypeMap
<BT
>::BranchProbabilityInfoT
766 BranchProbabilityInfoT
;
767 typedef typename
bfi_detail::TypeMap
<BT
>::LoopT LoopT
;
768 typedef typename
bfi_detail::TypeMap
<BT
>::LoopInfoT LoopInfoT
;
770 // This is part of a workaround for a GCC 4.7 crash on lambdas.
771 friend struct bfi_detail::BlockEdgesAdder
<BT
>;
773 typedef GraphTraits
<const BlockT
*> Successor
;
774 typedef GraphTraits
<Inverse
<const BlockT
*>> Predecessor
;
776 const BranchProbabilityInfoT
*BPI
;
780 // All blocks in reverse postorder.
781 std::vector
<const BlockT
*> RPOT
;
782 DenseMap
<const BlockT
*, BlockNode
> Nodes
;
784 typedef typename
std::vector
<const BlockT
*>::const_iterator rpot_iterator
;
786 rpot_iterator
rpot_begin() const { return RPOT
.begin(); }
787 rpot_iterator
rpot_end() const { return RPOT
.end(); }
789 size_t getIndex(const rpot_iterator
&I
) const { return I
- rpot_begin(); }
791 BlockNode
getNode(const rpot_iterator
&I
) const {
792 return BlockNode(getIndex(I
));
794 BlockNode
getNode(const BlockT
*BB
) const { return Nodes
.lookup(BB
); }
796 const BlockT
*getBlock(const BlockNode
&Node
) const {
797 assert(Node
.Index
< RPOT
.size());
798 return RPOT
[Node
.Index
];
801 /// \brief Run (and save) a post-order traversal.
803 /// Saves a reverse post-order traversal of all the nodes in \a F.
804 void initializeRPOT();
806 /// \brief Initialize loop data.
808 /// Build up \a Loops using \a LoopInfo. \a LoopInfo gives us a mapping from
809 /// each block to the deepest loop it's in, but we need the inverse. For each
810 /// loop, we store in reverse post-order its "immediate" members, defined as
811 /// the header, the headers of immediate sub-loops, and all other blocks in
812 /// the loop that are not in sub-loops.
813 void initializeLoops();
815 /// \brief Propagate to a block's successors.
817 /// In the context of distributing mass through \c OuterLoop, divide the mass
818 /// currently assigned to \c Node between its successors.
820 /// \return \c true unless there's an irreducible backedge.
821 bool propagateMassToSuccessors(LoopData
*OuterLoop
, const BlockNode
&Node
);
823 /// \brief Compute mass in a particular loop.
825 /// Assign mass to \c Loop's header, and then for each block in \c Loop in
826 /// reverse post-order, distribute mass to its successors. Only visits nodes
827 /// that have not been packaged into sub-loops.
829 /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
830 /// \return \c true unless there's an irreducible backedge.
831 bool computeMassInLoop(LoopData
&Loop
);
833 /// \brief Try to compute mass in the top-level function.
835 /// Assign mass to the entry block, and then for each block in reverse
836 /// post-order, distribute mass to its successors. Skips nodes that have
837 /// been packaged into loops.
839 /// \pre \a computeMassInLoops() has been called.
840 /// \return \c true unless there's an irreducible backedge.
841 bool tryToComputeMassInFunction();
843 /// \brief Compute mass in (and package up) irreducible SCCs.
845 /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front
846 /// of \c Insert), and call \a computeMassInLoop() on each of them.
848 /// If \c OuterLoop is \c nullptr, it refers to the top-level function.
850 /// \pre \a computeMassInLoop() has been called for each subloop of \c
852 /// \pre \c Insert points at the the last loop successfully processed by \a
853 /// computeMassInLoop().
854 /// \pre \c OuterLoop has irreducible SCCs.
855 void computeIrreducibleMass(LoopData
*OuterLoop
,
856 std::list
<LoopData
>::iterator Insert
);
858 /// \brief Compute mass in all loops.
860 /// For each loop bottom-up, call \a computeMassInLoop().
862 /// \a computeMassInLoop() aborts (and returns \c false) on loops that
863 /// contain a irreducible sub-SCCs. Use \a computeIrreducibleMass() and then
864 /// re-enter \a computeMassInLoop().
866 /// \post \a computeMassInLoop() has returned \c true for every loop.
867 void computeMassInLoops();
869 /// \brief Compute mass in the top-level function.
871 /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to
872 /// compute mass in the top-level function.
874 /// \post \a tryToComputeMassInFunction() has returned \c true.
875 void computeMassInFunction();
877 std::string
getBlockName(const BlockNode
&Node
) const override
{
878 return bfi_detail::getBlockName(getBlock(Node
));
882 const FunctionT
*getFunction() const { return F
; }
884 void doFunction(const FunctionT
*F
, const BranchProbabilityInfoT
*BPI
,
885 const LoopInfoT
*LI
);
886 BlockFrequencyInfoImpl() : BPI(nullptr), LI(nullptr), F(nullptr) {}
888 using BlockFrequencyInfoImplBase::getEntryFreq
;
889 BlockFrequency
getBlockFreq(const BlockT
*BB
) const {
890 return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB
));
892 Scaled64
getFloatingBlockFreq(const BlockT
*BB
) const {
893 return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB
));
896 /// \brief Print the frequencies for the current function.
898 /// Prints the frequencies for the blocks in the current function.
900 /// Blocks are printed in the natural iteration order of the function, rather
901 /// than reverse post-order. This provides two advantages: writing -analyze
902 /// tests is easier (since blocks come out in source order), and even
903 /// unreachable blocks are printed.
905 /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
906 /// we need to override it here.
907 raw_ostream
&print(raw_ostream
&OS
) const override
;
908 using BlockFrequencyInfoImplBase::dump
;
910 using BlockFrequencyInfoImplBase::printBlockFreq
;
911 raw_ostream
&printBlockFreq(raw_ostream
&OS
, const BlockT
*BB
) const {
912 return BlockFrequencyInfoImplBase::printBlockFreq(OS
, getNode(BB
));
917 void BlockFrequencyInfoImpl
<BT
>::doFunction(const FunctionT
*F
,
918 const BranchProbabilityInfoT
*BPI
,
919 const LoopInfoT
*LI
) {
920 // Save the parameters.
925 // Clean up left-over data structures.
926 BlockFrequencyInfoImplBase::clear();
931 DEBUG(dbgs() << "\nblock-frequency: " << F
->getName() << "\n================="
932 << std::string(F
->getName().size(), '=') << "\n");
936 // Visit loops in post-order to find thelocal mass distribution, and then do
937 // the full function.
938 computeMassInLoops();
939 computeMassInFunction();
944 template <class BT
> void BlockFrequencyInfoImpl
<BT
>::initializeRPOT() {
945 const BlockT
*Entry
= F
->begin();
946 RPOT
.reserve(F
->size());
947 std::copy(po_begin(Entry
), po_end(Entry
), std::back_inserter(RPOT
));
948 std::reverse(RPOT
.begin(), RPOT
.end());
950 assert(RPOT
.size() - 1 <= BlockNode::getMaxIndex() &&
951 "More nodes in function than Block Frequency Info supports");
953 DEBUG(dbgs() << "reverse-post-order-traversal\n");
954 for (rpot_iterator I
= rpot_begin(), E
= rpot_end(); I
!= E
; ++I
) {
955 BlockNode Node
= getNode(I
);
956 DEBUG(dbgs() << " - " << getIndex(I
) << ": " << getBlockName(Node
) << "\n");
960 Working
.reserve(RPOT
.size());
961 for (size_t Index
= 0; Index
< RPOT
.size(); ++Index
)
962 Working
.emplace_back(Index
);
963 Freqs
.resize(RPOT
.size());
966 template <class BT
> void BlockFrequencyInfoImpl
<BT
>::initializeLoops() {
967 DEBUG(dbgs() << "loop-detection\n");
971 // Visit loops top down and assign them an index.
972 std::deque
<std::pair
<const LoopT
*, LoopData
*>> Q
;
973 for (const LoopT
*L
: *LI
)
974 Q
.emplace_back(L
, nullptr);
976 const LoopT
*Loop
= Q
.front().first
;
977 LoopData
*Parent
= Q
.front().second
;
980 BlockNode Header
= getNode(Loop
->getHeader());
981 assert(Header
.isValid());
983 Loops
.emplace_back(Parent
, Header
);
984 Working
[Header
.Index
].Loop
= &Loops
.back();
985 DEBUG(dbgs() << " - loop = " << getBlockName(Header
) << "\n");
987 for (const LoopT
*L
: *Loop
)
988 Q
.emplace_back(L
, &Loops
.back());
991 // Visit nodes in reverse post-order and add them to their deepest containing
993 for (size_t Index
= 0; Index
< RPOT
.size(); ++Index
) {
994 // Loop headers have already been mostly mapped.
995 if (Working
[Index
].isLoopHeader()) {
996 LoopData
*ContainingLoop
= Working
[Index
].getContainingLoop();
998 ContainingLoop
->Nodes
.push_back(Index
);
1002 const LoopT
*Loop
= LI
->getLoopFor(RPOT
[Index
]);
1006 // Add this node to its containing loop's member list.
1007 BlockNode Header
= getNode(Loop
->getHeader());
1008 assert(Header
.isValid());
1009 const auto &HeaderData
= Working
[Header
.Index
];
1010 assert(HeaderData
.isLoopHeader());
1012 Working
[Index
].Loop
= HeaderData
.Loop
;
1013 HeaderData
.Loop
->Nodes
.push_back(Index
);
1014 DEBUG(dbgs() << " - loop = " << getBlockName(Header
)
1015 << ": member = " << getBlockName(Index
) << "\n");
1019 template <class BT
> void BlockFrequencyInfoImpl
<BT
>::computeMassInLoops() {
1020 // Visit loops with the deepest first, and the top-level loops last.
1021 for (auto L
= Loops
.rbegin(), E
= Loops
.rend(); L
!= E
; ++L
) {
1022 if (computeMassInLoop(*L
))
1024 auto Next
= std::next(L
);
1025 computeIrreducibleMass(&*L
, L
.base());
1026 L
= std::prev(Next
);
1027 if (computeMassInLoop(*L
))
1029 llvm_unreachable("unhandled irreducible control flow");
1034 bool BlockFrequencyInfoImpl
<BT
>::computeMassInLoop(LoopData
&Loop
) {
1035 // Compute mass in loop.
1036 DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop
) << "\n");
1038 if (Loop
.isIrreducible()) {
1039 BlockMass Remaining
= BlockMass::getFull();
1040 for (uint32_t H
= 0; H
< Loop
.NumHeaders
; ++H
) {
1041 auto &Mass
= Working
[Loop
.Nodes
[H
].Index
].getMass();
1042 Mass
= Remaining
* BranchProbability(1, Loop
.NumHeaders
- H
);
1045 for (const BlockNode
&M
: Loop
.Nodes
)
1046 if (!propagateMassToSuccessors(&Loop
, M
))
1047 llvm_unreachable("unhandled irreducible control flow");
1049 Working
[Loop
.getHeader().Index
].getMass() = BlockMass::getFull();
1050 if (!propagateMassToSuccessors(&Loop
, Loop
.getHeader()))
1051 llvm_unreachable("irreducible control flow to loop header!?");
1052 for (const BlockNode
&M
: Loop
.members())
1053 if (!propagateMassToSuccessors(&Loop
, M
))
1054 // Irreducible backedge.
1058 computeLoopScale(Loop
);
1064 bool BlockFrequencyInfoImpl
<BT
>::tryToComputeMassInFunction() {
1065 // Compute mass in function.
1066 DEBUG(dbgs() << "compute-mass-in-function\n");
1067 assert(!Working
.empty() && "no blocks in function");
1068 assert(!Working
[0].isLoopHeader() && "entry block is a loop header");
1070 Working
[0].getMass() = BlockMass::getFull();
1071 for (rpot_iterator I
= rpot_begin(), IE
= rpot_end(); I
!= IE
; ++I
) {
1072 // Check for nodes that have been packaged.
1073 BlockNode Node
= getNode(I
);
1074 if (Working
[Node
.Index
].isPackaged())
1077 if (!propagateMassToSuccessors(nullptr, Node
))
1083 template <class BT
> void BlockFrequencyInfoImpl
<BT
>::computeMassInFunction() {
1084 if (tryToComputeMassInFunction())
1086 computeIrreducibleMass(nullptr, Loops
.begin());
1087 if (tryToComputeMassInFunction())
1089 llvm_unreachable("unhandled irreducible control flow");
1092 /// \note This should be a lambda, but that crashes GCC 4.7.
1093 namespace bfi_detail
{
1094 template <class BT
> struct BlockEdgesAdder
{
1096 typedef BlockFrequencyInfoImplBase::LoopData LoopData
;
1097 typedef GraphTraits
<const BlockT
*> Successor
;
1099 const BlockFrequencyInfoImpl
<BT
> &BFI
;
1100 explicit BlockEdgesAdder(const BlockFrequencyInfoImpl
<BT
> &BFI
)
1102 void operator()(IrreducibleGraph
&G
, IrreducibleGraph::IrrNode
&Irr
,
1103 const LoopData
*OuterLoop
) {
1104 const BlockT
*BB
= BFI
.RPOT
[Irr
.Node
.Index
];
1105 for (auto I
= Successor::child_begin(BB
), E
= Successor::child_end(BB
);
1107 G
.addEdge(Irr
, BFI
.getNode(*I
), OuterLoop
);
1112 void BlockFrequencyInfoImpl
<BT
>::computeIrreducibleMass(
1113 LoopData
*OuterLoop
, std::list
<LoopData
>::iterator Insert
) {
1114 DEBUG(dbgs() << "analyze-irreducible-in-";
1115 if (OuterLoop
) dbgs() << "loop: " << getLoopName(*OuterLoop
) << "\n";
1116 else dbgs() << "function\n");
1118 using namespace bfi_detail
;
1119 // Ideally, addBlockEdges() would be declared here as a lambda, but that
1121 BlockEdgesAdder
<BT
> addBlockEdges(*this);
1122 IrreducibleGraph
G(*this, OuterLoop
, addBlockEdges
);
1124 for (auto &L
: analyzeIrreducible(G
, OuterLoop
, Insert
))
1125 computeMassInLoop(L
);
1129 updateLoopWithIrreducible(*OuterLoop
);
1134 BlockFrequencyInfoImpl
<BT
>::propagateMassToSuccessors(LoopData
*OuterLoop
,
1135 const BlockNode
&Node
) {
1136 DEBUG(dbgs() << " - node: " << getBlockName(Node
) << "\n");
1137 // Calculate probability for successors.
1139 if (auto *Loop
= Working
[Node
.Index
].getPackagedLoop()) {
1140 assert(Loop
!= OuterLoop
&& "Cannot propagate mass in a packaged loop");
1141 if (!addLoopSuccessorsToDist(OuterLoop
, *Loop
, Dist
))
1142 // Irreducible backedge.
1145 const BlockT
*BB
= getBlock(Node
);
1146 for (auto SI
= Successor::child_begin(BB
), SE
= Successor::child_end(BB
);
1148 // Do not dereference SI, or getEdgeWeight() is linear in the number of
1150 if (!addToDist(Dist
, OuterLoop
, Node
, getNode(*SI
),
1151 BPI
->getEdgeWeight(BB
, SI
)))
1152 // Irreducible backedge.
1156 // Distribute mass to successors, saving exit and backedge data in the
1158 distributeMass(Node
, OuterLoop
, Dist
);
1163 raw_ostream
&BlockFrequencyInfoImpl
<BT
>::print(raw_ostream
&OS
) const {
1166 OS
<< "block-frequency-info: " << F
->getName() << "\n";
1167 for (const BlockT
&BB
: *F
)
1168 OS
<< " - " << bfi_detail::getBlockName(&BB
)
1169 << ": float = " << getFloatingBlockFreq(&BB
)
1170 << ", int = " << getBlockFreq(&BB
).getFrequency() << "\n";
1172 // Add an extra newline for readability.
1177 } // end namespace llvm