LLVM 23.0.0git
BlockFrequencyInfoImpl.h
Go to the documentation of this file.
1//==- BlockFrequencyInfoImpl.h - Block Frequency Implementation --*- C++ -*-==//
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// Shared implementation of BlockFrequency for IR and Machine Instructions.
10// See the documentation below for BlockFrequencyInfoImpl for details.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
15#define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
16
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/Twine.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/ValueHandle.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/Format.h"
38#include <algorithm>
39#include <cassert>
40#include <cstddef>
41#include <cstdint>
42#include <deque>
43#include <iterator>
44#include <limits>
45#include <list>
46#include <optional>
47#include <queue>
48#include <string>
49#include <utility>
50#include <vector>
51
52#define DEBUG_TYPE "block-freq"
53
54namespace llvm {
56
60
61class BranchProbabilityInfo;
62class Function;
63class Loop;
64class LoopInfo;
65class MachineBasicBlock;
66class MachineBranchProbabilityInfo;
67class MachineFunction;
68class MachineLoop;
69class MachineLoopInfo;
70
71namespace bfi_detail {
72
73struct IrreducibleGraph;
74
75/// Mass of a block.
76///
77/// This class implements a sort of fixed-point fraction always between 0.0 and
78/// 1.0. getMass() == std::numeric_limits<uint64_t>::max() indicates a value of
79/// 1.0.
80///
81/// Masses can be added and subtracted. Simple saturation arithmetic is used,
82/// so arithmetic operations never overflow or underflow.
83///
84/// Masses can be multiplied. Multiplication treats full mass as 1.0 and uses
85/// an inexpensive floating-point algorithm that's off-by-one (almost, but not
86/// quite, maximum precision).
87///
88/// Masses can be scaled by \a BranchProbability at maximum precision.
89class BlockMass {
90 uint64_t Mass = 0;
91
92public:
93 BlockMass() = default;
94 explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
95
96 static BlockMass getEmpty() { return BlockMass(); }
97
98 static BlockMass getFull() {
99 return BlockMass(std::numeric_limits<uint64_t>::max());
100 }
101
102 uint64_t getMass() const { return Mass; }
103
104 bool isFull() const { return Mass == std::numeric_limits<uint64_t>::max(); }
105 bool isEmpty() const { return !Mass; }
106
107 bool operator!() const { return isEmpty(); }
108
109 /// Add another mass.
110 ///
111 /// Adds another mass, saturating at \a isFull() rather than overflowing.
113 uint64_t Sum = Mass + X.Mass;
114 Mass = Sum < Mass ? std::numeric_limits<uint64_t>::max() : Sum;
115 return *this;
116 }
117
118 /// Subtract another mass.
119 ///
120 /// Subtracts another mass, saturating at \a isEmpty() rather than
121 /// undeflowing.
123 uint64_t Diff = Mass - X.Mass;
124 Mass = Diff > Mass ? 0 : Diff;
125 return *this;
126 }
127
129 Mass = P.scale(Mass);
130 return *this;
131 }
132
133 bool operator==(BlockMass X) const { return Mass == X.Mass; }
134 bool operator!=(BlockMass X) const { return Mass != X.Mass; }
135 bool operator<=(BlockMass X) const { return Mass <= X.Mass; }
136 bool operator>=(BlockMass X) const { return Mass >= X.Mass; }
137 bool operator<(BlockMass X) const { return Mass < X.Mass; }
138 bool operator>(BlockMass X) const { return Mass > X.Mass; }
139
140 /// Convert to scaled number.
141 ///
142 /// Convert to \a ScaledNumber. \a isFull() gives 1.0, while \a isEmpty()
143 /// gives slightly above 0.0.
145
146 void dump() const;
147 raw_ostream &print(raw_ostream &OS) const;
148};
149
151 return BlockMass(L) += R;
152}
154 return BlockMass(L) -= R;
155}
157 return BlockMass(L) *= R;
158}
160 return BlockMass(R) *= L;
161}
162
164 return X.print(OS);
165}
166
167} // end namespace bfi_detail
168
169/// Base class for BlockFrequencyInfoImpl
170///
171/// BlockFrequencyInfoImplBase has supporting data structures and some
172/// algorithms for BlockFrequencyInfoImplBase. Only algorithms that depend on
173/// the block type (or that call such algorithms) are skipped here.
174///
175/// Nevertheless, the majority of the overall algorithm documentation lives with
176/// BlockFrequencyInfoImpl. See there for details.
178public:
181
182 /// Representative of a block.
183 ///
184 /// This is a simple wrapper around an index into the reverse-post-order
185 /// traversal of the blocks.
186 ///
187 /// Unlike a block pointer, its order has meaning (location in the
188 /// topological sort) and it's class is the same regardless of block type.
189 struct BlockNode {
191
193
194 BlockNode() : Index(std::numeric_limits<uint32_t>::max()) {}
196
197 bool operator==(const BlockNode &X) const { return Index == X.Index; }
198 bool operator!=(const BlockNode &X) const { return Index != X.Index; }
199 bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
200 bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
201 bool operator<(const BlockNode &X) const { return Index < X.Index; }
202 bool operator>(const BlockNode &X) const { return Index > X.Index; }
203
204 bool isValid() const { return Index <= getMaxIndex(); }
205
206 static size_t getMaxIndex() {
207 return std::numeric_limits<uint32_t>::max() - 1;
208 }
209 };
210
211 /// Stats about a block itself.
216
217 /// Data about a loop.
218 ///
219 /// Contains the data necessary to represent a loop as a pseudo-node once it's
220 /// packaged.
221 struct LoopData {
225
226 LoopData *Parent; ///< The parent loop.
227 bool IsPackaged = false; ///< Whether this has been packaged.
228 uint32_t NumHeaders = 1; ///< Number of headers.
229 ExitMap Exits; ///< Successor edges (and weights).
230 NodeList Nodes; ///< Header and the members of the loop.
231 HeaderMassList BackedgeMass; ///< Mass returned to each loop header.
234
236 : Parent(Parent), Nodes(1, Header), BackedgeMass(1) {}
237
238 template <class It1, class It2>
239 LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther,
240 It2 LastOther)
241 : Parent(Parent), Nodes(FirstHeader, LastHeader) {
242 NumHeaders = Nodes.size();
243 Nodes.insert(Nodes.end(), FirstOther, LastOther);
244 BackedgeMass.resize(NumHeaders);
245 }
246
247 bool isHeader(const BlockNode &Node) const {
248 if (isIrreducible())
249 return std::binary_search(Nodes.begin(), Nodes.begin() + NumHeaders,
250 Node);
251 return Node == Nodes[0];
252 }
253
254 BlockNode getHeader() const { return Nodes[0]; }
255 bool isIrreducible() const { return NumHeaders > 1; }
256
258 assert(isHeader(B) && "this is only valid on loop header blocks");
259 if (isIrreducible())
260 return std::lower_bound(Nodes.begin(), Nodes.begin() + NumHeaders, B) -
261 Nodes.begin();
262 return 0;
263 }
264
266 return Nodes.begin() + NumHeaders;
267 }
268
273 };
274
275 /// Index of loop information.
276 struct WorkingData {
277 BlockNode Node; ///< This node.
278 LoopData *Loop = nullptr; ///< The loop this block is inside.
279 BlockMass Mass; ///< Mass distribution from the entry block.
280
282
283 bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
284
285 bool isDoubleLoopHeader() const {
286 return isLoopHeader() && Loop->Parent && Loop->Parent->isIrreducible() &&
287 Loop->Parent->isHeader(Node);
288 }
289
291 if (!isLoopHeader())
292 return Loop;
293 if (!isDoubleLoopHeader())
294 return Loop->Parent;
295 return Loop->Parent->Parent;
296 }
297
298 /// Resolve a node to its representative.
299 ///
300 /// Get the node currently representing Node, which could be a containing
301 /// loop.
302 ///
303 /// This function should only be called when distributing mass. As long as
304 /// there are no irreducible edges to Node, then it will have complexity
305 /// O(1) in this context.
306 ///
307 /// In general, the complexity is O(L), where L is the number of loop
308 /// headers Node has been packaged into. Since this method is called in
309 /// the context of distributing mass, L will be the number of loop headers
310 /// an early exit edge jumps out of.
312 auto *L = getPackagedLoop();
313 return L ? L->getHeader() : Node;
314 }
315
317 if (!Loop || !Loop->IsPackaged)
318 return nullptr;
319 auto *L = Loop;
320 while (L->Parent && L->Parent->IsPackaged)
321 L = L->Parent;
322 return L;
323 }
324
325 /// Get the appropriate mass for a node.
326 ///
327 /// Get appropriate mass for Node. If Node is a loop-header (whose loop
328 /// has been packaged), returns the mass of its pseudo-node. If it's a
329 /// node inside a packaged loop, it returns the loop's mass.
331 if (!isAPackage())
332 return Mass;
333 if (!isADoublePackage())
334 return Loop->Mass;
335 return Loop->Parent->Mass;
336 }
337
338 /// Has ContainingLoop been packaged up?
339 bool isPackaged() const { return getResolvedNode() != Node; }
340
341 /// Has Loop been packaged up?
342 bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; }
343
344 /// Has Loop been packaged up twice?
345 bool isADoublePackage() const {
346 return isDoubleLoopHeader() && Loop->Parent->IsPackaged;
347 }
348 };
349
350 /// Unscaled probability weight.
351 ///
352 /// Probability weight for an edge in the graph (including the
353 /// successor/target node).
354 ///
355 /// All edges in the original function are 32-bit. However, exit edges from
356 /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
357 /// space in general.
358 ///
359 /// In addition to the raw weight amount, Weight stores the type of the edge
360 /// in the current context (i.e., the context of the loop being processed).
361 /// Is this a local edge within the loop, an exit from the loop, or a
362 /// backedge to the loop header?
373
374 /// Distribution of unscaled probability weight.
375 ///
376 /// Distribution of unscaled probability weight to a set of successors.
377 ///
378 /// This class collates the successor edge weights for later processing.
379 ///
380 /// \a DidOverflow indicates whether \a Total did overflow while adding to
381 /// the distribution. It should never overflow twice.
384
385 WeightList Weights; ///< Individual successor weights.
386 uint64_t Total = 0; ///< Sum of all weights.
387 bool DidOverflow = false; ///< Whether \a Total did overflow.
388
389 Distribution() = default;
390
391 void addLocal(const BlockNode &Node, uint64_t Amount) {
392 add(Node, Amount, Weight::Local);
393 }
394
395 void addExit(const BlockNode &Node, uint64_t Amount) {
396 add(Node, Amount, Weight::Exit);
397 }
398
399 void addBackedge(const BlockNode &Node, uint64_t Amount) {
400 add(Node, Amount, Weight::Backedge);
401 }
402
403 /// Normalize the distribution.
404 ///
405 /// Combines multiple edges to the same \a Weight::TargetNode and scales
406 /// down so that \a Total fits into 32-bits.
407 ///
408 /// This is linear in the size of \a Weights. For the vast majority of
409 /// cases, adjacent edge weights are combined by sorting WeightList and
410 /// combining adjacent weights. However, for very large edge lists an
411 /// auxiliary hash table is used.
412 void normalize();
413
414 private:
415 void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
416 };
417
418 /// Data about each block. This is used downstream.
419 std::vector<FrequencyData> Freqs;
420
421 /// Whether each block is an irreducible loop header.
422 /// This is used downstream.
424
425 /// Loop data: see initializeLoops().
426 std::vector<WorkingData> Working;
427
428 /// Indexed information about loops.
429 std::list<LoopData> Loops;
430
431 /// Virtual destructor.
432 ///
433 /// Need a virtual destructor to mask the compiler warning about
434 /// getBlockName().
435 virtual ~BlockFrequencyInfoImplBase() = default;
436
437 /// Add all edges out of a packaged loop to the distribution.
438 ///
439 /// Adds all edges from LocalLoopHead to Dist. Calls addToDist() to add each
440 /// successor edge.
441 ///
442 /// \return \c true unless there's an irreducible backedge.
443 bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop,
444 Distribution &Dist);
445
446 /// Add an edge to the distribution.
447 ///
448 /// Adds an edge to Succ to Dist. If \c LoopHead.isValid(), then whether the
449 /// edge is local/exit/backedge is in the context of LoopHead. Otherwise,
450 /// every edge should be a local edge (since all the loops are packaged up).
451 ///
452 /// \return \c true unless aborted due to an irreducible backedge.
453 bool addToDist(Distribution &Dist, const LoopData *OuterLoop,
454 const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
455
456 /// Analyze irreducible SCCs.
457 ///
458 /// Separate irreducible SCCs from \c G, which is an explicit graph of \c
459 /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr).
460 /// Insert them into \a Loops before \c Insert.
461 ///
462 /// \return the \c LoopData nodes representing the irreducible SCCs.
465 std::list<LoopData>::iterator Insert);
466
467 /// Update a loop after packaging irreducible SCCs inside of it.
468 ///
469 /// Update \c OuterLoop. Before finding irreducible control flow, it was
470 /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a
471 /// LoopData::BackedgeMass need to be reset. Also, nodes that were packaged
472 /// up need to be removed from \a OuterLoop::Nodes.
473 void updateLoopWithIrreducible(LoopData &OuterLoop);
474
475 /// Distribute mass according to a distribution.
476 ///
477 /// Distributes the mass in Source according to Dist. If LoopHead.isValid(),
478 /// backedges and exits are stored in its entry in Loops.
479 ///
480 /// Mass is distributed in parallel from two copies of the source mass.
481 void distributeMass(const BlockNode &Source, LoopData *OuterLoop,
482 Distribution &Dist);
483
484 /// Compute the loop scale for a loop.
486
487 /// Adjust the mass of all headers in an irreducible loop.
488 ///
489 /// Initially, irreducible loops are assumed to distribute their mass
490 /// equally among its headers. This can lead to wrong frequency estimates
491 /// since some headers may be executed more frequently than others.
492 ///
493 /// This adjusts header mass distribution so it matches the weights of
494 /// the backedges going into each of the loop headers.
496
498
499 /// Package up a loop.
501
502 /// Unwrap loops.
503 void unwrapLoops();
504
505 /// Finalize frequency metrics.
506 ///
507 /// Calculates final frequencies and cleans up no-longer-needed data
508 /// structures.
509 void finalizeMetrics();
510
511 /// Clear all memory.
512 void clear();
513
514 virtual std::string getBlockName(const BlockNode &Node) const;
515 std::string getLoopName(const LoopData &Loop) const;
516
517 virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
518 void dump() const { print(dbgs()); }
519
520 Scaled64 getFloatingBlockFreq(const BlockNode &Node) const;
521
522 BlockFrequency getBlockFreq(const BlockNode &Node) const;
523 std::optional<uint64_t>
524 getBlockProfileCount(const Function &F, const BlockNode &Node,
525 bool AllowSynthetic = false) const;
526 std::optional<uint64_t>
528 bool AllowSynthetic = false) const;
529 bool isIrrLoopHeader(const BlockNode &Node);
530
531 void setBlockFreq(const BlockNode &Node, BlockFrequency Freq);
532
534 assert(!Freqs.empty());
535 return BlockFrequency(Freqs[0].Integer);
536 }
537};
538
539namespace bfi_detail {
540
541template <class BlockT> struct TypeMap {};
556
557/// Get the name of a MachineBasicBlock.
558///
559/// Get the name of a MachineBasicBlock. It's templated so that including from
560/// CodeGen is unnecessary (that would be a layering issue).
561///
562/// This is used mainly for debug output. The name is similar to
563/// MachineBasicBlock::getFullName(), but skips the name of the function.
564template <class BlockT> std::string getBlockName(const BlockT *BB) {
565 assert(BB && "Unexpected nullptr");
566 auto MachineName = "BB" + Twine(BB->getNumber());
567 if (BB->getBasicBlock())
568 return (MachineName + "[" + BB->getName() + "]").str();
569 return MachineName.str();
570}
571/// Get the name of a BasicBlock.
572template <> inline std::string getBlockName(const BasicBlock *BB) {
573 assert(BB && "Unexpected nullptr");
574 return BB->getName().str();
575}
576
577/// Graph of irreducible control flow.
578///
579/// This graph is used for determining the SCCs in a loop (or top-level
580/// function) that has irreducible control flow.
581///
582/// During the block frequency algorithm, the local graphs are defined in a
583/// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock
584/// graphs for most edges, but getting others from \a LoopData::ExitMap. The
585/// latter only has successor information.
586///
587/// \a IrreducibleGraph makes this graph explicit. It's in a form that can use
588/// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator),
589/// and it explicitly lists predecessors and successors. The initialization
590/// that relies on \c MachineBasicBlock is defined in the header.
593
595
597 struct IrrNode {
599 unsigned NumIn = 0;
600 std::deque<const IrrNode *> Edges;
601
603
604 using iterator = std::deque<const IrrNode *>::const_iterator;
605
606 iterator pred_begin() const { return Edges.begin(); }
607 iterator succ_begin() const { return Edges.begin() + NumIn; }
608 iterator pred_end() const { return succ_begin(); }
609 iterator succ_end() const { return Edges.end(); }
610 };
612 const IrrNode *StartIrr = nullptr;
613 std::vector<IrrNode> Nodes;
615
616 /// Construct an explicit graph containing irreducible control flow.
617 ///
618 /// Construct an explicit graph of the control flow in \c OuterLoop (or the
619 /// top-level function, if \c OuterLoop is \c nullptr). Uses \c
620 /// addBlockEdges to add block successors that have not been packaged into
621 /// loops.
622 ///
623 /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected
624 /// user of this.
625 template <class BlockEdgesAdder>
627 BlockEdgesAdder addBlockEdges) : BFI(BFI) {
628 initialize(OuterLoop, addBlockEdges);
629 }
630
631 template <class BlockEdgesAdder>
632 void initialize(const BFIBase::LoopData *OuterLoop,
633 BlockEdgesAdder addBlockEdges);
634 void addNodesInLoop(const BFIBase::LoopData &OuterLoop);
635 void addNodesInFunction();
636
637 void addNode(const BlockNode &Node) {
638 Nodes.emplace_back(Node);
639 BFI.Working[Node.Index].getMass() = BlockMass::getEmpty();
640 }
641
642 void indexNodes();
643 template <class BlockEdgesAdder>
644 void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop,
645 BlockEdgesAdder addBlockEdges);
646 void addEdge(IrrNode &Irr, const BlockNode &Succ,
647 const BFIBase::LoopData *OuterLoop);
648};
649
650template <class BlockEdgesAdder>
652 BlockEdgesAdder addBlockEdges) {
653 if (OuterLoop) {
654 addNodesInLoop(*OuterLoop);
655 for (auto N : OuterLoop->Nodes)
656 addEdges(N, OuterLoop, addBlockEdges);
657 } else {
659 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
660 addEdges(Index, OuterLoop, addBlockEdges);
661 }
662 StartIrr = Lookup[Start.Index];
663}
664
665template <class BlockEdgesAdder>
667 const BFIBase::LoopData *OuterLoop,
668 BlockEdgesAdder addBlockEdges) {
669 auto L = Lookup.find(Node.Index);
670 if (L == Lookup.end())
671 return;
672 IrrNode &Irr = *L->second;
673 const auto &Working = BFI.Working[Node.Index];
674
675 if (Working.isAPackage())
676 for (const auto &I : Working.Loop->Exits)
677 addEdge(Irr, I.first, OuterLoop);
678 else
679 addBlockEdges(*this, Irr, OuterLoop);
680}
681
682} // end namespace bfi_detail
683
684/// Shared implementation for block frequency analysis.
685///
686/// This is a shared implementation of BlockFrequencyInfo and
687/// MachineBlockFrequencyInfo, and calculates the relative frequencies of
688/// blocks.
689///
690/// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block,
691/// which is called the header. A given loop, L, can have sub-loops, which are
692/// loops within the subgraph of L that exclude its header. (A "trivial" SCC
693/// consists of a single block that does not have a self-edge.)
694///
695/// In addition to loops, this algorithm has limited support for irreducible
696/// SCCs, which are SCCs with multiple entry blocks. Irreducible SCCs are
697/// discovered on the fly, and modelled as loops with multiple headers.
698///
699/// The headers of irreducible sub-SCCs consist of its entry blocks and all
700/// nodes that are targets of a backedge within it (excluding backedges within
701/// true sub-loops). Block frequency calculations act as if a block is
702/// inserted that intercepts all the edges to the headers. All backedges and
703/// entries point to this block. Its successors are the headers, which split
704/// the frequency evenly.
705///
706/// This algorithm leverages BlockMass and ScaledNumber to maintain precision,
707/// separates mass distribution from loop scaling, and dithers to eliminate
708/// probability mass loss.
709///
710/// The implementation is split between BlockFrequencyInfoImpl, which knows the
711/// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
712/// BlockFrequencyInfoImplBase, which doesn't. The base class uses \a
713/// BlockNode, a wrapper around a uint32_t. BlockNode is numbered from 0 in
714/// reverse-post order. This gives two advantages: it's easy to compare the
715/// relative ordering of two nodes, and maps keyed on BlockT can be represented
716/// by vectors.
717///
718/// This algorithm is O(V+E), unless there is irreducible control flow, in
719/// which case it's O(V*E) in the worst case.
720///
721/// These are the main stages:
722///
723/// 0. Reverse post-order traversal (\a initializeRPOT()).
724///
725/// Run a single post-order traversal and save it (in reverse) in RPOT.
726/// All other stages make use of this ordering. Save a lookup from BlockT
727/// to BlockNode (the index into RPOT) in Nodes.
728///
729/// 1. Loop initialization (\a initializeLoops()).
730///
731/// Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
732/// the algorithm. In particular, store the immediate members of each loop
733/// in reverse post-order.
734///
735/// 2. Calculate mass and scale in loops (\a computeMassInLoops()).
736///
737/// For each loop (bottom-up), distribute mass through the DAG resulting
738/// from ignoring backedges and treating sub-loops as a single pseudo-node.
739/// Track the backedge mass distributed to the loop header, and use it to
740/// calculate the loop scale (number of loop iterations). Immediate
741/// members that represent sub-loops will already have been visited and
742/// packaged into a pseudo-node.
743///
744/// Distributing mass in a loop is a reverse-post-order traversal through
745/// the loop. Start by assigning full mass to the Loop header. For each
746/// node in the loop:
747///
748/// - Fetch and categorize the weight distribution for its successors.
749/// If this is a packaged-subloop, the weight distribution is stored
750/// in \a LoopData::Exits. Otherwise, fetch it from
751/// BranchProbabilityInfo.
752///
753/// - Each successor is categorized as \a Weight::Local, a local edge
754/// within the current loop, \a Weight::Backedge, a backedge to the
755/// loop header, or \a Weight::Exit, any successor outside the loop.
756/// The weight, the successor, and its category are stored in \a
757/// Distribution. There can be multiple edges to each successor.
758///
759/// - If there's a backedge to a non-header, there's an irreducible SCC.
760/// The usual flow is temporarily aborted. \a
761/// computeIrreducibleMass() finds the irreducible SCCs within the
762/// loop, packages them up, and restarts the flow.
763///
764/// - Normalize the distribution: scale weights down so that their sum
765/// is 32-bits, and coalesce multiple edges to the same node.
766///
767/// - Distribute the mass accordingly, dithering to minimize mass loss,
768/// as described in \a distributeMass().
769///
770/// In the case of irreducible loops, instead of a single loop header,
771/// there will be several. The computation of backedge masses is similar
772/// but instead of having a single backedge mass, there will be one
773/// backedge per loop header. In these cases, each backedge will carry
774/// a mass proportional to the edge weights along the corresponding
775/// path.
776///
777/// At the end of propagation, the full mass assigned to the loop will be
778/// distributed among the loop headers proportionally according to the
779/// mass flowing through their backedges.
780///
781/// Finally, calculate the loop scale from the accumulated backedge mass.
782///
783/// 3. Distribute mass in the function (\a computeMassInFunction()).
784///
785/// Finally, distribute mass through the DAG resulting from packaging all
786/// loops in the function. This uses the same algorithm as distributing
787/// mass in a loop, except that there are no exit or backedge edges.
788///
789/// 4. Unpackage loops (\a unwrapLoops()).
790///
791/// Initialize each block's frequency to a floating point representation of
792/// its mass.
793///
794/// Visit loops top-down, scaling the frequencies of its immediate members
795/// by the loop's pseudo-node's frequency.
796///
797/// 5. Convert frequencies to a 64-bit range (\a finalizeMetrics()).
798///
799/// Using the min and max frequencies as a guide, translate floating point
800/// frequencies to an appropriate range in uint64_t.
801///
802/// It has some known flaws.
803///
804/// - The model of irreducible control flow is a rough approximation.
805///
806/// Modelling irreducible control flow exactly involves setting up and
807/// solving a group of infinite geometric series. Such precision is
808/// unlikely to be worthwhile, since most of our algorithms give up on
809/// irreducible control flow anyway.
810///
811/// Nevertheless, we might find that we need to get closer. Here's a sort
812/// of TODO list for the model with diminishing returns, to be completed as
813/// necessary.
814///
815/// - The headers for the \a LoopData representing an irreducible SCC
816/// include non-entry blocks. When these extra blocks exist, they
817/// indicate a self-contained irreducible sub-SCC. We could treat them
818/// as sub-loops, rather than arbitrarily shoving the problematic
819/// blocks into the headers of the main irreducible SCC.
820///
821/// - Entry frequencies are assumed to be evenly split between the
822/// headers of a given irreducible SCC, which is the only option if we
823/// need to compute mass in the SCC before its parent loop. Instead,
824/// we could partially compute mass in the parent loop, and stop when
825/// we get to the SCC. Here, we have the correct ratio of entry
826/// masses, which we can use to adjust their relative frequencies.
827/// Compute mass in the SCC, and then continue propagation in the
828/// parent.
829///
830/// - We can propagate mass iteratively through the SCC, for some fixed
831/// number of iterations. Each iteration starts by assigning the entry
832/// blocks their backedge mass from the prior iteration. The final
833/// mass for each block (and each exit, and the total backedge mass
834/// used for computing loop scale) is the sum of all iterations.
835/// (Running this until fixed point would "solve" the geometric
836/// series by simulation.)
838 using BlockT = typename bfi_detail::TypeMap<BT>::BlockT;
839 using FunctionT = typename bfi_detail::TypeMap<BT>::FunctionT;
840 using BranchProbabilityInfoT =
842 using LoopT = typename bfi_detail::TypeMap<BT>::LoopT;
843 using LoopInfoT = typename bfi_detail::TypeMap<BT>::LoopInfoT;
844 using Successor = GraphTraits<const BlockT *>;
845 using Predecessor = GraphTraits<Inverse<const BlockT *>>;
846
847 const BranchProbabilityInfoT *BPI = nullptr;
848 const LoopInfoT *LI = nullptr;
849 const FunctionT *F = nullptr;
850
851 // All blocks in reverse postorder.
852 std::vector<const BlockT *> RPOT;
853 /// Map from block number to number on RPOT/Freqs.
855 unsigned BlockNumberEpoch;
856
857 BlockNode getNode(const BlockT *BB) const {
858 assert(BlockNumberEpoch ==
860 unsigned BlockNumber = GraphTraits<const BlockT *>::getNumber(BB);
861 return BlockNumber < Nodes.size() ? Nodes[BlockNumber] : BlockNode();
862 }
863
864 const BlockT *getBlock(const BlockNode &Node) const {
865 assert(Node.Index < RPOT.size());
866 return RPOT[Node.Index];
867 }
868
869 /// Run (and save) a post-order traversal.
870 ///
871 /// Saves a reverse post-order traversal of all the nodes in \a F.
872 void initializeRPOT();
873
874 /// Initialize loop data.
875 ///
876 /// Build up \a Loops using \a LoopInfo. \a LoopInfo gives us a mapping from
877 /// each block to the deepest loop it's in, but we need the inverse. For each
878 /// loop, we store in reverse post-order its "immediate" members, defined as
879 /// the header, the headers of immediate sub-loops, and all other blocks in
880 /// the loop that are not in sub-loops.
881 void initializeLoops();
882
883 /// Propagate to a block's successors.
884 ///
885 /// In the context of distributing mass through \c OuterLoop, divide the mass
886 /// currently assigned to \c Node between its successors.
887 ///
888 /// \return \c true unless there's an irreducible backedge.
889 bool propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node);
890
891 /// Compute mass in a particular loop.
892 ///
893 /// Assign mass to \c Loop's header, and then for each block in \c Loop in
894 /// reverse post-order, distribute mass to its successors. Only visits nodes
895 /// that have not been packaged into sub-loops.
896 ///
897 /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
898 /// \return \c true unless there's an irreducible backedge.
899 bool computeMassInLoop(LoopData &Loop);
900
901 /// Try to compute mass in the top-level function.
902 ///
903 /// Assign mass to the entry block, and then for each block in reverse
904 /// post-order, distribute mass to its successors. Skips nodes that have
905 /// been packaged into loops.
906 ///
907 /// \pre \a computeMassInLoops() has been called.
908 /// \return \c true unless there's an irreducible backedge.
909 bool tryToComputeMassInFunction();
910
911 /// Compute mass in (and package up) irreducible SCCs.
912 ///
913 /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front
914 /// of \c Insert), and call \a computeMassInLoop() on each of them.
915 ///
916 /// If \c OuterLoop is \c nullptr, it refers to the top-level function.
917 ///
918 /// \pre \a computeMassInLoop() has been called for each subloop of \c
919 /// OuterLoop.
920 /// \pre \c Insert points at the last loop successfully processed by \a
921 /// computeMassInLoop().
922 /// \pre \c OuterLoop has irreducible SCCs.
923 void computeIrreducibleMass(LoopData *OuterLoop,
924 std::list<LoopData>::iterator Insert);
925
926 /// Compute mass in all loops.
927 ///
928 /// For each loop bottom-up, call \a computeMassInLoop().
929 ///
930 /// \a computeMassInLoop() aborts (and returns \c false) on loops that
931 /// contain a irreducible sub-SCCs. Use \a computeIrreducibleMass() and then
932 /// re-enter \a computeMassInLoop().
933 ///
934 /// \post \a computeMassInLoop() has returned \c true for every loop.
935 void computeMassInLoops();
936
937 /// Compute mass in the top-level function.
938 ///
939 /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to
940 /// compute mass in the top-level function.
941 ///
942 /// \post \a tryToComputeMassInFunction() has returned \c true.
943 void computeMassInFunction();
944
945 std::string getBlockName(const BlockNode &Node) const override {
946 return bfi_detail::getBlockName(getBlock(Node));
947 }
948
949 /// The current implementation for computing relative block frequencies does
950 /// not handle correctly control-flow graphs containing irreducible loops. To
951 /// resolve the problem, we apply a post-processing step, which iteratively
952 /// updates block frequencies based on the frequencies of their predesessors.
953 /// This corresponds to finding the stationary point of the Markov chain by
954 /// an iterative method aka "PageRank computation".
955 /// The algorithm takes at most O(|E| * IterativeBFIMaxIterations) steps but
956 /// typically converges faster.
957 ///
958 /// Decide whether we want to apply iterative inference for a given function.
959 bool needIterativeInference() const;
960
961 /// Apply an iterative post-processing to infer correct counts for irr loops.
962 void applyIterativeInference();
963
964 using ProbMatrixType = std::vector<std::vector<std::pair<size_t, Scaled64>>>;
965
966 /// Run iterative inference for a probability matrix and initial frequencies.
967 void iterativeInference(const ProbMatrixType &ProbMatrix,
968 std::vector<Scaled64> &Freq) const;
969
970 /// Find all blocks to apply inference on, that is, reachable from the entry
971 /// and backward reachable from exists along edges with positive probability.
972 void findReachableBlocks(std::vector<const BlockT *> &Blocks) const;
973
974 /// Build a matrix of probabilities with transitions (edges) between the
975 /// blocks: ProbMatrix[I] holds pairs (J, P), where Pr[J -> I | J] = P
976 void initTransitionProbabilities(
977 const std::vector<const BlockT *> &Blocks,
978 const DenseMap<const BlockT *, size_t> &BlockIndex,
979 ProbMatrixType &ProbMatrix) const;
980
981#ifndef NDEBUG
982 /// Compute the discrepancy between current block frequencies and the
983 /// probability matrix.
984 Scaled64 discrepancy(const ProbMatrixType &ProbMatrix,
985 const std::vector<Scaled64> &Freq) const;
986#endif
987
988public:
990
991 const FunctionT *getFunction() const { return F; }
992
993 void calculate(const FunctionT &F, const BranchProbabilityInfoT &BPI,
994 const LoopInfoT &LI);
995
997
998 BlockFrequency getBlockFreq(const BlockT *BB) const {
1000 }
1001
1002 std::optional<uint64_t>
1003 getBlockProfileCount(const Function &F, const BlockT *BB,
1004 bool AllowSynthetic = false) const {
1006 AllowSynthetic);
1007 }
1008
1009 std::optional<uint64_t>
1011 bool AllowSynthetic = false) const {
1013 AllowSynthetic);
1014 }
1015
1016 bool isIrrLoopHeader(const BlockT *BB) {
1018 }
1019
1020 void setBlockFreq(const BlockT *BB, BlockFrequency Freq);
1021
1022 Scaled64 getFloatingBlockFreq(const BlockT *BB) const {
1024 }
1025
1026 const BranchProbabilityInfoT &getBPI() const { return *BPI; }
1027
1028 /// Print the frequencies for the current function.
1029 ///
1030 /// Prints the frequencies for the blocks in the current function.
1031 ///
1032 /// Blocks are printed in the natural iteration order of the function, rather
1033 /// than reverse post-order. This provides two advantages: writing -analyze
1034 /// tests is easier (since blocks come out in source order), and even
1035 /// unreachable blocks are printed.
1036 ///
1037 /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
1038 /// we need to override it here.
1039 raw_ostream &print(raw_ostream &OS) const override;
1040
1042
1044};
1045
1046template <class BT>
1048 const BranchProbabilityInfoT &BPI,
1049 const LoopInfoT &LI) {
1050 // Save the parameters.
1051 this->BPI = &BPI;
1052 this->LI = &LI;
1053 this->F = &F;
1054
1055 // Clean up left-over data structures.
1057 RPOT.clear();
1058 Nodes.clear();
1059
1060 // Initialize.
1061 LLVM_DEBUG(dbgs() << "\nblock-frequency: " << F.getName()
1062 << "\n================="
1063 << std::string(F.getName().size(), '=') << "\n");
1064 initializeRPOT();
1065 initializeLoops();
1066
1067 // Visit loops in post-order to find the local mass distribution, and then do
1068 // the full function.
1069 computeMassInLoops();
1070 computeMassInFunction();
1071 unwrapLoops();
1072 // Apply a post-processing step improving computed frequencies for functions
1073 // with irreducible loops.
1074 if (needIterativeInference())
1075 applyIterativeInference();
1077
1079 // To detect BFI queries for unknown blocks, add entries for unreachable
1080 // blocks, if any. This is to distinguish between known/existing unreachable
1081 // blocks and unknown blocks.
1082 for (const BlockT &BB : F)
1083 if (!getNode(&BB).isValid())
1085 }
1086
1087 RPOT.clear();
1088}
1089
1090template <class BT>
1092 BlockFrequency Freq) {
1094 unsigned BlockNumber = GraphTraits<const BlockT *>::getNumber(BB);
1095 if (Nodes.size() <= BlockNumber)
1097 BlockNode &Node = Nodes[BlockNumber];
1098 if (!Node.isValid()) {
1099 // If BB is a newly added block after BFI is done, we need to create a new
1100 // BlockNode for it assigned with a new index. The index can be determined
1101 // by the size of Freqs.
1102 Node = BlockNode(Freqs.size());
1103 Freqs.emplace_back();
1104 }
1106}
1107
1108template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1109 const BlockT *Entry = &F->front();
1110 RPOT.reserve(F->size());
1111 for (const BlockT *BB : post_order(Entry))
1112 RPOT.emplace_back(BB);
1113 std::reverse(RPOT.begin(), RPOT.end());
1114
1115 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1116 "More nodes in function than Block Frequency Info supports");
1117
1118 LLVM_DEBUG(dbgs() << "reverse-post-order-traversal\n");
1121 for (auto [Idx, Block] : enumerate(RPOT)) {
1122 BlockNode Node = BlockNode(Idx);
1123 LLVM_DEBUG(dbgs() << " - " << Idx << ": " << getBlockName(Node) << "\n");
1125 }
1126
1127 Working.reserve(RPOT.size());
1128 for (size_t Index = 0; Index < RPOT.size(); ++Index)
1129 Working.emplace_back(Index);
1130 Freqs.resize(RPOT.size());
1131}
1132
1133template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1134 LLVM_DEBUG(dbgs() << "loop-detection\n");
1135 if (LI->empty())
1136 return;
1137
1138 // Visit loops top down and assign them an index.
1139 std::deque<std::pair<const LoopT *, LoopData *>> Q;
1140 for (const LoopT *L : *LI)
1141 Q.emplace_back(L, nullptr);
1142 while (!Q.empty()) {
1143 const LoopT *Loop = Q.front().first;
1144 LoopData *Parent = Q.front().second;
1145 Q.pop_front();
1146
1147 BlockNode Header = getNode(Loop->getHeader());
1148 assert(Header.isValid());
1149
1150 Loops.emplace_back(Parent, Header);
1151 Working[Header.Index].Loop = &Loops.back();
1152 LLVM_DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1153
1154 for (const LoopT *L : *Loop)
1155 Q.emplace_back(L, &Loops.back());
1156 }
1157
1158 // Visit nodes in reverse post-order and add them to their deepest containing
1159 // loop.
1160 for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1161 // Loop headers have already been mostly mapped.
1162 if (Working[Index].isLoopHeader()) {
1163 LoopData *ContainingLoop = Working[Index].getContainingLoop();
1164 if (ContainingLoop)
1165 ContainingLoop->Nodes.push_back(Index);
1166 continue;
1167 }
1168
1169 const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1170 if (!Loop)
1171 continue;
1172
1173 // Add this node to its containing loop's member list.
1174 BlockNode Header = getNode(Loop->getHeader());
1175 assert(Header.isValid());
1176 const auto &HeaderData = Working[Header.Index];
1177 assert(HeaderData.isLoopHeader());
1178
1179 Working[Index].Loop = HeaderData.Loop;
1180 HeaderData.Loop->Nodes.push_back(Index);
1181 LLVM_DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1182 << ": member = " << getBlockName(Index) << "\n");
1183 }
1184}
1185
1186template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1187 // Visit loops with the deepest first, and the top-level loops last.
1188 for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) {
1189 if (computeMassInLoop(*L))
1190 continue;
1191 auto Next = std::next(L);
1192 computeIrreducibleMass(&*L, L.base());
1193 L = std::prev(Next);
1194 if (computeMassInLoop(*L))
1195 continue;
1196 llvm_unreachable("unhandled irreducible control flow");
1197 }
1198}
1199
1200template <class BT>
1201bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
1202 // Compute mass in loop.
1203 LLVM_DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop) << "\n");
1204
1205 if (Loop.isIrreducible()) {
1206 LLVM_DEBUG(dbgs() << "isIrreducible = true\n");
1207 Distribution Dist;
1208 unsigned NumHeadersWithWeight = 0;
1209 std::optional<uint64_t> MinHeaderWeight;
1210 DenseSet<uint32_t> HeadersWithoutWeight;
1211 HeadersWithoutWeight.reserve(Loop.NumHeaders);
1212 for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
1213 auto &HeaderNode = Loop.Nodes[H];
1214 const BlockT *Block = getBlock(HeaderNode);
1215 IsIrrLoopHeader.set(Loop.Nodes[H].Index);
1216 std::optional<uint64_t> HeaderWeight = Block->getIrrLoopHeaderWeight();
1217 if (!HeaderWeight) {
1218 LLVM_DEBUG(dbgs() << "Missing irr loop header metadata on "
1219 << getBlockName(HeaderNode) << "\n");
1220 HeadersWithoutWeight.insert(H);
1221 continue;
1222 }
1223 LLVM_DEBUG(dbgs() << getBlockName(HeaderNode)
1224 << " has irr loop header weight " << *HeaderWeight
1225 << "\n");
1226 NumHeadersWithWeight++;
1227 uint64_t HeaderWeightValue = *HeaderWeight;
1228 if (!MinHeaderWeight || HeaderWeightValue < MinHeaderWeight)
1229 MinHeaderWeight = HeaderWeightValue;
1230 if (HeaderWeightValue) {
1231 Dist.addLocal(HeaderNode, HeaderWeightValue);
1232 }
1233 }
1234 // As a heuristic, if some headers don't have a weight, give them the
1235 // minimum weight seen (not to disrupt the existing trends too much by
1236 // using a weight that's in the general range of the other headers' weights,
1237 // and the minimum seems to perform better than the average.)
1238 // FIXME: better update in the passes that drop the header weight.
1239 // If no headers have a weight, give them even weight (use weight 1).
1240 if (!MinHeaderWeight)
1241 MinHeaderWeight = 1;
1242 for (uint32_t H : HeadersWithoutWeight) {
1243 auto &HeaderNode = Loop.Nodes[H];
1244 assert(!getBlock(HeaderNode)->getIrrLoopHeaderWeight() &&
1245 "Shouldn't have a weight metadata");
1246 uint64_t MinWeight = *MinHeaderWeight;
1247 LLVM_DEBUG(dbgs() << "Giving weight " << MinWeight << " to "
1248 << getBlockName(HeaderNode) << "\n");
1249 if (MinWeight)
1250 Dist.addLocal(HeaderNode, MinWeight);
1251 }
1252 distributeIrrLoopHeaderMass(Dist);
1253 for (const BlockNode &M : Loop.Nodes)
1254 if (!propagateMassToSuccessors(&Loop, M))
1255 llvm_unreachable("unhandled irreducible control flow");
1256 if (NumHeadersWithWeight == 0)
1257 // No headers have a metadata. Adjust header mass.
1258 adjustLoopHeaderMass(Loop);
1259 } else {
1260 Working[Loop.getHeader().Index].getMass() = BlockMass::getFull();
1261 if (!propagateMassToSuccessors(&Loop, Loop.getHeader()))
1262 llvm_unreachable("irreducible control flow to loop header!?");
1263 for (const BlockNode &M : Loop.members())
1264 if (!propagateMassToSuccessors(&Loop, M))
1265 // Irreducible backedge.
1266 return false;
1267 }
1268
1269 computeLoopScale(Loop);
1270 packageLoop(Loop);
1271 return true;
1272}
1273
1274template <class BT>
1275bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
1276 // Compute mass in function.
1277 LLVM_DEBUG(dbgs() << "compute-mass-in-function\n");
1278 assert(!Working.empty() && "no blocks in function");
1279 assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1280
1281 Working[0].getMass() = BlockMass::getFull();
1282 for (size_t i = 0, n = RPOT.size(); i != n; ++i) {
1283 // Check for nodes that have been packaged.
1284 if (Working[i].isPackaged())
1285 continue;
1286
1287 if (!propagateMassToSuccessors(nullptr, BlockNode(i)))
1288 return false;
1289 }
1290 return true;
1291}
1292
1293template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1294 if (tryToComputeMassInFunction())
1295 return;
1296 computeIrreducibleMass(nullptr, Loops.begin());
1297 if (tryToComputeMassInFunction())
1298 return;
1299 llvm_unreachable("unhandled irreducible control flow");
1300}
1301
1302template <class BT>
1303bool BlockFrequencyInfoImpl<BT>::needIterativeInference() const {
1305 return false;
1306 if (!F->getFunction().hasProfileData())
1307 return false;
1308 // Apply iterative inference only if the function contains irreducible loops;
1309 // otherwise, computed block frequencies are reasonably correct.
1310 for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) {
1311 if (L->isIrreducible())
1312 return true;
1313 }
1314 return false;
1315}
1316
1317template <class BT> void BlockFrequencyInfoImpl<BT>::applyIterativeInference() {
1318 // Extract blocks for processing: a block is considered for inference iff it
1319 // can be reached from the entry by edges with a positive probability.
1320 // Non-processed blocks are assigned with the zero frequency and are ignored
1321 // in the computation
1322 std::vector<const BlockT *> ReachableBlocks;
1323 findReachableBlocks(ReachableBlocks);
1324 if (ReachableBlocks.empty())
1325 return;
1326
1327 // The map is used to index successors/predecessors of reachable blocks in
1328 // the ReachableBlocks vector
1330 // Extract initial frequencies for the reachable blocks
1331 auto Freq = std::vector<Scaled64>(ReachableBlocks.size());
1332 Scaled64 SumFreq;
1333 for (size_t I = 0; I < ReachableBlocks.size(); I++) {
1334 const BlockT *BB = ReachableBlocks[I];
1335 BlockIndex[BB] = I;
1336 Freq[I] = getFloatingBlockFreq(BB);
1337 SumFreq += Freq[I];
1338 }
1339 assert(!SumFreq.isZero() && "empty initial block frequencies");
1340
1341 LLVM_DEBUG(dbgs() << "Applying iterative inference for " << F->getName()
1342 << " with " << ReachableBlocks.size() << " blocks\n");
1343
1344 // Normalizing frequencies so they sum up to 1.0
1345 for (auto &Value : Freq) {
1346 Value /= SumFreq;
1347 }
1348
1349 // Setting up edge probabilities using sparse matrix representation:
1350 // ProbMatrix[I] holds a vector of pairs (J, P) where Pr[J -> I | J] = P
1351 ProbMatrixType ProbMatrix;
1352 initTransitionProbabilities(ReachableBlocks, BlockIndex, ProbMatrix);
1353
1354 // Run the propagation
1355 iterativeInference(ProbMatrix, Freq);
1356
1357 // Assign computed frequency values
1358 for (const BlockT &BB : *F) {
1359 auto Node = getNode(&BB);
1360 if (!Node.isValid())
1361 continue;
1362 if (auto It = BlockIndex.find(&BB); It != BlockIndex.end())
1363 Freqs[Node.Index].Scaled = Freq[It->second];
1364 else
1365 Freqs[Node.Index].Scaled = Scaled64::getZero();
1366 }
1367}
1368
1369template <class BT>
1370void BlockFrequencyInfoImpl<BT>::iterativeInference(
1371 const ProbMatrixType &ProbMatrix, std::vector<Scaled64> &Freq) const {
1373 "incorrectly specified precision");
1374 // Convert double precision to Scaled64
1375 const auto Precision =
1376 Scaled64::getInverse(static_cast<uint64_t>(1.0 / IterativeBFIPrecision));
1377 const size_t MaxIterations = IterativeBFIMaxIterationsPerBlock * Freq.size();
1378
1379#ifndef NDEBUG
1380 LLVM_DEBUG(dbgs() << " Initial discrepancy = "
1381 << discrepancy(ProbMatrix, Freq).toString() << "\n");
1382#endif
1383
1384 // Successors[I] holds unique sucessors of the I-th block
1385 auto Successors = std::vector<std::vector<size_t>>(Freq.size());
1386 for (size_t I = 0; I < Freq.size(); I++) {
1387 for (const auto &Jump : ProbMatrix[I]) {
1388 Successors[Jump.first].push_back(I);
1389 }
1390 }
1391
1392 // To speedup computation, we maintain a set of "active" blocks whose
1393 // frequencies need to be updated based on the incoming edges.
1394 // The set is dynamic and changes after every update. Initially all blocks
1395 // with a positive frequency are active
1396 auto IsActive = BitVector(Freq.size(), false);
1397 std::queue<size_t> ActiveSet;
1398 for (size_t I = 0; I < Freq.size(); I++) {
1399 if (Freq[I] > 0) {
1400 ActiveSet.push(I);
1401 IsActive[I] = true;
1402 }
1403 }
1404
1405 // Iterate over the blocks propagating frequencies
1406 size_t It = 0;
1407 while (It++ < MaxIterations && !ActiveSet.empty()) {
1408 size_t I = ActiveSet.front();
1409 ActiveSet.pop();
1410 IsActive[I] = false;
1411
1412 // Compute a new frequency for the block: NewFreq := Freq \times ProbMatrix.
1413 // A special care is taken for self-edges that needs to be scaled by
1414 // (1.0 - SelfProb), where SelfProb is the sum of probabilities on the edges
1415 Scaled64 NewFreq;
1416 Scaled64 OneMinusSelfProb = Scaled64::getOne();
1417 for (const auto &Jump : ProbMatrix[I]) {
1418 if (Jump.first == I) {
1419 OneMinusSelfProb -= Jump.second;
1420 } else {
1421 NewFreq += Freq[Jump.first] * Jump.second;
1422 }
1423 }
1424 if (OneMinusSelfProb != Scaled64::getOne())
1425 NewFreq /= OneMinusSelfProb;
1426
1427 // If the block's frequency has changed enough, then
1428 // make sure the block and its successors are in the active set
1429 auto Change = Freq[I] >= NewFreq ? Freq[I] - NewFreq : NewFreq - Freq[I];
1430 if (Change > Precision) {
1431 ActiveSet.push(I);
1432 IsActive[I] = true;
1433 for (size_t Succ : Successors[I]) {
1434 if (!IsActive[Succ]) {
1435 ActiveSet.push(Succ);
1436 IsActive[Succ] = true;
1437 }
1438 }
1439 }
1440
1441 // Update the frequency for the block
1442 Freq[I] = NewFreq;
1443 }
1444
1445 LLVM_DEBUG(dbgs() << " Completed " << It << " inference iterations"
1446 << format(" (%0.0f per block)", double(It) / Freq.size())
1447 << "\n");
1448#ifndef NDEBUG
1449 LLVM_DEBUG(dbgs() << " Final discrepancy = "
1450 << discrepancy(ProbMatrix, Freq).toString() << "\n");
1451#endif
1452}
1453
1454template <class BT>
1455void BlockFrequencyInfoImpl<BT>::findReachableBlocks(
1456 std::vector<const BlockT *> &Blocks) const {
1457 // Find all blocks to apply inference on, that is, reachable from the entry
1458 // along edges with non-zero probablities
1459 std::queue<const BlockT *> Queue;
1461 const BlockT *Entry = &F->front();
1462 Queue.push(Entry);
1463 Reachable.insert(Entry);
1464 while (!Queue.empty()) {
1465 const BlockT *SrcBB = Queue.front();
1466 Queue.pop();
1467 for (auto It : enumerate(children<const BlockT *>(SrcBB))) {
1468 auto EP = BPI->getEdgeProbability(SrcBB, It.index());
1469 if (EP.isZero())
1470 continue;
1471 if (Reachable.insert(It.value()).second)
1472 Queue.push(It.value());
1473 }
1474 }
1475
1476 // Find all blocks to apply inference on, that is, backward reachable from
1477 // the entry along (backward) edges with non-zero probablities
1478 SmallPtrSet<const BlockT *, 8> InverseReachable;
1479 for (const BlockT &BB : *F) {
1480 // An exit block is a block without any successors
1481 bool HasSucc = !llvm::children<const BlockT *>(&BB).empty();
1482 if (!HasSucc && Reachable.count(&BB)) {
1483 Queue.push(&BB);
1484 InverseReachable.insert(&BB);
1485 }
1486 }
1487 while (!Queue.empty()) {
1488 const BlockT *SrcBB = Queue.front();
1489 Queue.pop();
1490 for (const BlockT *DstBB : inverse_children<const BlockT *>(SrcBB)) {
1491 auto EP = BPI->getEdgeProbability(DstBB, SrcBB);
1492 if (EP.isZero())
1493 continue;
1494 if (InverseReachable.insert(DstBB).second)
1495 Queue.push(DstBB);
1496 }
1497 }
1498
1499 // Collect the result
1500 Blocks.reserve(F->size());
1501 for (const BlockT &BB : *F) {
1502 if (Reachable.count(&BB) && InverseReachable.count(&BB)) {
1503 Blocks.push_back(&BB);
1504 }
1505 }
1506}
1507
1508template <class BT>
1509void BlockFrequencyInfoImpl<BT>::initTransitionProbabilities(
1510 const std::vector<const BlockT *> &Blocks,
1511 const DenseMap<const BlockT *, size_t> &BlockIndex,
1512 ProbMatrixType &ProbMatrix) const {
1513 const size_t NumBlocks = Blocks.size();
1514 auto Succs = std::vector<std::vector<std::pair<size_t, Scaled64>>>(NumBlocks);
1515 auto SumProb = std::vector<Scaled64>(NumBlocks);
1516
1517 // Find unique successors and corresponding probabilities for every block
1518 for (size_t Src = 0; Src < NumBlocks; Src++) {
1519 const BlockT *BB = Blocks[Src];
1521 for (auto It : enumerate(children<const BlockT *>(BB))) {
1522 const BlockT *SI = It.value();
1523 // Ignore cold blocks
1524 auto BlockIndexIt = BlockIndex.find(SI);
1525 if (BlockIndexIt == BlockIndex.end())
1526 continue;
1527 // Ignore parallel edges between BB and SI blocks
1528 if (!UniqueSuccs.insert(SI).second)
1529 continue;
1530 // Ignore jumps with zero probability
1531 auto EP = BPI->getEdgeProbability(BB, It.index());
1532 if (EP.isZero())
1533 continue;
1534
1535 auto EdgeProb =
1536 Scaled64::getFraction(EP.getNumerator(), EP.getDenominator());
1537 size_t Dst = BlockIndexIt->second;
1538 Succs[Src].push_back(std::make_pair(Dst, EdgeProb));
1539 SumProb[Src] += EdgeProb;
1540 }
1541 }
1542
1543 // Add transitions for every jump with positive branch probability
1544 ProbMatrix = ProbMatrixType(NumBlocks);
1545 for (size_t Src = 0; Src < NumBlocks; Src++) {
1546 // Ignore blocks w/o successors
1547 if (Succs[Src].empty())
1548 continue;
1549
1550 assert(!SumProb[Src].isZero() && "Zero sum probability of non-exit block");
1551 for (auto &Jump : Succs[Src]) {
1552 size_t Dst = Jump.first;
1553 Scaled64 Prob = Jump.second;
1554 ProbMatrix[Dst].push_back(std::make_pair(Src, Prob / SumProb[Src]));
1555 }
1556 }
1557
1558 // Add transitions from sinks to the source
1559 size_t EntryIdx = BlockIndex.find(&F->front())->second;
1560 for (size_t Src = 0; Src < NumBlocks; Src++) {
1561 if (Succs[Src].empty()) {
1562 ProbMatrix[EntryIdx].push_back(std::make_pair(Src, Scaled64::getOne()));
1563 }
1564 }
1565}
1566
1567#ifndef NDEBUG
1568template <class BT>
1569BlockFrequencyInfoImplBase::Scaled64 BlockFrequencyInfoImpl<BT>::discrepancy(
1570 const ProbMatrixType &ProbMatrix, const std::vector<Scaled64> &Freq) const {
1571 assert(Freq[0] > 0 && "Incorrectly computed frequency of the entry block");
1572 Scaled64 Discrepancy;
1573 for (size_t I = 0; I < ProbMatrix.size(); I++) {
1574 Scaled64 Sum;
1575 for (const auto &Jump : ProbMatrix[I]) {
1576 Sum += Freq[Jump.first] * Jump.second;
1577 }
1578 Discrepancy += Freq[I] >= Sum ? Freq[I] - Sum : Sum - Freq[I];
1579 }
1580 // Normalizing by the frequency of the entry block
1581 return Discrepancy / Freq[0];
1582}
1583#endif
1584
1585template <class BT>
1586void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1587 LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1588 LLVM_DEBUG(dbgs() << "analyze-irreducible-in-";
1589 if (OuterLoop) dbgs()
1590 << "loop: " << getLoopName(*OuterLoop) << "\n";
1591 else dbgs() << "function\n");
1592
1593 using namespace bfi_detail;
1594
1595 auto addBlockEdges = [&](IrreducibleGraph &G, IrreducibleGraph::IrrNode &Irr,
1596 const LoopData *OuterLoop) {
1597 const BlockT *BB = RPOT[Irr.Node.Index];
1598 for (const auto *Succ : children<const BlockT *>(BB))
1599 G.addEdge(Irr, getNode(Succ), OuterLoop);
1600 };
1601 IrreducibleGraph G(*this, OuterLoop, addBlockEdges);
1602
1603 for (auto &L : analyzeIrreducible(G, OuterLoop, Insert))
1604 computeMassInLoop(L);
1605
1606 if (!OuterLoop)
1607 return;
1608 updateLoopWithIrreducible(*OuterLoop);
1609}
1610
1611// A helper function that converts a branch probability into weight.
1613 return Prob.getNumerator();
1614}
1615
1616template <class BT>
1617bool
1618BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1619 const BlockNode &Node) {
1620 LLVM_DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1621 // Calculate probability for successors.
1622 Distribution Dist;
1623 if (auto *Loop = Working[Node.Index].getPackagedLoop()) {
1624 assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop");
1625 if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
1626 // Irreducible backedge.
1627 return false;
1628 } else {
1629 const BlockT *BB = getBlock(Node);
1630 for (auto It : enumerate(children<const BlockT *>(BB)))
1631 if (!addToDist(
1632 Dist, OuterLoop, Node, getNode(It.value()),
1633 getWeightFromBranchProb(BPI->getEdgeProbability(BB, It.index()))))
1634 // Irreducible backedge.
1635 return false;
1636 }
1637
1638 // Distribute mass to successors, saving exit and backedge data in the
1639 // loop header.
1640 distributeMass(Node, OuterLoop, Dist);
1641 return true;
1642}
1643
1644template <class BT>
1646 if (!F)
1647 return OS;
1648 OS << "block-frequency-info: " << F->getName() << "\n";
1649 for (const BlockT &BB : *F) {
1650 OS << " - " << bfi_detail::getBlockName(&BB) << ": float = ";
1651 getFloatingBlockFreq(&BB).print(OS, 5)
1652 << ", int = " << getBlockFreq(&BB).getFrequency();
1653 if (std::optional<uint64_t> ProfileCount =
1655 F->getFunction(), getNode(&BB)))
1656 OS << ", count = " << *ProfileCount;
1657 if (std::optional<uint64_t> IrrLoopHeaderWeight =
1658 BB.getIrrLoopHeaderWeight())
1659 OS << ", irr_loop_header_weight = " << *IrrLoopHeaderWeight;
1660 OS << "\n";
1661 }
1662
1663 // Add an extra newline for readability.
1664 OS << "\n";
1665 return OS;
1666}
1667
1668template <class BT>
1671 bool Match = true;
1672 // Gather blocks for numbers so that we can print names and determine whether
1673 // they still exist.
1676 for (const auto &BB : *F)
1677 Blocks[GraphTraits<const BlockT *>::getNumber(&BB)] = &BB;
1678
1679 size_t MinSize = std::min(Nodes.size(), Other.Nodes.size());
1680 for (size_t i = 0; i < MinSize; ++i) {
1681 if (!Blocks[i])
1682 continue; // Block got deleted in the mean time, ignore.
1683 if (Nodes[i].isValid() != Other.Nodes[i].isValid()) {
1684 Match = false;
1685 dbgs() << "Block " << bfi_detail::getBlockName(Blocks[i])
1686 << " existence mismatch.\n";
1687 } else if (Nodes[i].isValid()) {
1688 const auto &Freq = Freqs[Nodes[i].Index];
1689 const auto &OtherFreq = Other.Freqs[Other.Nodes[i].Index];
1690 if (Freq.Integer != OtherFreq.Integer) {
1691 Match = false;
1692 dbgs() << "Freq mismatch: " << bfi_detail::getBlockName(Blocks[i])
1693 << " " << Freq.Integer << " vs " << OtherFreq.Integer << "\n";
1694 }
1695 }
1696 }
1697 // Block with higher numbers must not exist in either state.
1698 for (size_t i = MinSize; i < Nodes.size(); ++i) {
1699 if (Nodes[i].isValid()) {
1700 Match = false;
1701 dbgs() << "Block " << bfi_detail::getBlockName(Blocks[i])
1702 << " existence mismatch.\n";
1703 }
1704 }
1705 for (size_t i = MinSize; i < Other.Nodes.size(); ++i) {
1706 if (Other.Nodes[i].isValid()) {
1707 Match = false;
1708 dbgs() << "Block " << bfi_detail::getBlockName(Blocks[i])
1709 << " existence mismatch.\n";
1710 }
1711 }
1712
1713 if (!Match) {
1714 dbgs() << "This\n";
1715 print(dbgs());
1716 dbgs() << "Other\n";
1717 Other.print(dbgs());
1718 }
1719 assert(Match && "BFI mismatch");
1720}
1721
1722// Graph trait base class for block frequency information graph
1723// viewer.
1724
1726
1727template <class BlockFrequencyInfoT, class BranchProbabilityInfoT>
1730 using NodeRef = typename GTraits::NodeRef;
1731 using EdgeIter = typename GTraits::ChildIteratorType;
1732 using NodeIter = typename GTraits::nodes_iterator;
1733
1735
1738
1739 static StringRef getGraphName(const BlockFrequencyInfoT *G) {
1740 return G->getFunction()->getName();
1741 }
1742
1743 std::string getNodeAttributes(NodeRef Node, const BlockFrequencyInfoT *Graph,
1744 unsigned HotPercentThreshold = 0) {
1745 std::string Result;
1746 if (!HotPercentThreshold)
1747 return Result;
1748
1749 // Compute MaxFrequency on the fly:
1750 if (!MaxFrequency) {
1751 for (NodeIter I = GTraits::nodes_begin(Graph),
1752 E = GTraits::nodes_end(Graph);
1753 I != E; ++I) {
1754 NodeRef N = *I;
1755 MaxFrequency =
1756 std::max(MaxFrequency, Graph->getBlockFreq(N).getFrequency());
1757 }
1758 }
1759 BlockFrequency Freq = Graph->getBlockFreq(Node);
1760 BlockFrequency HotFreq =
1762 BranchProbability::getBranchProbability(HotPercentThreshold, 100));
1763
1764 if (Freq < HotFreq)
1765 return Result;
1766
1767 raw_string_ostream(Result) << "color=\"red\"";
1768 return Result;
1769 }
1770
1771 std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfoT *Graph,
1772 GVDAGType GType, int layout_order = -1) {
1773 std::string Result;
1774 raw_string_ostream OS(Result);
1775
1776 if (layout_order != -1)
1777 OS << Node->getName() << "[" << layout_order << "] : ";
1778 else
1779 OS << Node->getName() << " : ";
1780 switch (GType) {
1781 case GVDT_Fraction:
1782 OS << printBlockFreq(*Graph, *Node);
1783 break;
1784 case GVDT_Integer:
1785 OS << Graph->getBlockFreq(Node).getFrequency();
1786 break;
1787 case GVDT_Count: {
1788 auto Count = Graph->getBlockProfileCount(Node);
1789 if (Count)
1790 OS << *Count;
1791 else
1792 OS << "Unknown";
1793 break;
1794 }
1795 case GVDT_None:
1796 llvm_unreachable("If we are not supposed to render a graph we should "
1797 "never reach this point.");
1798 }
1799 return Result;
1800 }
1801
1803 const BlockFrequencyInfoT *BFI,
1804 const BranchProbabilityInfoT *BPI,
1805 unsigned HotPercentThreshold = 0) {
1806 std::string Str;
1807 if (!BPI)
1808 return Str;
1809
1810 unsigned SuccIdx = std::distance(succ_begin(Node), EI);
1811 BranchProbability BP = BPI->getEdgeProbability(Node, SuccIdx);
1812 uint32_t N = BP.getNumerator();
1813 uint32_t D = BP.getDenominator();
1814 double Percent = 100.0 * N / D;
1815 raw_string_ostream OS(Str);
1816 OS << format("label=\"%.1f%%\"", Percent);
1817
1818 if (HotPercentThreshold) {
1819 BlockFrequency EFreq = BFI->getBlockFreq(Node) * BP;
1821 BranchProbability(HotPercentThreshold, 100);
1822
1823 if (EFreq >= HotFreq)
1824 OS << ",color=\"red\"";
1825 }
1826 return Str;
1827 }
1828};
1829
1830} // end namespace llvm
1831
1832#undef DEBUG_TYPE
1833
1834#endif // LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
This file implements the BitVector class.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
Hexagon Hardware Loops
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
Branch Probability Basic Block static false std::string getBlockName(const MachineBasicBlock *BB)
Helper to print the name of a MBB.
#define P(N)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the SparseBitVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for BlockFrequencyInfoImpl.
std::vector< WorkingData > Working
Loop data: see initializeLoops().
virtual ~BlockFrequencyInfoImplBase()=default
Virtual destructor.
std::list< LoopData > Loops
Indexed information about loops.
bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist)
Add all edges out of a packaged loop to the distribution.
std::string getLoopName(const LoopData &Loop) const
bool isIrrLoopHeader(const BlockNode &Node)
void computeLoopScale(LoopData &Loop)
Compute the loop scale for a loop.
void packageLoop(LoopData &Loop)
Package up a loop.
virtual raw_ostream & print(raw_ostream &OS) const
virtual std::string getBlockName(const BlockNode &Node) const
void finalizeMetrics()
Finalize frequency metrics.
void setBlockFreq(const BlockNode &Node, BlockFrequency Freq)
void updateLoopWithIrreducible(LoopData &OuterLoop)
Update a loop after packaging irreducible SCCs inside of it.
std::optional< uint64_t > getBlockProfileCount(const Function &F, const BlockNode &Node, bool AllowSynthetic=false) const
BlockFrequency getBlockFreq(const BlockNode &Node) const
void distributeIrrLoopHeaderMass(Distribution &Dist)
iterator_range< std::list< LoopData >::iterator > analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop, std::list< LoopData >::iterator Insert)
Analyze irreducible SCCs.
bool addToDist(Distribution &Dist, const LoopData *OuterLoop, const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight)
Add an edge to the distribution.
std::optional< uint64_t > getProfileCountFromFreq(const Function &F, BlockFrequency Freq, bool AllowSynthetic=false) const
Scaled64 getFloatingBlockFreq(const BlockNode &Node) const
void distributeMass(const BlockNode &Source, LoopData *OuterLoop, Distribution &Dist)
Distribute mass according to a distribution.
SparseBitVector IsIrrLoopHeader
Whether each block is an irreducible loop header.
std::vector< FrequencyData > Freqs
Data about each block. This is used downstream.
void adjustLoopHeaderMass(LoopData &Loop)
Adjust the mass of all headers in an irreducible loop.
std::optional< uint64_t > getBlockProfileCount(const Function &F, const BlockT *BB, bool AllowSynthetic=false) const
const BranchProbabilityInfoT & getBPI() const
const FunctionT * getFunction() const
void verifyMatch(BlockFrequencyInfoImpl< BT > &Other) const
Scaled64 getFloatingBlockFreq(const BlockT *BB) const
std::optional< uint64_t > getProfileCountFromFreq(const Function &F, BlockFrequency Freq, bool AllowSynthetic=false) const
void calculate(const FunctionT &F, const BranchProbabilityInfoT &BPI, const LoopInfoT &LI)
void setBlockFreq(const BlockT *BB, BlockFrequency Freq)
raw_ostream & print(raw_ostream &OS) const override
Print the frequencies for the current function.
BlockFrequency getBlockFreq(const BlockT *BB) const
Analysis providing branch probability information.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static uint32_t getDenominator()
uint32_t getNumerator() const
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
BlockT * getHeader() const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Simple representation of a scaled number.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
typename SuperClass::const_iterator const_iterator
void resize(size_type N)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:222
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
bool operator<(BlockMass X) const
bool operator>(BlockMass X) const
raw_ostream & print(raw_ostream &OS) const
bool operator==(BlockMass X) const
BlockMass & operator-=(BlockMass X)
Subtract another mass.
bool operator<=(BlockMass X) const
BlockMass & operator*=(BranchProbability P)
bool operator!=(BlockMass X) const
BlockMass & operator+=(BlockMass X)
Add another mass.
bool operator>=(BlockMass X) const
ScaledNumber< uint64_t > toScaled() const
Convert to scaled number.
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
Definition DenseSet.h:96
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
std::string getBlockName(const BlockT *BB)
Get the name of a MachineBasicBlock.
BlockMass operator*(BlockMass L, BranchProbability R)
BlockMass operator+(BlockMass L, BlockMass R)
raw_ostream & operator<<(raw_ostream &OS, BlockMass X)
BlockMass operator-(BlockMass L, BlockMass R)
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
bool empty() const
Definition BasicBlock.h:101
This is an optimization pass for GlobalISel generic memory operations.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
uint32_t getWeightFromBranchProb(const BranchProbability Prob)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
llvm::cl::opt< unsigned > IterativeBFIMaxIterationsPerBlock
llvm::cl::opt< bool > UseIterativeBFIInference
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
Function::ProfileCount ProfileCount
auto post_order(const T &G)
Post-order traversal of a graph.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
llvm::cl::opt< bool > CheckBFIUnknownBlockQueries
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
@ Other
Any other memory.
Definition ModRef.h:68
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
llvm::cl::opt< double > IterativeBFIPrecision
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
#define N
GraphTraits< BlockFrequencyInfoT * > GTraits
std::string getNodeAttributes(NodeRef Node, const BlockFrequencyInfoT *Graph, unsigned HotPercentThreshold=0)
typename GTraits::nodes_iterator NodeIter
typename GTraits::NodeRef NodeRef
typename GTraits::ChildIteratorType EdgeIter
std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfoT *Graph, GVDAGType GType, int layout_order=-1)
std::string getEdgeAttributes(NodeRef Node, EdgeIter EI, const BlockFrequencyInfoT *BFI, const BranchProbabilityInfoT *BPI, unsigned HotPercentThreshold=0)
BFIDOTGraphTraitsBase(bool isSimple=false)
static StringRef getGraphName(const BlockFrequencyInfoT *G)
Distribution of unscaled probability weight.
void addBackedge(const BlockNode &Node, uint64_t Amount)
WeightList Weights
Individual successor weights.
void addExit(const BlockNode &Node, uint64_t Amount)
void addLocal(const BlockNode &Node, uint64_t Amount)
SmallVector< std::pair< BlockNode, BlockMass >, 4 > ExitMap
LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther, It2 LastOther)
ExitMap Exits
Successor edges (and weights).
bool IsPackaged
Whether this has been packaged.
LoopData(LoopData *Parent, const BlockNode &Header)
NodeList::const_iterator members_begin() const
NodeList Nodes
Header and the members of the loop.
HeaderMassList BackedgeMass
Mass returned to each loop header.
HeaderMassList::difference_type getHeaderIndex(const BlockNode &B)
iterator_range< NodeList::const_iterator > members() const
Weight(DistType Type, BlockNode TargetNode, uint64_t Amount)
bool isPackaged() const
Has ContainingLoop been packaged up?
BlockMass Mass
Mass distribution from the entry block.
BlockMass & getMass()
Get the appropriate mass for a node.
bool isAPackage() const
Has Loop been packaged up?
LoopData * Loop
The loop this block is inside.
BlockNode getResolvedNode() const
Resolve a node to its representative.
bool isADoublePackage() const
Has Loop been packaged up twice?
DefaultDOTGraphTraits(bool simple=false)
static nodes_iterator nodes_end(const BlockFrequencyInfo *G)
static nodes_iterator nodes_begin(const BlockFrequencyInfo *G)
typename BlockFrequencyInfoT *::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:95
std::deque< const IrrNode * >::const_iterator iterator
Graph of irreducible control flow.
IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
Construct an explicit graph containing irreducible control flow.
void addEdge(IrrNode &Irr, const BlockNode &Succ, const BFIBase::LoopData *OuterLoop)
void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
SmallDenseMap< uint32_t, IrrNode *, 4 > Lookup
void initialize(const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
void addNodesInLoop(const BFIBase::LoopData &OuterLoop)