1//==- BlockFrequencyInfoImpl.h - Block Frequency Implementation -*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Shared implementation of BlockFrequency for IR and Machine Instructions.
11// See the documentation below for BlockFrequencyInfoImpl for details.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
16#define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
17
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/GraphTraits.h"
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/PostOrderIterator.h"
22#include "llvm/ADT/iterator_range.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/Support/BlockFrequency.h"
25#include "llvm/Support/BranchProbability.h"
26#include "llvm/Support/DOTGraphTraits.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/Format.h"
29#include "llvm/Support/ScaledNumber.h"
30#include "llvm/Support/raw_ostream.h"
31#include <deque>
32#include <list>
33#include <string>
34#include <vector>
35
36#define DEBUG_TYPE "block-freq"
37
38namespace llvm {
39
40class BasicBlock;
41class BranchProbabilityInfo;
42class Function;
43class Loop;
44class LoopInfo;
45class MachineBasicBlock;
46class MachineBranchProbabilityInfo;
47class MachineFunction;
48class MachineLoop;
49class MachineLoopInfo;
50
51namespace bfi_detail {
52
53struct IrreducibleGraph;
54
55// This is part of a workaround for a GCC 4.7 crash on lambdas.
56template <class BT> struct BlockEdgesAdder;
57
58/// \brief Mass of a block.
59///
60/// This class implements a sort of fixed-point fraction always between 0.0 and
61/// 1.0.  getMass() == UINT64_MAX indicates a value of 1.0.
62///
63/// Masses can be added and subtracted.  Simple saturation arithmetic is used,
64/// so arithmetic operations never overflow or underflow.
65///
66/// Masses can be multiplied.  Multiplication treats full mass as 1.0 and uses
67/// an inexpensive floating-point algorithm that's off-by-one (almost, but not
68/// quite, maximum precision).
69///
70/// Masses can be scaled by \a BranchProbability at maximum precision.
71class BlockMass {
72  uint64_t Mass;
73
74public:
75  BlockMass() : Mass(0) {}
76  explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
77
78  static BlockMass getEmpty() { return BlockMass(); }
79  static BlockMass getFull() { return BlockMass(UINT64_MAX); }
80
81  uint64_t getMass() const { return Mass; }
82
83  bool isFull() const { return Mass == UINT64_MAX; }
84  bool isEmpty() const { return !Mass; }
85
86  bool operator!() const { return isEmpty(); }
87
88  /// \brief Add another mass.
89  ///
90  /// Adds another mass, saturating at \a isFull() rather than overflowing.
91  BlockMass &operator+=(BlockMass X) {
92    uint64_t Sum = Mass + X.Mass;
93    Mass = Sum < Mass ? UINT64_MAX : Sum;
94    return *this;
95  }
96
97  /// \brief Subtract another mass.
98  ///
99  /// Subtracts another mass, saturating at \a isEmpty() rather than
100  /// undeflowing.
101  BlockMass &operator-=(BlockMass X) {
102    uint64_t Diff = Mass - X.Mass;
103    Mass = Diff > Mass ? 0 : Diff;
104    return *this;
105  }
106
107  BlockMass &operator*=(BranchProbability P) {
108    Mass = P.scale(Mass);
109    return *this;
110  }
111
112  bool operator==(BlockMass X) const { return Mass == X.Mass; }
113  bool operator!=(BlockMass X) const { return Mass != X.Mass; }
114  bool operator<=(BlockMass X) const { return Mass <= X.Mass; }
115  bool operator>=(BlockMass X) const { return Mass >= X.Mass; }
116  bool operator<(BlockMass X) const { return Mass < X.Mass; }
117  bool operator>(BlockMass X) const { return Mass > X.Mass; }
118
119  /// \brief Convert to scaled number.
120  ///
121  /// Convert to \a ScaledNumber.  \a isFull() gives 1.0, while \a isEmpty()
122  /// gives slightly above 0.0.
123  ScaledNumber<uint64_t> toScaled() const;
124
125  void dump() const;
126  raw_ostream &print(raw_ostream &OS) const;
127};
128
129inline BlockMass operator+(BlockMass L, BlockMass R) {
130  return BlockMass(L) += R;
131}
132inline BlockMass operator-(BlockMass L, BlockMass R) {
133  return BlockMass(L) -= R;
134}
135inline BlockMass operator*(BlockMass L, BranchProbability R) {
136  return BlockMass(L) *= R;
137}
138inline BlockMass operator*(BranchProbability L, BlockMass R) {
139  return BlockMass(R) *= L;
140}
141
142inline raw_ostream &operator<<(raw_ostream &OS, BlockMass X) {
143  return X.print(OS);
144}
145
146} // end namespace bfi_detail
147
148template <> struct isPodLike<bfi_detail::BlockMass> {
149  static const bool value = true;
150};
151
152/// \brief Base class for BlockFrequencyInfoImpl
153///
154/// BlockFrequencyInfoImplBase has supporting data structures and some
155/// algorithms for BlockFrequencyInfoImplBase.  Only algorithms that depend on
156/// the block type (or that call such algorithms) are skipped here.
157///
158/// Nevertheless, the majority of the overall algorithm documention lives with
159/// BlockFrequencyInfoImpl.  See there for details.
160class BlockFrequencyInfoImplBase {
161public:
162  typedef ScaledNumber<uint64_t> Scaled64;
163  typedef bfi_detail::BlockMass BlockMass;
164
165  /// \brief Representative of a block.
166  ///
167  /// This is a simple wrapper around an index into the reverse-post-order
168  /// traversal of the blocks.
169  ///
170  /// Unlike a block pointer, its order has meaning (location in the
171  /// topological sort) and it's class is the same regardless of block type.
172  struct BlockNode {
173    typedef uint32_t IndexType;
174    IndexType Index;
175
176    bool operator==(const BlockNode &X) const { return Index == X.Index; }
177    bool operator!=(const BlockNode &X) const { return Index != X.Index; }
178    bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
179    bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
180    bool operator<(const BlockNode &X) const { return Index < X.Index; }
181    bool operator>(const BlockNode &X) const { return Index > X.Index; }
182
183    BlockNode() : Index(UINT32_MAX) {}
184    BlockNode(IndexType Index) : Index(Index) {}
185
186    bool isValid() const { return Index <= getMaxIndex(); }
187    static size_t getMaxIndex() { return UINT32_MAX - 1; }
188  };
189
190  /// \brief Stats about a block itself.
191  struct FrequencyData {
192    Scaled64 Scaled;
193    uint64_t Integer;
194  };
195
196  /// \brief Data about a loop.
197  ///
198  /// Contains the data necessary to represent a loop as a pseudo-node once it's
199  /// packaged.
200  struct LoopData {
201    typedef SmallVector<std::pair<BlockNode, BlockMass>, 4> ExitMap;
202    typedef SmallVector<BlockNode, 4> NodeList;
203    typedef SmallVector<BlockMass, 1> HeaderMassList;
204    LoopData *Parent;            ///< The parent loop.
205    bool IsPackaged;             ///< Whether this has been packaged.
206    uint32_t NumHeaders;         ///< Number of headers.
207    ExitMap Exits;               ///< Successor edges (and weights).
208    NodeList Nodes;              ///< Header and the members of the loop.
209    HeaderMassList BackedgeMass; ///< Mass returned to each loop header.
210    BlockMass Mass;
211    Scaled64 Scale;
212
213    LoopData(LoopData *Parent, const BlockNode &Header)
214        : Parent(Parent), IsPackaged(false), NumHeaders(1), Nodes(1, Header),
215          BackedgeMass(1) {}
216    template <class It1, class It2>
217    LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther,
218             It2 LastOther)
219        : Parent(Parent), IsPackaged(false), Nodes(FirstHeader, LastHeader) {
220      NumHeaders = Nodes.size();
221      Nodes.insert(Nodes.end(), FirstOther, LastOther);
222      BackedgeMass.resize(NumHeaders);
223    }
224    bool isHeader(const BlockNode &Node) const {
225      if (isIrreducible())
226        return std::binary_search(Nodes.begin(), Nodes.begin() + NumHeaders,
227                                  Node);
228      return Node == Nodes[0];
229    }
230    BlockNode getHeader() const { return Nodes[0]; }
231    bool isIrreducible() const { return NumHeaders > 1; }
232
233    HeaderMassList::difference_type getHeaderIndex(const BlockNode &B) {
234      assert(isHeader(B) && "this is only valid on loop header blocks");
235      if (isIrreducible())
236        return std::lower_bound(Nodes.begin(), Nodes.begin() + NumHeaders, B) -
237               Nodes.begin();
238      return 0;
239    }
240
241    NodeList::const_iterator members_begin() const {
242      return Nodes.begin() + NumHeaders;
243    }
244    NodeList::const_iterator members_end() const { return Nodes.end(); }
245    iterator_range<NodeList::const_iterator> members() const {
246      return make_range(members_begin(), members_end());
247    }
248  };
249
250  /// \brief Index of loop information.
251  struct WorkingData {
252    BlockNode Node; ///< This node.
253    LoopData *Loop; ///< The loop this block is inside.
254    BlockMass Mass; ///< Mass distribution from the entry block.
255
256    WorkingData(const BlockNode &Node) : Node(Node), Loop(nullptr) {}
257
258    bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
259    bool isDoubleLoopHeader() const {
260      return isLoopHeader() && Loop->Parent && Loop->Parent->isIrreducible() &&
261             Loop->Parent->isHeader(Node);
262    }
263
264    LoopData *getContainingLoop() const {
265      if (!isLoopHeader())
266        return Loop;
267      if (!isDoubleLoopHeader())
268        return Loop->Parent;
269      return Loop->Parent->Parent;
270    }
271
272    /// \brief Resolve a node to its representative.
273    ///
274    /// Get the node currently representing Node, which could be a containing
275    /// loop.
276    ///
277    /// This function should only be called when distributing mass.  As long as
278    /// there are no irreducible edges to Node, then it will have complexity
279    /// O(1) in this context.
280    ///
281    /// In general, the complexity is O(L), where L is the number of loop
282    /// headers Node has been packaged into.  Since this method is called in
283    /// the context of distributing mass, L will be the number of loop headers
284    /// an early exit edge jumps out of.
285    BlockNode getResolvedNode() const {
286      auto L = getPackagedLoop();
287      return L ? L->getHeader() : Node;
288    }
289    LoopData *getPackagedLoop() const {
290      if (!Loop || !Loop->IsPackaged)
291        return nullptr;
292      auto L = Loop;
293      while (L->Parent && L->Parent->IsPackaged)
294        L = L->Parent;
295      return L;
296    }
297
298    /// \brief Get the appropriate mass for a node.
299    ///
300    /// Get appropriate mass for Node.  If Node is a loop-header (whose loop
301    /// has been packaged), returns the mass of its pseudo-node.  If it's a
302    /// node inside a packaged loop, it returns the loop's mass.
303    BlockMass &getMass() {
304      if (!isAPackage())
305        return Mass;
306      if (!isADoublePackage())
307        return Loop->Mass;
308      return Loop->Parent->Mass;
309    }
310
311    /// \brief Has ContainingLoop been packaged up?
312    bool isPackaged() const { return getResolvedNode() != Node; }
313    /// \brief Has Loop been packaged up?
314    bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; }
315    /// \brief Has Loop been packaged up twice?
316    bool isADoublePackage() const {
317      return isDoubleLoopHeader() && Loop->Parent->IsPackaged;
318    }
319  };
320
321  /// \brief Unscaled probability weight.
322  ///
323  /// Probability weight for an edge in the graph (including the
324  /// successor/target node).
325  ///
326  /// All edges in the original function are 32-bit.  However, exit edges from
327  /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
328  /// space in general.
329  ///
330  /// In addition to the raw weight amount, Weight stores the type of the edge
331  /// in the current context (i.e., the context of the loop being processed).
332  /// Is this a local edge within the loop, an exit from the loop, or a
333  /// backedge to the loop header?
334  struct Weight {
335    enum DistType { Local, Exit, Backedge };
336    DistType Type;
337    BlockNode TargetNode;
338    uint64_t Amount;
339    Weight() : Type(Local), Amount(0) {}
340    Weight(DistType Type, BlockNode TargetNode, uint64_t Amount)
341        : Type(Type), TargetNode(TargetNode), Amount(Amount) {}
342  };
343
344  /// \brief Distribution of unscaled probability weight.
345  ///
346  /// Distribution of unscaled probability weight to a set of successors.
347  ///
348  /// This class collates the successor edge weights for later processing.
349  ///
350  /// \a DidOverflow indicates whether \a Total did overflow while adding to
351  /// the distribution.  It should never overflow twice.
352  struct Distribution {
353    typedef SmallVector<Weight, 4> WeightList;
354    WeightList Weights;    ///< Individual successor weights.
355    uint64_t Total;        ///< Sum of all weights.
356    bool DidOverflow;      ///< Whether \a Total did overflow.
357
358    Distribution() : Total(0), DidOverflow(false) {}
359    void addLocal(const BlockNode &Node, uint64_t Amount) {
360      add(Node, Amount, Weight::Local);
361    }
362    void addExit(const BlockNode &Node, uint64_t Amount) {
363      add(Node, Amount, Weight::Exit);
364    }
365    void addBackedge(const BlockNode &Node, uint64_t Amount) {
366      add(Node, Amount, Weight::Backedge);
367    }
368
369    /// \brief Normalize the distribution.
370    ///
371    /// Combines multiple edges to the same \a Weight::TargetNode and scales
372    /// down so that \a Total fits into 32-bits.
373    ///
374    /// This is linear in the size of \a Weights.  For the vast majority of
375    /// cases, adjacent edge weights are combined by sorting WeightList and
376    /// combining adjacent weights.  However, for very large edge lists an
377    /// auxiliary hash table is used.
378    void normalize();
379
380  private:
381    void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
382  };
383
384  /// \brief Data about each block.  This is used downstream.
385  std::vector<FrequencyData> Freqs;
386
387  /// \brief Loop data: see initializeLoops().
388  std::vector<WorkingData> Working;
389
390  /// \brief Indexed information about loops.
391  std::list<LoopData> Loops;
392
393  /// \brief Add all edges out of a packaged loop to the distribution.
394  ///
395  /// Adds all edges from LocalLoopHead to Dist.  Calls addToDist() to add each
396  /// successor edge.
397  ///
398  /// \return \c true unless there's an irreducible backedge.
399  bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop,
400                               Distribution &Dist);
401
402  /// \brief Add an edge to the distribution.
403  ///
404  /// Adds an edge to Succ to Dist.  If \c LoopHead.isValid(), then whether the
405  /// edge is local/exit/backedge is in the context of LoopHead.  Otherwise,
406  /// every edge should be a local edge (since all the loops are packaged up).
407  ///
408  /// \return \c true unless aborted due to an irreducible backedge.
409  bool addToDist(Distribution &Dist, const LoopData *OuterLoop,
410                 const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
411
412  LoopData &getLoopPackage(const BlockNode &Head) {
413    assert(Head.Index < Working.size());
414    assert(Working[Head.Index].isLoopHeader());
415    return *Working[Head.Index].Loop;
416  }
417
418  /// \brief Analyze irreducible SCCs.
419  ///
420  /// Separate irreducible SCCs from \c G, which is an explict graph of \c
421  /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr).
422  /// Insert them into \a Loops before \c Insert.
423  ///
424  /// \return the \c LoopData nodes representing the irreducible SCCs.
425  iterator_range<std::list<LoopData>::iterator>
426  analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop,
427                     std::list<LoopData>::iterator Insert);
428
429  /// \brief Update a loop after packaging irreducible SCCs inside of it.
430  ///
431  /// Update \c OuterLoop.  Before finding irreducible control flow, it was
432  /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a
433  /// LoopData::BackedgeMass need to be reset.  Also, nodes that were packaged
434  /// up need to be removed from \a OuterLoop::Nodes.
435  void updateLoopWithIrreducible(LoopData &OuterLoop);
436
437  /// \brief Distribute mass according to a distribution.
438  ///
439  /// Distributes the mass in Source according to Dist.  If LoopHead.isValid(),
440  /// backedges and exits are stored in its entry in Loops.
441  ///
442  /// Mass is distributed in parallel from two copies of the source mass.
443  void distributeMass(const BlockNode &Source, LoopData *OuterLoop,
444                      Distribution &Dist);
445
446  /// \brief Compute the loop scale for a loop.
447  void computeLoopScale(LoopData &Loop);
448
449  /// Adjust the mass of all headers in an irreducible loop.
450  ///
451  /// Initially, irreducible loops are assumed to distribute their mass
452  /// equally among its headers. This can lead to wrong frequency estimates
453  /// since some headers may be executed more frequently than others.
454  ///
455  /// This adjusts header mass distribution so it matches the weights of
456  /// the backedges going into each of the loop headers.
457  void adjustLoopHeaderMass(LoopData &Loop);
458
459  /// \brief Package up a loop.
460  void packageLoop(LoopData &Loop);
461
462  /// \brief Unwrap loops.
463  void unwrapLoops();
464
465  /// \brief Finalize frequency metrics.
466  ///
467  /// Calculates final frequencies and cleans up no-longer-needed data
468  /// structures.
469  void finalizeMetrics();
470
471  /// \brief Clear all memory.
472  void clear();
473
474  virtual std::string getBlockName(const BlockNode &Node) const;
475  std::string getLoopName(const LoopData &Loop) const;
476
477  virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
478  void dump() const { print(dbgs()); }
479
480  Scaled64 getFloatingBlockFreq(const BlockNode &Node) const;
481
482  BlockFrequency getBlockFreq(const BlockNode &Node) const;
483  Optional<uint64_t> getBlockProfileCount(const Function &F,
484                                          const BlockNode &Node) const;
485
486  void setBlockFreq(const BlockNode &Node, uint64_t Freq);
487
488  raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
489  raw_ostream &printBlockFreq(raw_ostream &OS,
490                              const BlockFrequency &Freq) const;
491
492  uint64_t getEntryFreq() const {
493    assert(!Freqs.empty());
494    return Freqs[0].Integer;
495  }
496  /// \brief Virtual destructor.
497  ///
498  /// Need a virtual destructor to mask the compiler warning about
499  /// getBlockName().
500  virtual ~BlockFrequencyInfoImplBase() {}
501};
502
503namespace bfi_detail {
504template <class BlockT> struct TypeMap {};
505template <> struct TypeMap<BasicBlock> {
506  typedef BasicBlock BlockT;
507  typedef Function FunctionT;
508  typedef BranchProbabilityInfo BranchProbabilityInfoT;
509  typedef Loop LoopT;
510  typedef LoopInfo LoopInfoT;
511};
512template <> struct TypeMap<MachineBasicBlock> {
513  typedef MachineBasicBlock BlockT;
514  typedef MachineFunction FunctionT;
515  typedef MachineBranchProbabilityInfo BranchProbabilityInfoT;
516  typedef MachineLoop LoopT;
517  typedef MachineLoopInfo LoopInfoT;
518};
519
520/// \brief Get the name of a MachineBasicBlock.
521///
522/// Get the name of a MachineBasicBlock.  It's templated so that including from
523/// CodeGen is unnecessary (that would be a layering issue).
524///
525/// This is used mainly for debug output.  The name is similar to
526/// MachineBasicBlock::getFullName(), but skips the name of the function.
527template <class BlockT> std::string getBlockName(const BlockT *BB) {
528  assert(BB && "Unexpected nullptr");
529  auto MachineName = "BB" + Twine(BB->getNumber());
530  if (BB->getBasicBlock())
531    return (MachineName + "[" + BB->getName() + "]").str();
532  return MachineName.str();
533}
534/// \brief Get the name of a BasicBlock.
535template <> inline std::string getBlockName(const BasicBlock *BB) {
536  assert(BB && "Unexpected nullptr");
537  return BB->getName().str();
538}
539
540/// \brief Graph of irreducible control flow.
541///
542/// This graph is used for determining the SCCs in a loop (or top-level
543/// function) that has irreducible control flow.
544///
545/// During the block frequency algorithm, the local graphs are defined in a
546/// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock
547/// graphs for most edges, but getting others from \a LoopData::ExitMap.  The
548/// latter only has successor information.
549///
550/// \a IrreducibleGraph makes this graph explicit.  It's in a form that can use
551/// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator),
552/// and it explicitly lists predecessors and successors.  The initialization
553/// that relies on \c MachineBasicBlock is defined in the header.
554struct IrreducibleGraph {
555  typedef BlockFrequencyInfoImplBase BFIBase;
556
557  BFIBase &BFI;
558
559  typedef BFIBase::BlockNode BlockNode;
560  struct IrrNode {
561    BlockNode Node;
562    unsigned NumIn;
563    std::deque<const IrrNode *> Edges;
564    IrrNode(const BlockNode &Node) : Node(Node), NumIn(0) {}
565
566    typedef std::deque<const IrrNode *>::const_iterator iterator;
567    iterator pred_begin() const { return Edges.begin(); }
568    iterator succ_begin() const { return Edges.begin() + NumIn; }
569    iterator pred_end() const { return succ_begin(); }
570    iterator succ_end() const { return Edges.end(); }
571  };
572  BlockNode Start;
573  const IrrNode *StartIrr;
574  std::vector<IrrNode> Nodes;
575  SmallDenseMap<uint32_t, IrrNode *, 4> Lookup;
576
577  /// \brief Construct an explicit graph containing irreducible control flow.
578  ///
579  /// Construct an explicit graph of the control flow in \c OuterLoop (or the
580  /// top-level function, if \c OuterLoop is \c nullptr).  Uses \c
581  /// addBlockEdges to add block successors that have not been packaged into
582  /// loops.
583  ///
584  /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected
585  /// user of this.
586  template <class BlockEdgesAdder>
587  IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop,
588                   BlockEdgesAdder addBlockEdges)
589      : BFI(BFI), StartIrr(nullptr) {
590    initialize(OuterLoop, addBlockEdges);
591  }
592
593  template <class BlockEdgesAdder>
594  void initialize(const BFIBase::LoopData *OuterLoop,
595                  BlockEdgesAdder addBlockEdges);
596  void addNodesInLoop(const BFIBase::LoopData &OuterLoop);
597  void addNodesInFunction();
598  void addNode(const BlockNode &Node) {
599    Nodes.emplace_back(Node);
600    BFI.Working[Node.Index].getMass() = BlockMass::getEmpty();
601  }
602  void indexNodes();
603  template <class BlockEdgesAdder>
604  void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop,
605                BlockEdgesAdder addBlockEdges);
606  void addEdge(IrrNode &Irr, const BlockNode &Succ,
607               const BFIBase::LoopData *OuterLoop);
608};
609template <class BlockEdgesAdder>
610void IrreducibleGraph::initialize(const BFIBase::LoopData *OuterLoop,
611                                  BlockEdgesAdder addBlockEdges) {
612  if (OuterLoop) {
613    addNodesInLoop(*OuterLoop);
614    for (auto N : OuterLoop->Nodes)
615      addEdges(N, OuterLoop, addBlockEdges);
616  } else {
617    addNodesInFunction();
618    for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
619      addEdges(Index, OuterLoop, addBlockEdges);
620  }
621  StartIrr = Lookup[Start.Index];
622}
623template <class BlockEdgesAdder>
624void IrreducibleGraph::addEdges(const BlockNode &Node,
625                                const BFIBase::LoopData *OuterLoop,
626                                BlockEdgesAdder addBlockEdges) {
627  auto L = Lookup.find(Node.Index);
628  if (L == Lookup.end())
629    return;
630  IrrNode &Irr = *L->second;
631  const auto &Working = BFI.Working[Node.Index];
632
633  if (Working.isAPackage())
634    for (const auto &I : Working.Loop->Exits)
635      addEdge(Irr, I.first, OuterLoop);
636  else
637    addBlockEdges(*this, Irr, OuterLoop);
638}
639}
640
641/// \brief Shared implementation for block frequency analysis.
642///
643/// This is a shared implementation of BlockFrequencyInfo and
644/// MachineBlockFrequencyInfo, and calculates the relative frequencies of
645/// blocks.
646///
647/// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block,
648/// which is called the header.  A given loop, L, can have sub-loops, which are
649/// loops within the subgraph of L that exclude its header.  (A "trivial" SCC
650/// consists of a single block that does not have a self-edge.)
651///
652/// In addition to loops, this algorithm has limited support for irreducible
653/// SCCs, which are SCCs with multiple entry blocks.  Irreducible SCCs are
654/// discovered on they fly, and modelled as loops with multiple headers.
655///
656/// The headers of irreducible sub-SCCs consist of its entry blocks and all
657/// nodes that are targets of a backedge within it (excluding backedges within
658/// true sub-loops).  Block frequency calculations act as if a block is
659/// inserted that intercepts all the edges to the headers.  All backedges and
660/// entries point to this block.  Its successors are the headers, which split
661/// the frequency evenly.
662///
663/// This algorithm leverages BlockMass and ScaledNumber to maintain precision,
664/// separates mass distribution from loop scaling, and dithers to eliminate
665/// probability mass loss.
666///
667/// The implementation is split between BlockFrequencyInfoImpl, which knows the
668/// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
669/// BlockFrequencyInfoImplBase, which doesn't.  The base class uses \a
670/// BlockNode, a wrapper around a uint32_t.  BlockNode is numbered from 0 in
671/// reverse-post order.  This gives two advantages:  it's easy to compare the
672/// relative ordering of two nodes, and maps keyed on BlockT can be represented
673/// by vectors.
674///
675/// This algorithm is O(V+E), unless there is irreducible control flow, in
676/// which case it's O(V*E) in the worst case.
677///
678/// These are the main stages:
679///
680///  0. Reverse post-order traversal (\a initializeRPOT()).
681///
682///     Run a single post-order traversal and save it (in reverse) in RPOT.
683///     All other stages make use of this ordering.  Save a lookup from BlockT
684///     to BlockNode (the index into RPOT) in Nodes.
685///
686///  1. Loop initialization (\a initializeLoops()).
687///
688///     Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
689///     the algorithm.  In particular, store the immediate members of each loop
690///     in reverse post-order.
691///
692///  2. Calculate mass and scale in loops (\a computeMassInLoops()).
693///
694///     For each loop (bottom-up), distribute mass through the DAG resulting
695///     from ignoring backedges and treating sub-loops as a single pseudo-node.
696///     Track the backedge mass distributed to the loop header, and use it to
697///     calculate the loop scale (number of loop iterations).  Immediate
698///     members that represent sub-loops will already have been visited and
699///     packaged into a pseudo-node.
700///
701///     Distributing mass in a loop is a reverse-post-order traversal through
702///     the loop.  Start by assigning full mass to the Loop header.  For each
703///     node in the loop:
704///
705///         - Fetch and categorize the weight distribution for its successors.
706///           If this is a packaged-subloop, the weight distribution is stored
707///           in \a LoopData::Exits.  Otherwise, fetch it from
708///           BranchProbabilityInfo.
709///
710///         - Each successor is categorized as \a Weight::Local, a local edge
711///           within the current loop, \a Weight::Backedge, a backedge to the
712///           loop header, or \a Weight::Exit, any successor outside the loop.
713///           The weight, the successor, and its category are stored in \a
714///           Distribution.  There can be multiple edges to each successor.
715///
716///         - If there's a backedge to a non-header, there's an irreducible SCC.
717///           The usual flow is temporarily aborted.  \a
718///           computeIrreducibleMass() finds the irreducible SCCs within the
719///           loop, packages them up, and restarts the flow.
720///
721///         - Normalize the distribution:  scale weights down so that their sum
722///           is 32-bits, and coalesce multiple edges to the same node.
723///
724///         - Distribute the mass accordingly, dithering to minimize mass loss,
725///           as described in \a distributeMass().
726///
727///     In the case of irreducible loops, instead of a single loop header,
728///     there will be several. The computation of backedge masses is similar
729///     but instead of having a single backedge mass, there will be one
730///     backedge per loop header. In these cases, each backedge will carry
731///     a mass proportional to the edge weights along the corresponding
732///     path.
733///
734///     At the end of propagation, the full mass assigned to the loop will be
735///     distributed among the loop headers proportionally according to the
736///     mass flowing through their backedges.
737///
738///     Finally, calculate the loop scale from the accumulated backedge mass.
739///
740///  3. Distribute mass in the function (\a computeMassInFunction()).
741///
742///     Finally, distribute mass through the DAG resulting from packaging all
743///     loops in the function.  This uses the same algorithm as distributing
744///     mass in a loop, except that there are no exit or backedge edges.
745///
746///  4. Unpackage loops (\a unwrapLoops()).
747///
748///     Initialize each block's frequency to a floating point representation of
749///     its mass.
750///
751///     Visit loops top-down, scaling the frequencies of its immediate members
752///     by the loop's pseudo-node's frequency.
753///
754///  5. Convert frequencies to a 64-bit range (\a finalizeMetrics()).
755///
756///     Using the min and max frequencies as a guide, translate floating point
757///     frequencies to an appropriate range in uint64_t.
758///
759/// It has some known flaws.
760///
761///   - The model of irreducible control flow is a rough approximation.
762///
763///     Modelling irreducible control flow exactly involves setting up and
764///     solving a group of infinite geometric series.  Such precision is
765///     unlikely to be worthwhile, since most of our algorithms give up on
766///     irreducible control flow anyway.
767///
768///     Nevertheless, we might find that we need to get closer.  Here's a sort
769///     of TODO list for the model with diminishing returns, to be completed as
770///     necessary.
771///
772///       - The headers for the \a LoopData representing an irreducible SCC
773///         include non-entry blocks.  When these extra blocks exist, they
774///         indicate a self-contained irreducible sub-SCC.  We could treat them
775///         as sub-loops, rather than arbitrarily shoving the problematic
776///         blocks into the headers of the main irreducible SCC.
777///
778///       - Entry frequencies are assumed to be evenly split between the
779///         headers of a given irreducible SCC, which is the only option if we
780///         need to compute mass in the SCC before its parent loop.  Instead,
781///         we could partially compute mass in the parent loop, and stop when
782///         we get to the SCC.  Here, we have the correct ratio of entry
783///         masses, which we can use to adjust their relative frequencies.
784///         Compute mass in the SCC, and then continue propagation in the
785///         parent.
786///
787///       - We can propagate mass iteratively through the SCC, for some fixed
788///         number of iterations.  Each iteration starts by assigning the entry
789///         blocks their backedge mass from the prior iteration.  The final
790///         mass for each block (and each exit, and the total backedge mass
791///         used for computing loop scale) is the sum of all iterations.
792///         (Running this until fixed point would "solve" the geometric
793///         series by simulation.)
794template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
795  typedef typename bfi_detail::TypeMap<BT>::BlockT BlockT;
796  typedef typename bfi_detail::TypeMap<BT>::FunctionT FunctionT;
797  typedef typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT
798  BranchProbabilityInfoT;
799  typedef typename bfi_detail::TypeMap<BT>::LoopT LoopT;
800  typedef typename bfi_detail::TypeMap<BT>::LoopInfoT LoopInfoT;
801
802  // This is part of a workaround for a GCC 4.7 crash on lambdas.
803  friend struct bfi_detail::BlockEdgesAdder<BT>;
804
805  typedef GraphTraits<const BlockT *> Successor;
806  typedef GraphTraits<Inverse<const BlockT *>> Predecessor;
807
808  const BranchProbabilityInfoT *BPI;
809  const LoopInfoT *LI;
810  const FunctionT *F;
811
812  // All blocks in reverse postorder.
813  std::vector<const BlockT *> RPOT;
814  DenseMap<const BlockT *, BlockNode> Nodes;
815
816  typedef typename std::vector<const BlockT *>::const_iterator rpot_iterator;
817
818  rpot_iterator rpot_begin() const { return RPOT.begin(); }
819  rpot_iterator rpot_end() const { return RPOT.end(); }
820
821  size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
822
823  BlockNode getNode(const rpot_iterator &I) const {
824    return BlockNode(getIndex(I));
825  }
826  BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB); }
827
828  const BlockT *getBlock(const BlockNode &Node) const {
829    assert(Node.Index < RPOT.size());
830    return RPOT[Node.Index];
831  }
832
833  /// \brief Run (and save) a post-order traversal.
834  ///
835  /// Saves a reverse post-order traversal of all the nodes in \a F.
836  void initializeRPOT();
837
838  /// \brief Initialize loop data.
839  ///
840  /// Build up \a Loops using \a LoopInfo.  \a LoopInfo gives us a mapping from
841  /// each block to the deepest loop it's in, but we need the inverse.  For each
842  /// loop, we store in reverse post-order its "immediate" members, defined as
843  /// the header, the headers of immediate sub-loops, and all other blocks in
844  /// the loop that are not in sub-loops.
845  void initializeLoops();
846
847  /// \brief Propagate to a block's successors.
848  ///
849  /// In the context of distributing mass through \c OuterLoop, divide the mass
850  /// currently assigned to \c Node between its successors.
851  ///
852  /// \return \c true unless there's an irreducible backedge.
853  bool propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node);
854
855  /// \brief Compute mass in a particular loop.
856  ///
857  /// Assign mass to \c Loop's header, and then for each block in \c Loop in
858  /// reverse post-order, distribute mass to its successors.  Only visits nodes
859  /// that have not been packaged into sub-loops.
860  ///
861  /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
862  /// \return \c true unless there's an irreducible backedge.
863  bool computeMassInLoop(LoopData &Loop);
864
865  /// \brief Try to compute mass in the top-level function.
866  ///
867  /// Assign mass to the entry block, and then for each block in reverse
868  /// post-order, distribute mass to its successors.  Skips nodes that have
869  /// been packaged into loops.
870  ///
871  /// \pre \a computeMassInLoops() has been called.
872  /// \return \c true unless there's an irreducible backedge.
873  bool tryToComputeMassInFunction();
874
875  /// \brief Compute mass in (and package up) irreducible SCCs.
876  ///
877  /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front
878  /// of \c Insert), and call \a computeMassInLoop() on each of them.
879  ///
880  /// If \c OuterLoop is \c nullptr, it refers to the top-level function.
881  ///
882  /// \pre \a computeMassInLoop() has been called for each subloop of \c
883  /// OuterLoop.
884  /// \pre \c Insert points at the last loop successfully processed by \a
885  /// computeMassInLoop().
886  /// \pre \c OuterLoop has irreducible SCCs.
887  void computeIrreducibleMass(LoopData *OuterLoop,
888                              std::list<LoopData>::iterator Insert);
889
890  /// \brief Compute mass in all loops.
891  ///
892  /// For each loop bottom-up, call \a computeMassInLoop().
893  ///
894  /// \a computeMassInLoop() aborts (and returns \c false) on loops that
895  /// contain a irreducible sub-SCCs.  Use \a computeIrreducibleMass() and then
896  /// re-enter \a computeMassInLoop().
897  ///
898  /// \post \a computeMassInLoop() has returned \c true for every loop.
899  void computeMassInLoops();
900
901  /// \brief Compute mass in the top-level function.
902  ///
903  /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to
904  /// compute mass in the top-level function.
905  ///
906  /// \post \a tryToComputeMassInFunction() has returned \c true.
907  void computeMassInFunction();
908
909  std::string getBlockName(const BlockNode &Node) const override {
910    return bfi_detail::getBlockName(getBlock(Node));
911  }
912
913public:
914  const FunctionT *getFunction() const { return F; }
915
916  void calculate(const FunctionT &F, const BranchProbabilityInfoT &BPI,
917                 const LoopInfoT &LI);
918  BlockFrequencyInfoImpl() : BPI(nullptr), LI(nullptr), F(nullptr) {}
919
920  using BlockFrequencyInfoImplBase::getEntryFreq;
921  BlockFrequency getBlockFreq(const BlockT *BB) const {
922    return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
923  }
924  Optional<uint64_t> getBlockProfileCount(const Function &F,
925                                          const BlockT *BB) const {
926    return BlockFrequencyInfoImplBase::getBlockProfileCount(F, getNode(BB));
927  }
928  void setBlockFreq(const BlockT *BB, uint64_t Freq);
929  Scaled64 getFloatingBlockFreq(const BlockT *BB) const {
930    return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
931  }
932
933  const BranchProbabilityInfoT &getBPI() const { return *BPI; }
934
935  /// \brief Print the frequencies for the current function.
936  ///
937  /// Prints the frequencies for the blocks in the current function.
938  ///
939  /// Blocks are printed in the natural iteration order of the function, rather
940  /// than reverse post-order.  This provides two advantages:  writing -analyze
941  /// tests is easier (since blocks come out in source order), and even
942  /// unreachable blocks are printed.
943  ///
944  /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
945  /// we need to override it here.
946  raw_ostream &print(raw_ostream &OS) const override;
947  using BlockFrequencyInfoImplBase::dump;
948
949  using BlockFrequencyInfoImplBase::printBlockFreq;
950  raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
951    return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
952  }
953};
954
955template <class BT>
956void BlockFrequencyInfoImpl<BT>::calculate(const FunctionT &F,
957                                           const BranchProbabilityInfoT &BPI,
958                                           const LoopInfoT &LI) {
959  // Save the parameters.
960  this->BPI = &BPI;
961  this->LI = &LI;
962  this->F = &F;
963
964  // Clean up left-over data structures.
965  BlockFrequencyInfoImplBase::clear();
966  RPOT.clear();
967  Nodes.clear();
968
969  // Initialize.
970  DEBUG(dbgs() << "\nblock-frequency: " << F.getName() << "\n================="
971               << std::string(F.getName().size(), '=') << "\n");
972  initializeRPOT();
973  initializeLoops();
974
975  // Visit loops in post-order to find the local mass distribution, and then do
976  // the full function.
977  computeMassInLoops();
978  computeMassInFunction();
979  unwrapLoops();
980  finalizeMetrics();
981}
982
983template <class BT>
984void BlockFrequencyInfoImpl<BT>::setBlockFreq(const BlockT *BB, uint64_t Freq) {
985  if (Nodes.count(BB))
986    BlockFrequencyInfoImplBase::setBlockFreq(getNode(BB), Freq);
987  else {
988    // If BB is a newly added block after BFI is done, we need to create a new
989    // BlockNode for it assigned with a new index. The index can be determined
990    // by the size of Freqs.
991    BlockNode NewNode(Freqs.size());
992    Nodes[BB] = NewNode;
993    Freqs.emplace_back();
994    BlockFrequencyInfoImplBase::setBlockFreq(NewNode, Freq);
995  }
996}
997
998template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
999  const BlockT *Entry = &F->front();
1000  RPOT.reserve(F->size());
1001  std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
1002  std::reverse(RPOT.begin(), RPOT.end());
1003
1004  assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1005         "More nodes in function than Block Frequency Info supports");
1006
1007  DEBUG(dbgs() << "reverse-post-order-traversal\n");
1008  for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
1009    BlockNode Node = getNode(I);
1010    DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) << "\n");
1011    Nodes[*I] = Node;
1012  }
1013
1014  Working.reserve(RPOT.size());
1015  for (size_t Index = 0; Index < RPOT.size(); ++Index)
1016    Working.emplace_back(Index);
1017  Freqs.resize(RPOT.size());
1018}
1019
1020template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1021  DEBUG(dbgs() << "loop-detection\n");
1022  if (LI->empty())
1023    return;
1024
1025  // Visit loops top down and assign them an index.
1026  std::deque<std::pair<const LoopT *, LoopData *>> Q;
1027  for (const LoopT *L : *LI)
1028    Q.emplace_back(L, nullptr);
1029  while (!Q.empty()) {
1030    const LoopT *Loop = Q.front().first;
1031    LoopData *Parent = Q.front().second;
1032    Q.pop_front();
1033
1034    BlockNode Header = getNode(Loop->getHeader());
1035    assert(Header.isValid());
1036
1037    Loops.emplace_back(Parent, Header);
1038    Working[Header.Index].Loop = &Loops.back();
1039    DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1040
1041    for (const LoopT *L : *Loop)
1042      Q.emplace_back(L, &Loops.back());
1043  }
1044
1045  // Visit nodes in reverse post-order and add them to their deepest containing
1046  // loop.
1047  for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1048    // Loop headers have already been mostly mapped.
1049    if (Working[Index].isLoopHeader()) {
1050      LoopData *ContainingLoop = Working[Index].getContainingLoop();
1051      if (ContainingLoop)
1052        ContainingLoop->Nodes.push_back(Index);
1053      continue;
1054    }
1055
1056    const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1057    if (!Loop)
1058      continue;
1059
1060    // Add this node to its containing loop's member list.
1061    BlockNode Header = getNode(Loop->getHeader());
1062    assert(Header.isValid());
1063    const auto &HeaderData = Working[Header.Index];
1064    assert(HeaderData.isLoopHeader());
1065
1066    Working[Index].Loop = HeaderData.Loop;
1067    HeaderData.Loop->Nodes.push_back(Index);
1068    DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1069                 << ": member = " << getBlockName(Index) << "\n");
1070  }
1071}
1072
1073template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1074  // Visit loops with the deepest first, and the top-level loops last.
1075  for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) {
1076    if (computeMassInLoop(*L))
1077      continue;
1078    auto Next = std::next(L);
1079    computeIrreducibleMass(&*L, L.base());
1080    L = std::prev(Next);
1081    if (computeMassInLoop(*L))
1082      continue;
1083    llvm_unreachable("unhandled irreducible control flow");
1084  }
1085}
1086
1087template <class BT>
1088bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
1089  // Compute mass in loop.
1090  DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop) << "\n");
1091
1092  if (Loop.isIrreducible()) {
1093    BlockMass Remaining = BlockMass::getFull();
1094    for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
1095      auto &Mass = Working[Loop.Nodes[H].Index].getMass();
1096      Mass = Remaining * BranchProbability(1, Loop.NumHeaders - H);
1097      Remaining -= Mass;
1098    }
1099    for (const BlockNode &M : Loop.Nodes)
1100      if (!propagateMassToSuccessors(&Loop, M))
1101        llvm_unreachable("unhandled irreducible control flow");
1102
1103    adjustLoopHeaderMass(Loop);
1104  } else {
1105    Working[Loop.getHeader().Index].getMass() = BlockMass::getFull();
1106    if (!propagateMassToSuccessors(&Loop, Loop.getHeader()))
1107      llvm_unreachable("irreducible control flow to loop header!?");
1108    for (const BlockNode &M : Loop.members())
1109      if (!propagateMassToSuccessors(&Loop, M))
1110        // Irreducible backedge.
1111        return false;
1112  }
1113
1114  computeLoopScale(Loop);
1115  packageLoop(Loop);
1116  return true;
1117}
1118
1119template <class BT>
1120bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
1121  // Compute mass in function.
1122  DEBUG(dbgs() << "compute-mass-in-function\n");
1123  assert(!Working.empty() && "no blocks in function");
1124  assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1125
1126  Working[0].getMass() = BlockMass::getFull();
1127  for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
1128    // Check for nodes that have been packaged.
1129    BlockNode Node = getNode(I);
1130    if (Working[Node.Index].isPackaged())
1131      continue;
1132
1133    if (!propagateMassToSuccessors(nullptr, Node))
1134      return false;
1135  }
1136  return true;
1137}
1138
1139template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1140  if (tryToComputeMassInFunction())
1141    return;
1142  computeIrreducibleMass(nullptr, Loops.begin());
1143  if (tryToComputeMassInFunction())
1144    return;
1145  llvm_unreachable("unhandled irreducible control flow");
1146}
1147
1148/// \note This should be a lambda, but that crashes GCC 4.7.
1149namespace bfi_detail {
1150template <class BT> struct BlockEdgesAdder {
1151  typedef BT BlockT;
1152  typedef BlockFrequencyInfoImplBase::LoopData LoopData;
1153  typedef GraphTraits<const BlockT *> Successor;
1154
1155  const BlockFrequencyInfoImpl<BT> &BFI;
1156  explicit BlockEdgesAdder(const BlockFrequencyInfoImpl<BT> &BFI)
1157      : BFI(BFI) {}
1158  void operator()(IrreducibleGraph &G, IrreducibleGraph::IrrNode &Irr,
1159                  const LoopData *OuterLoop) {
1160    const BlockT *BB = BFI.RPOT[Irr.Node.Index];
1161    for (auto I = Successor::child_begin(BB), E = Successor::child_end(BB);
1162         I != E; ++I)
1163      G.addEdge(Irr, BFI.getNode(*I), OuterLoop);
1164  }
1165};
1166}
1167template <class BT>
1168void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1169    LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1170  DEBUG(dbgs() << "analyze-irreducible-in-";
1171        if (OuterLoop) dbgs() << "loop: " << getLoopName(*OuterLoop) << "\n";
1172        else dbgs() << "function\n");
1173
1174  using namespace bfi_detail;
1175  // Ideally, addBlockEdges() would be declared here as a lambda, but that
1176  // crashes GCC 4.7.
1177  BlockEdgesAdder<BT> addBlockEdges(*this);
1178  IrreducibleGraph G(*this, OuterLoop, addBlockEdges);
1179
1180  for (auto &L : analyzeIrreducible(G, OuterLoop, Insert))
1181    computeMassInLoop(L);
1182
1183  if (!OuterLoop)
1184    return;
1185  updateLoopWithIrreducible(*OuterLoop);
1186}
1187
1188// A helper function that converts a branch probability into weight.
1189inline uint32_t getWeightFromBranchProb(const BranchProbability Prob) {
1190  return Prob.getNumerator();
1191}
1192
1193template <class BT>
1194bool
1195BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1196                                                      const BlockNode &Node) {
1197  DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1198  // Calculate probability for successors.
1199  Distribution Dist;
1200  if (auto *Loop = Working[Node.Index].getPackagedLoop()) {
1201    assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop");
1202    if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
1203      // Irreducible backedge.
1204      return false;
1205  } else {
1206    const BlockT *BB = getBlock(Node);
1207    for (auto SI = Successor::child_begin(BB), SE = Successor::child_end(BB);
1208         SI != SE; ++SI)
1209      if (!addToDist(Dist, OuterLoop, Node, getNode(*SI),
1210                     getWeightFromBranchProb(BPI->getEdgeProbability(BB, SI))))
1211        // Irreducible backedge.
1212        return false;
1213  }
1214
1215  // Distribute mass to successors, saving exit and backedge data in the
1216  // loop header.
1217  distributeMass(Node, OuterLoop, Dist);
1218  return true;
1219}
1220
1221template <class BT>
1222raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
1223  if (!F)
1224    return OS;
1225  OS << "block-frequency-info: " << F->getName() << "\n";
1226  for (const BlockT &BB : *F) {
1227    OS << " - " << bfi_detail::getBlockName(&BB) << ": float = ";
1228    getFloatingBlockFreq(&BB).print(OS, 5)
1229        << ", int = " << getBlockFreq(&BB).getFrequency() << "\n";
1230  }
1231
1232  // Add an extra newline for readability.
1233  OS << "\n";
1234  return OS;
1235}
1236
1237// Graph trait base class for block frequency information graph
1238// viewer.
1239
1240enum GVDAGType { GVDT_None, GVDT_Fraction, GVDT_Integer, GVDT_Count };
1241
1242template <class BlockFrequencyInfoT, class BranchProbabilityInfoT>
1243struct BFIDOTGraphTraitsBase : public DefaultDOTGraphTraits {
1244  explicit BFIDOTGraphTraitsBase(bool isSimple = false)
1245      : DefaultDOTGraphTraits(isSimple) {}
1246
1247  typedef GraphTraits<BlockFrequencyInfoT *> GTraits;
1248  typedef typename GTraits::NodeType NodeType;
1249  typedef typename GTraits::ChildIteratorType EdgeIter;
1250  typedef typename GTraits::nodes_iterator NodeIter;
1251
1252  uint64_t MaxFrequency = 0;
1253  static std::string getGraphName(const BlockFrequencyInfoT *G) {
1254    return G->getFunction()->getName();
1255  }
1256
1257  std::string getNodeAttributes(const NodeType *Node,
1258                                const BlockFrequencyInfoT *Graph,
1259                                unsigned HotPercentThreshold = 0) {
1260    std::string Result;
1261    if (!HotPercentThreshold)
1262      return Result;
1263
1264    // Compute MaxFrequency on the fly:
1265    if (!MaxFrequency) {
1266      for (NodeIter I = GTraits::nodes_begin(Graph),
1267                    E = GTraits::nodes_end(Graph);
1268           I != E; ++I) {
1269        NodeType &N = *I;
1270        MaxFrequency =
1271            std::max(MaxFrequency, Graph->getBlockFreq(&N).getFrequency());
1272      }
1273    }
1274    BlockFrequency Freq = Graph->getBlockFreq(Node);
1275    BlockFrequency HotFreq =
1276        (BlockFrequency(MaxFrequency) *
1277         BranchProbability::getBranchProbability(HotPercentThreshold, 100));
1278
1279    if (Freq < HotFreq)
1280      return Result;
1281
1282    raw_string_ostream OS(Result);
1283    OS << "color=\"red\"";
1284    OS.flush();
1285    return Result;
1286  }
1287
1288  std::string getNodeLabel(const NodeType *Node,
1289                           const BlockFrequencyInfoT *Graph, GVDAGType GType) {
1290    std::string Result;
1291    raw_string_ostream OS(Result);
1292
1293    OS << Node->getName().str() << " : ";
1294    switch (GType) {
1295    case GVDT_Fraction:
1296      Graph->printBlockFreq(OS, Node);
1297      break;
1298    case GVDT_Integer:
1299      OS << Graph->getBlockFreq(Node).getFrequency();
1300      break;
1301    case GVDT_Count: {
1302      auto Count = Graph->getBlockProfileCount(Node);
1303      if (Count)
1304        OS << Count.getValue();
1305      else
1306        OS << "Unknown";
1307      break;
1308    }
1309    case GVDT_None:
1310      llvm_unreachable("If we are not supposed to render a graph we should "
1311                       "never reach this point.");
1312    }
1313    return Result;
1314  }
1315
1316  std::string getEdgeAttributes(const NodeType *Node, EdgeIter EI,
1317                                const BlockFrequencyInfoT *BFI,
1318                                const BranchProbabilityInfoT *BPI,
1319                                unsigned HotPercentThreshold = 0) {
1320    std::string Str;
1321    if (!BPI)
1322      return Str;
1323
1324    BranchProbability BP = BPI->getEdgeProbability(Node, EI);
1325    uint32_t N = BP.getNumerator();
1326    uint32_t D = BP.getDenominator();
1327    double Percent = 100.0 * N / D;
1328    raw_string_ostream OS(Str);
1329    OS << format("label=\"%.1f%%\"", Percent);
1330
1331    if (HotPercentThreshold) {
1332      BlockFrequency EFreq = BFI->getBlockFreq(Node) * BP;
1333      BlockFrequency HotFreq = BlockFrequency(MaxFrequency) *
1334                               BranchProbability(HotPercentThreshold, 100);
1335
1336      if (EFreq >= HotFreq) {
1337        OS << ",color=\"red\"";
1338      }
1339    }
1340
1341    OS.flush();
1342    return Str;
1343  }
1344};
1345
1346} // end namespace llvm
1347
1348#undef DEBUG_TYPE
1349
1350#endif
1351