LLVM API Documentation

BlockFrequencyInfoImpl.h
Go to the documentation of this file.
00001 //==- BlockFrequencyInfoImpl.h - Block Frequency Implementation -*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Shared implementation of BlockFrequency for IR and Machine Instructions.
00011 // See the documentation below for BlockFrequencyInfoImpl for details.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
00016 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
00017 
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/PostOrderIterator.h"
00020 #include "llvm/ADT/iterator_range.h"
00021 #include "llvm/IR/BasicBlock.h"
00022 #include "llvm/Support/BlockFrequency.h"
00023 #include "llvm/Support/BranchProbability.h"
00024 #include "llvm/Support/Debug.h"
00025 #include "llvm/Support/ScaledNumber.h"
00026 #include "llvm/Support/raw_ostream.h"
00027 #include <deque>
00028 #include <list>
00029 #include <string>
00030 #include <vector>
00031 
00032 #define DEBUG_TYPE "block-freq"
00033 
00034 namespace llvm {
00035 
00036 class BasicBlock;
00037 class BranchProbabilityInfo;
00038 class Function;
00039 class Loop;
00040 class LoopInfo;
00041 class MachineBasicBlock;
00042 class MachineBranchProbabilityInfo;
00043 class MachineFunction;
00044 class MachineLoop;
00045 class MachineLoopInfo;
00046 
00047 namespace bfi_detail {
00048 
00049 struct IrreducibleGraph;
00050 
00051 // This is part of a workaround for a GCC 4.7 crash on lambdas.
00052 template <class BT> struct BlockEdgesAdder;
00053 
00054 /// \brief Mass of a block.
00055 ///
00056 /// This class implements a sort of fixed-point fraction always between 0.0 and
00057 /// 1.0.  getMass() == UINT64_MAX indicates a value of 1.0.
00058 ///
00059 /// Masses can be added and subtracted.  Simple saturation arithmetic is used,
00060 /// so arithmetic operations never overflow or underflow.
00061 ///
00062 /// Masses can be multiplied.  Multiplication treats full mass as 1.0 and uses
00063 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not
00064 /// quite, maximum precision).
00065 ///
00066 /// Masses can be scaled by \a BranchProbability at maximum precision.
00067 class BlockMass {
00068   uint64_t Mass;
00069 
00070 public:
00071   BlockMass() : Mass(0) {}
00072   explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
00073 
00074   static BlockMass getEmpty() { return BlockMass(); }
00075   static BlockMass getFull() { return BlockMass(UINT64_MAX); }
00076 
00077   uint64_t getMass() const { return Mass; }
00078 
00079   bool isFull() const { return Mass == UINT64_MAX; }
00080   bool isEmpty() const { return !Mass; }
00081 
00082   bool operator!() const { return isEmpty(); }
00083 
00084   /// \brief Add another mass.
00085   ///
00086   /// Adds another mass, saturating at \a isFull() rather than overflowing.
00087   BlockMass &operator+=(const BlockMass &X) {
00088     uint64_t Sum = Mass + X.Mass;
00089     Mass = Sum < Mass ? UINT64_MAX : Sum;
00090     return *this;
00091   }
00092 
00093   /// \brief Subtract another mass.
00094   ///
00095   /// Subtracts another mass, saturating at \a isEmpty() rather than
00096   /// undeflowing.
00097   BlockMass &operator-=(const BlockMass &X) {
00098     uint64_t Diff = Mass - X.Mass;
00099     Mass = Diff > Mass ? 0 : Diff;
00100     return *this;
00101   }
00102 
00103   BlockMass &operator*=(const BranchProbability &P) {
00104     Mass = P.scale(Mass);
00105     return *this;
00106   }
00107 
00108   bool operator==(const BlockMass &X) const { return Mass == X.Mass; }
00109   bool operator!=(const BlockMass &X) const { return Mass != X.Mass; }
00110   bool operator<=(const BlockMass &X) const { return Mass <= X.Mass; }
00111   bool operator>=(const BlockMass &X) const { return Mass >= X.Mass; }
00112   bool operator<(const BlockMass &X) const { return Mass < X.Mass; }
00113   bool operator>(const BlockMass &X) const { return Mass > X.Mass; }
00114 
00115   /// \brief Convert to scaled number.
00116   ///
00117   /// Convert to \a ScaledNumber.  \a isFull() gives 1.0, while \a isEmpty()
00118   /// gives slightly above 0.0.
00119   ScaledNumber<uint64_t> toScaled() const;
00120 
00121   void dump() const;
00122   raw_ostream &print(raw_ostream &OS) const;
00123 };
00124 
00125 inline BlockMass operator+(const BlockMass &L, const BlockMass &R) {
00126   return BlockMass(L) += R;
00127 }
00128 inline BlockMass operator-(const BlockMass &L, const BlockMass &R) {
00129   return BlockMass(L) -= R;
00130 }
00131 inline BlockMass operator*(const BlockMass &L, const BranchProbability &R) {
00132   return BlockMass(L) *= R;
00133 }
00134 inline BlockMass operator*(const BranchProbability &L, const BlockMass &R) {
00135   return BlockMass(R) *= L;
00136 }
00137 
00138 inline raw_ostream &operator<<(raw_ostream &OS, const BlockMass &X) {
00139   return X.print(OS);
00140 }
00141 
00142 } // end namespace bfi_detail
00143 
00144 template <> struct isPodLike<bfi_detail::BlockMass> {
00145   static const bool value = true;
00146 };
00147 
00148 /// \brief Base class for BlockFrequencyInfoImpl
00149 ///
00150 /// BlockFrequencyInfoImplBase has supporting data structures and some
00151 /// algorithms for BlockFrequencyInfoImplBase.  Only algorithms that depend on
00152 /// the block type (or that call such algorithms) are skipped here.
00153 ///
00154 /// Nevertheless, the majority of the overall algorithm documention lives with
00155 /// BlockFrequencyInfoImpl.  See there for details.
00156 class BlockFrequencyInfoImplBase {
00157 public:
00158   typedef ScaledNumber<uint64_t> Scaled64;
00159   typedef bfi_detail::BlockMass BlockMass;
00160 
00161   /// \brief Representative of a block.
00162   ///
00163   /// This is a simple wrapper around an index into the reverse-post-order
00164   /// traversal of the blocks.
00165   ///
00166   /// Unlike a block pointer, its order has meaning (location in the
00167   /// topological sort) and it's class is the same regardless of block type.
00168   struct BlockNode {
00169     typedef uint32_t IndexType;
00170     IndexType Index;
00171 
00172     bool operator==(const BlockNode &X) const { return Index == X.Index; }
00173     bool operator!=(const BlockNode &X) const { return Index != X.Index; }
00174     bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
00175     bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
00176     bool operator<(const BlockNode &X) const { return Index < X.Index; }
00177     bool operator>(const BlockNode &X) const { return Index > X.Index; }
00178 
00179     BlockNode() : Index(UINT32_MAX) {}
00180     BlockNode(IndexType Index) : Index(Index) {}
00181 
00182     bool isValid() const { return Index <= getMaxIndex(); }
00183     static size_t getMaxIndex() { return UINT32_MAX - 1; }
00184   };
00185 
00186   /// \brief Stats about a block itself.
00187   struct FrequencyData {
00188     Scaled64 Scaled;
00189     uint64_t Integer;
00190   };
00191 
00192   /// \brief Data about a loop.
00193   ///
00194   /// Contains the data necessary to represent represent a loop as a
00195   /// pseudo-node once it's packaged.
00196   struct LoopData {
00197     typedef SmallVector<std::pair<BlockNode, BlockMass>, 4> ExitMap;
00198     typedef SmallVector<BlockNode, 4> NodeList;
00199     LoopData *Parent;       ///< The parent loop.
00200     bool IsPackaged;        ///< Whether this has been packaged.
00201     uint32_t NumHeaders;    ///< Number of headers.
00202     ExitMap Exits;          ///< Successor edges (and weights).
00203     NodeList Nodes;         ///< Header and the members of the loop.
00204     BlockMass BackedgeMass; ///< Mass returned to loop header.
00205     BlockMass Mass;
00206     Scaled64 Scale;
00207 
00208     LoopData(LoopData *Parent, const BlockNode &Header)
00209         : Parent(Parent), IsPackaged(false), NumHeaders(1), Nodes(1, Header) {}
00210     template <class It1, class It2>
00211     LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther,
00212              It2 LastOther)
00213         : Parent(Parent), IsPackaged(false), Nodes(FirstHeader, LastHeader) {
00214       NumHeaders = Nodes.size();
00215       Nodes.insert(Nodes.end(), FirstOther, LastOther);
00216     }
00217     bool isHeader(const BlockNode &Node) const {
00218       if (isIrreducible())
00219         return std::binary_search(Nodes.begin(), Nodes.begin() + NumHeaders,
00220                                   Node);
00221       return Node == Nodes[0];
00222     }
00223     BlockNode getHeader() const { return Nodes[0]; }
00224     bool isIrreducible() const { return NumHeaders > 1; }
00225 
00226     NodeList::const_iterator members_begin() const {
00227       return Nodes.begin() + NumHeaders;
00228     }
00229     NodeList::const_iterator members_end() const { return Nodes.end(); }
00230     iterator_range<NodeList::const_iterator> members() const {
00231       return make_range(members_begin(), members_end());
00232     }
00233   };
00234 
00235   /// \brief Index of loop information.
00236   struct WorkingData {
00237     BlockNode Node; ///< This node.
00238     LoopData *Loop; ///< The loop this block is inside.
00239     BlockMass Mass; ///< Mass distribution from the entry block.
00240 
00241     WorkingData(const BlockNode &Node) : Node(Node), Loop(nullptr) {}
00242 
00243     bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
00244     bool isDoubleLoopHeader() const {
00245       return isLoopHeader() && Loop->Parent && Loop->Parent->isIrreducible() &&
00246              Loop->Parent->isHeader(Node);
00247     }
00248 
00249     LoopData *getContainingLoop() const {
00250       if (!isLoopHeader())
00251         return Loop;
00252       if (!isDoubleLoopHeader())
00253         return Loop->Parent;
00254       return Loop->Parent->Parent;
00255     }
00256 
00257     /// \brief Resolve a node to its representative.
00258     ///
00259     /// Get the node currently representing Node, which could be a containing
00260     /// loop.
00261     ///
00262     /// This function should only be called when distributing mass.  As long as
00263     /// there are no irreducilbe edges to Node, then it will have complexity
00264     /// O(1) in this context.
00265     ///
00266     /// In general, the complexity is O(L), where L is the number of loop
00267     /// headers Node has been packaged into.  Since this method is called in
00268     /// the context of distributing mass, L will be the number of loop headers
00269     /// an early exit edge jumps out of.
00270     BlockNode getResolvedNode() const {
00271       auto L = getPackagedLoop();
00272       return L ? L->getHeader() : Node;
00273     }
00274     LoopData *getPackagedLoop() const {
00275       if (!Loop || !Loop->IsPackaged)
00276         return nullptr;
00277       auto L = Loop;
00278       while (L->Parent && L->Parent->IsPackaged)
00279         L = L->Parent;
00280       return L;
00281     }
00282 
00283     /// \brief Get the appropriate mass for a node.
00284     ///
00285     /// Get appropriate mass for Node.  If Node is a loop-header (whose loop
00286     /// has been packaged), returns the mass of its pseudo-node.  If it's a
00287     /// node inside a packaged loop, it returns the loop's mass.
00288     BlockMass &getMass() {
00289       if (!isAPackage())
00290         return Mass;
00291       if (!isADoublePackage())
00292         return Loop->Mass;
00293       return Loop->Parent->Mass;
00294     }
00295 
00296     /// \brief Has ContainingLoop been packaged up?
00297     bool isPackaged() const { return getResolvedNode() != Node; }
00298     /// \brief Has Loop been packaged up?
00299     bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; }
00300     /// \brief Has Loop been packaged up twice?
00301     bool isADoublePackage() const {
00302       return isDoubleLoopHeader() && Loop->Parent->IsPackaged;
00303     }
00304   };
00305 
00306   /// \brief Unscaled probability weight.
00307   ///
00308   /// Probability weight for an edge in the graph (including the
00309   /// successor/target node).
00310   ///
00311   /// All edges in the original function are 32-bit.  However, exit edges from
00312   /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
00313   /// space in general.
00314   ///
00315   /// In addition to the raw weight amount, Weight stores the type of the edge
00316   /// in the current context (i.e., the context of the loop being processed).
00317   /// Is this a local edge within the loop, an exit from the loop, or a
00318   /// backedge to the loop header?
00319   struct Weight {
00320     enum DistType { Local, Exit, Backedge };
00321     DistType Type;
00322     BlockNode TargetNode;
00323     uint64_t Amount;
00324     Weight() : Type(Local), Amount(0) {}
00325     Weight(DistType Type, BlockNode TargetNode, uint64_t Amount)
00326         : Type(Type), TargetNode(TargetNode), Amount(Amount) {}
00327   };
00328 
00329   /// \brief Distribution of unscaled probability weight.
00330   ///
00331   /// Distribution of unscaled probability weight to a set of successors.
00332   ///
00333   /// This class collates the successor edge weights for later processing.
00334   ///
00335   /// \a DidOverflow indicates whether \a Total did overflow while adding to
00336   /// the distribution.  It should never overflow twice.
00337   struct Distribution {
00338     typedef SmallVector<Weight, 4> WeightList;
00339     WeightList Weights;    ///< Individual successor weights.
00340     uint64_t Total;        ///< Sum of all weights.
00341     bool DidOverflow;      ///< Whether \a Total did overflow.
00342 
00343     Distribution() : Total(0), DidOverflow(false) {}
00344     void addLocal(const BlockNode &Node, uint64_t Amount) {
00345       add(Node, Amount, Weight::Local);
00346     }
00347     void addExit(const BlockNode &Node, uint64_t Amount) {
00348       add(Node, Amount, Weight::Exit);
00349     }
00350     void addBackedge(const BlockNode &Node, uint64_t Amount) {
00351       add(Node, Amount, Weight::Backedge);
00352     }
00353 
00354     /// \brief Normalize the distribution.
00355     ///
00356     /// Combines multiple edges to the same \a Weight::TargetNode and scales
00357     /// down so that \a Total fits into 32-bits.
00358     ///
00359     /// This is linear in the size of \a Weights.  For the vast majority of
00360     /// cases, adjacent edge weights are combined by sorting WeightList and
00361     /// combining adjacent weights.  However, for very large edge lists an
00362     /// auxiliary hash table is used.
00363     void normalize();
00364 
00365   private:
00366     void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
00367   };
00368 
00369   /// \brief Data about each block.  This is used downstream.
00370   std::vector<FrequencyData> Freqs;
00371 
00372   /// \brief Loop data: see initializeLoops().
00373   std::vector<WorkingData> Working;
00374 
00375   /// \brief Indexed information about loops.
00376   std::list<LoopData> Loops;
00377 
00378   /// \brief Add all edges out of a packaged loop to the distribution.
00379   ///
00380   /// Adds all edges from LocalLoopHead to Dist.  Calls addToDist() to add each
00381   /// successor edge.
00382   ///
00383   /// \return \c true unless there's an irreducible backedge.
00384   bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop,
00385                                Distribution &Dist);
00386 
00387   /// \brief Add an edge to the distribution.
00388   ///
00389   /// Adds an edge to Succ to Dist.  If \c LoopHead.isValid(), then whether the
00390   /// edge is local/exit/backedge is in the context of LoopHead.  Otherwise,
00391   /// every edge should be a local edge (since all the loops are packaged up).
00392   ///
00393   /// \return \c true unless aborted due to an irreducible backedge.
00394   bool addToDist(Distribution &Dist, const LoopData *OuterLoop,
00395                  const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
00396 
00397   LoopData &getLoopPackage(const BlockNode &Head) {
00398     assert(Head.Index < Working.size());
00399     assert(Working[Head.Index].isLoopHeader());
00400     return *Working[Head.Index].Loop;
00401   }
00402 
00403   /// \brief Analyze irreducible SCCs.
00404   ///
00405   /// Separate irreducible SCCs from \c G, which is an explict graph of \c
00406   /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr).
00407   /// Insert them into \a Loops before \c Insert.
00408   ///
00409   /// \return the \c LoopData nodes representing the irreducible SCCs.
00410   iterator_range<std::list<LoopData>::iterator>
00411   analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop,
00412                      std::list<LoopData>::iterator Insert);
00413 
00414   /// \brief Update a loop after packaging irreducible SCCs inside of it.
00415   ///
00416   /// Update \c OuterLoop.  Before finding irreducible control flow, it was
00417   /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a
00418   /// LoopData::BackedgeMass need to be reset.  Also, nodes that were packaged
00419   /// up need to be removed from \a OuterLoop::Nodes.
00420   void updateLoopWithIrreducible(LoopData &OuterLoop);
00421 
00422   /// \brief Distribute mass according to a distribution.
00423   ///
00424   /// Distributes the mass in Source according to Dist.  If LoopHead.isValid(),
00425   /// backedges and exits are stored in its entry in Loops.
00426   ///
00427   /// Mass is distributed in parallel from two copies of the source mass.
00428   void distributeMass(const BlockNode &Source, LoopData *OuterLoop,
00429                       Distribution &Dist);
00430 
00431   /// \brief Compute the loop scale for a loop.
00432   void computeLoopScale(LoopData &Loop);
00433 
00434   /// \brief Package up a loop.
00435   void packageLoop(LoopData &Loop);
00436 
00437   /// \brief Unwrap loops.
00438   void unwrapLoops();
00439 
00440   /// \brief Finalize frequency metrics.
00441   ///
00442   /// Calculates final frequencies and cleans up no-longer-needed data
00443   /// structures.
00444   void finalizeMetrics();
00445 
00446   /// \brief Clear all memory.
00447   void clear();
00448 
00449   virtual std::string getBlockName(const BlockNode &Node) const;
00450   std::string getLoopName(const LoopData &Loop) const;
00451 
00452   virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
00453   void dump() const { print(dbgs()); }
00454 
00455   Scaled64 getFloatingBlockFreq(const BlockNode &Node) const;
00456 
00457   BlockFrequency getBlockFreq(const BlockNode &Node) const;
00458 
00459   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
00460   raw_ostream &printBlockFreq(raw_ostream &OS,
00461                               const BlockFrequency &Freq) const;
00462 
00463   uint64_t getEntryFreq() const {
00464     assert(!Freqs.empty());
00465     return Freqs[0].Integer;
00466   }
00467   /// \brief Virtual destructor.
00468   ///
00469   /// Need a virtual destructor to mask the compiler warning about
00470   /// getBlockName().
00471   virtual ~BlockFrequencyInfoImplBase() {}
00472 };
00473 
00474 namespace bfi_detail {
00475 template <class BlockT> struct TypeMap {};
00476 template <> struct TypeMap<BasicBlock> {
00477   typedef BasicBlock BlockT;
00478   typedef Function FunctionT;
00479   typedef BranchProbabilityInfo BranchProbabilityInfoT;
00480   typedef Loop LoopT;
00481   typedef LoopInfo LoopInfoT;
00482 };
00483 template <> struct TypeMap<MachineBasicBlock> {
00484   typedef MachineBasicBlock BlockT;
00485   typedef MachineFunction FunctionT;
00486   typedef MachineBranchProbabilityInfo BranchProbabilityInfoT;
00487   typedef MachineLoop LoopT;
00488   typedef MachineLoopInfo LoopInfoT;
00489 };
00490 
00491 /// \brief Get the name of a MachineBasicBlock.
00492 ///
00493 /// Get the name of a MachineBasicBlock.  It's templated so that including from
00494 /// CodeGen is unnecessary (that would be a layering issue).
00495 ///
00496 /// This is used mainly for debug output.  The name is similar to
00497 /// MachineBasicBlock::getFullName(), but skips the name of the function.
00498 template <class BlockT> std::string getBlockName(const BlockT *BB) {
00499   assert(BB && "Unexpected nullptr");
00500   auto MachineName = "BB" + Twine(BB->getNumber());
00501   if (BB->getBasicBlock())
00502     return (MachineName + "[" + BB->getName() + "]").str();
00503   return MachineName.str();
00504 }
00505 /// \brief Get the name of a BasicBlock.
00506 template <> inline std::string getBlockName(const BasicBlock *BB) {
00507   assert(BB && "Unexpected nullptr");
00508   return BB->getName().str();
00509 }
00510 
00511 /// \brief Graph of irreducible control flow.
00512 ///
00513 /// This graph is used for determining the SCCs in a loop (or top-level
00514 /// function) that has irreducible control flow.
00515 ///
00516 /// During the block frequency algorithm, the local graphs are defined in a
00517 /// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock
00518 /// graphs for most edges, but getting others from \a LoopData::ExitMap.  The
00519 /// latter only has successor information.
00520 ///
00521 /// \a IrreducibleGraph makes this graph explicit.  It's in a form that can use
00522 /// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator),
00523 /// and it explicitly lists predecessors and successors.  The initialization
00524 /// that relies on \c MachineBasicBlock is defined in the header.
00525 struct IrreducibleGraph {
00526   typedef BlockFrequencyInfoImplBase BFIBase;
00527 
00528   BFIBase &BFI;
00529 
00530   typedef BFIBase::BlockNode BlockNode;
00531   struct IrrNode {
00532     BlockNode Node;
00533     unsigned NumIn;
00534     std::deque<const IrrNode *> Edges;
00535     IrrNode(const BlockNode &Node) : Node(Node), NumIn(0) {}
00536 
00537     typedef std::deque<const IrrNode *>::const_iterator iterator;
00538     iterator pred_begin() const { return Edges.begin(); }
00539     iterator succ_begin() const { return Edges.begin() + NumIn; }
00540     iterator pred_end() const { return succ_begin(); }
00541     iterator succ_end() const { return Edges.end(); }
00542   };
00543   BlockNode Start;
00544   const IrrNode *StartIrr;
00545   std::vector<IrrNode> Nodes;
00546   SmallDenseMap<uint32_t, IrrNode *, 4> Lookup;
00547 
00548   /// \brief Construct an explicit graph containing irreducible control flow.
00549   ///
00550   /// Construct an explicit graph of the control flow in \c OuterLoop (or the
00551   /// top-level function, if \c OuterLoop is \c nullptr).  Uses \c
00552   /// addBlockEdges to add block successors that have not been packaged into
00553   /// loops.
00554   ///
00555   /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected
00556   /// user of this.
00557   template <class BlockEdgesAdder>
00558   IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop,
00559                    BlockEdgesAdder addBlockEdges)
00560       : BFI(BFI), StartIrr(nullptr) {
00561     initialize(OuterLoop, addBlockEdges);
00562   }
00563 
00564   template <class BlockEdgesAdder>
00565   void initialize(const BFIBase::LoopData *OuterLoop,
00566                   BlockEdgesAdder addBlockEdges);
00567   void addNodesInLoop(const BFIBase::LoopData &OuterLoop);
00568   void addNodesInFunction();
00569   void addNode(const BlockNode &Node) {
00570     Nodes.emplace_back(Node);
00571     BFI.Working[Node.Index].getMass() = BlockMass::getEmpty();
00572   }
00573   void indexNodes();
00574   template <class BlockEdgesAdder>
00575   void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop,
00576                 BlockEdgesAdder addBlockEdges);
00577   void addEdge(IrrNode &Irr, const BlockNode &Succ,
00578                const BFIBase::LoopData *OuterLoop);
00579 };
00580 template <class BlockEdgesAdder>
00581 void IrreducibleGraph::initialize(const BFIBase::LoopData *OuterLoop,
00582                                   BlockEdgesAdder addBlockEdges) {
00583   if (OuterLoop) {
00584     addNodesInLoop(*OuterLoop);
00585     for (auto N : OuterLoop->Nodes)
00586       addEdges(N, OuterLoop, addBlockEdges);
00587   } else {
00588     addNodesInFunction();
00589     for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
00590       addEdges(Index, OuterLoop, addBlockEdges);
00591   }
00592   StartIrr = Lookup[Start.Index];
00593 }
00594 template <class BlockEdgesAdder>
00595 void IrreducibleGraph::addEdges(const BlockNode &Node,
00596                                 const BFIBase::LoopData *OuterLoop,
00597                                 BlockEdgesAdder addBlockEdges) {
00598   auto L = Lookup.find(Node.Index);
00599   if (L == Lookup.end())
00600     return;
00601   IrrNode &Irr = *L->second;
00602   const auto &Working = BFI.Working[Node.Index];
00603 
00604   if (Working.isAPackage())
00605     for (const auto &I : Working.Loop->Exits)
00606       addEdge(Irr, I.first, OuterLoop);
00607   else
00608     addBlockEdges(*this, Irr, OuterLoop);
00609 }
00610 }
00611 
00612 /// \brief Shared implementation for block frequency analysis.
00613 ///
00614 /// This is a shared implementation of BlockFrequencyInfo and
00615 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
00616 /// blocks.
00617 ///
00618 /// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block,
00619 /// which is called the header.  A given loop, L, can have sub-loops, which are
00620 /// loops within the subgraph of L that exclude its header.  (A "trivial" SCC
00621 /// consists of a single block that does not have a self-edge.)
00622 ///
00623 /// In addition to loops, this algorithm has limited support for irreducible
00624 /// SCCs, which are SCCs with multiple entry blocks.  Irreducible SCCs are
00625 /// discovered on they fly, and modelled as loops with multiple headers.
00626 ///
00627 /// The headers of irreducible sub-SCCs consist of its entry blocks and all
00628 /// nodes that are targets of a backedge within it (excluding backedges within
00629 /// true sub-loops).  Block frequency calculations act as if a block is
00630 /// inserted that intercepts all the edges to the headers.  All backedges and
00631 /// entries point to this block.  Its successors are the headers, which split
00632 /// the frequency evenly.
00633 ///
00634 /// This algorithm leverages BlockMass and ScaledNumber to maintain precision,
00635 /// separates mass distribution from loop scaling, and dithers to eliminate
00636 /// probability mass loss.
00637 ///
00638 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
00639 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
00640 /// BlockFrequencyInfoImplBase, which doesn't.  The base class uses \a
00641 /// BlockNode, a wrapper around a uint32_t.  BlockNode is numbered from 0 in
00642 /// reverse-post order.  This gives two advantages:  it's easy to compare the
00643 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
00644 /// by vectors.
00645 ///
00646 /// This algorithm is O(V+E), unless there is irreducible control flow, in
00647 /// which case it's O(V*E) in the worst case.
00648 ///
00649 /// These are the main stages:
00650 ///
00651 ///  0. Reverse post-order traversal (\a initializeRPOT()).
00652 ///
00653 ///     Run a single post-order traversal and save it (in reverse) in RPOT.
00654 ///     All other stages make use of this ordering.  Save a lookup from BlockT
00655 ///     to BlockNode (the index into RPOT) in Nodes.
00656 ///
00657 ///  1. Loop initialization (\a initializeLoops()).
00658 ///
00659 ///     Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
00660 ///     the algorithm.  In particular, store the immediate members of each loop
00661 ///     in reverse post-order.
00662 ///
00663 ///  2. Calculate mass and scale in loops (\a computeMassInLoops()).
00664 ///
00665 ///     For each loop (bottom-up), distribute mass through the DAG resulting
00666 ///     from ignoring backedges and treating sub-loops as a single pseudo-node.
00667 ///     Track the backedge mass distributed to the loop header, and use it to
00668 ///     calculate the loop scale (number of loop iterations).  Immediate
00669 ///     members that represent sub-loops will already have been visited and
00670 ///     packaged into a pseudo-node.
00671 ///
00672 ///     Distributing mass in a loop is a reverse-post-order traversal through
00673 ///     the loop.  Start by assigning full mass to the Loop header.  For each
00674 ///     node in the loop:
00675 ///
00676 ///         - Fetch and categorize the weight distribution for its successors.
00677 ///           If this is a packaged-subloop, the weight distribution is stored
00678 ///           in \a LoopData::Exits.  Otherwise, fetch it from
00679 ///           BranchProbabilityInfo.
00680 ///
00681 ///         - Each successor is categorized as \a Weight::Local, a local edge
00682 ///           within the current loop, \a Weight::Backedge, a backedge to the
00683 ///           loop header, or \a Weight::Exit, any successor outside the loop.
00684 ///           The weight, the successor, and its category are stored in \a
00685 ///           Distribution.  There can be multiple edges to each successor.
00686 ///
00687 ///         - If there's a backedge to a non-header, there's an irreducible SCC.
00688 ///           The usual flow is temporarily aborted.  \a
00689 ///           computeIrreducibleMass() finds the irreducible SCCs within the
00690 ///           loop, packages them up, and restarts the flow.
00691 ///
00692 ///         - Normalize the distribution:  scale weights down so that their sum
00693 ///           is 32-bits, and coalesce multiple edges to the same node.
00694 ///
00695 ///         - Distribute the mass accordingly, dithering to minimize mass loss,
00696 ///           as described in \a distributeMass().
00697 ///
00698 ///     Finally, calculate the loop scale from the accumulated backedge mass.
00699 ///
00700 ///  3. Distribute mass in the function (\a computeMassInFunction()).
00701 ///
00702 ///     Finally, distribute mass through the DAG resulting from packaging all
00703 ///     loops in the function.  This uses the same algorithm as distributing
00704 ///     mass in a loop, except that there are no exit or backedge edges.
00705 ///
00706 ///  4. Unpackage loops (\a unwrapLoops()).
00707 ///
00708 ///     Initialize each block's frequency to a floating point representation of
00709 ///     its mass.
00710 ///
00711 ///     Visit loops top-down, scaling the frequencies of its immediate members
00712 ///     by the loop's pseudo-node's frequency.
00713 ///
00714 ///  5. Convert frequencies to a 64-bit range (\a finalizeMetrics()).
00715 ///
00716 ///     Using the min and max frequencies as a guide, translate floating point
00717 ///     frequencies to an appropriate range in uint64_t.
00718 ///
00719 /// It has some known flaws.
00720 ///
00721 ///   - Loop scale is limited to 4096 per loop (2^12) to avoid exhausting
00722 ///     BlockFrequency's 64-bit integer precision.
00723 ///
00724 ///   - The model of irreducible control flow is a rough approximation.
00725 ///
00726 ///     Modelling irreducible control flow exactly involves setting up and
00727 ///     solving a group of infinite geometric series.  Such precision is
00728 ///     unlikely to be worthwhile, since most of our algorithms give up on
00729 ///     irreducible control flow anyway.
00730 ///
00731 ///     Nevertheless, we might find that we need to get closer.  Here's a sort
00732 ///     of TODO list for the model with diminishing returns, to be completed as
00733 ///     necessary.
00734 ///
00735 ///       - The headers for the \a LoopData representing an irreducible SCC
00736 ///         include non-entry blocks.  When these extra blocks exist, they
00737 ///         indicate a self-contained irreducible sub-SCC.  We could treat them
00738 ///         as sub-loops, rather than arbitrarily shoving the problematic
00739 ///         blocks into the headers of the main irreducible SCC.
00740 ///
00741 ///       - Backedge frequencies are assumed to be evenly split between the
00742 ///         headers of a given irreducible SCC.  Instead, we could track the
00743 ///         backedge mass separately for each header, and adjust their relative
00744 ///         frequencies.
00745 ///
00746 ///       - Entry frequencies are assumed to be evenly split between the
00747 ///         headers of a given irreducible SCC, which is the only option if we
00748 ///         need to compute mass in the SCC before its parent loop.  Instead,
00749 ///         we could partially compute mass in the parent loop, and stop when
00750 ///         we get to the SCC.  Here, we have the correct ratio of entry
00751 ///         masses, which we can use to adjust their relative frequencies.
00752 ///         Compute mass in the SCC, and then continue propagation in the
00753 ///         parent.
00754 ///
00755 ///       - We can propagate mass iteratively through the SCC, for some fixed
00756 ///         number of iterations.  Each iteration starts by assigning the entry
00757 ///         blocks their backedge mass from the prior iteration.  The final
00758 ///         mass for each block (and each exit, and the total backedge mass
00759 ///         used for computing loop scale) is the sum of all iterations.
00760 ///         (Running this until fixed point would "solve" the geometric
00761 ///         series by simulation.)
00762 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
00763   typedef typename bfi_detail::TypeMap<BT>::BlockT BlockT;
00764   typedef typename bfi_detail::TypeMap<BT>::FunctionT FunctionT;
00765   typedef typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT
00766   BranchProbabilityInfoT;
00767   typedef typename bfi_detail::TypeMap<BT>::LoopT LoopT;
00768   typedef typename bfi_detail::TypeMap<BT>::LoopInfoT LoopInfoT;
00769 
00770   // This is part of a workaround for a GCC 4.7 crash on lambdas.
00771   friend struct bfi_detail::BlockEdgesAdder<BT>;
00772 
00773   typedef GraphTraits<const BlockT *> Successor;
00774   typedef GraphTraits<Inverse<const BlockT *>> Predecessor;
00775 
00776   const BranchProbabilityInfoT *BPI;
00777   const LoopInfoT *LI;
00778   const FunctionT *F;
00779 
00780   // All blocks in reverse postorder.
00781   std::vector<const BlockT *> RPOT;
00782   DenseMap<const BlockT *, BlockNode> Nodes;
00783 
00784   typedef typename std::vector<const BlockT *>::const_iterator rpot_iterator;
00785 
00786   rpot_iterator rpot_begin() const { return RPOT.begin(); }
00787   rpot_iterator rpot_end() const { return RPOT.end(); }
00788 
00789   size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
00790 
00791   BlockNode getNode(const rpot_iterator &I) const {
00792     return BlockNode(getIndex(I));
00793   }
00794   BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB); }
00795 
00796   const BlockT *getBlock(const BlockNode &Node) const {
00797     assert(Node.Index < RPOT.size());
00798     return RPOT[Node.Index];
00799   }
00800 
00801   /// \brief Run (and save) a post-order traversal.
00802   ///
00803   /// Saves a reverse post-order traversal of all the nodes in \a F.
00804   void initializeRPOT();
00805 
00806   /// \brief Initialize loop data.
00807   ///
00808   /// Build up \a Loops using \a LoopInfo.  \a LoopInfo gives us a mapping from
00809   /// each block to the deepest loop it's in, but we need the inverse.  For each
00810   /// loop, we store in reverse post-order its "immediate" members, defined as
00811   /// the header, the headers of immediate sub-loops, and all other blocks in
00812   /// the loop that are not in sub-loops.
00813   void initializeLoops();
00814 
00815   /// \brief Propagate to a block's successors.
00816   ///
00817   /// In the context of distributing mass through \c OuterLoop, divide the mass
00818   /// currently assigned to \c Node between its successors.
00819   ///
00820   /// \return \c true unless there's an irreducible backedge.
00821   bool propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node);
00822 
00823   /// \brief Compute mass in a particular loop.
00824   ///
00825   /// Assign mass to \c Loop's header, and then for each block in \c Loop in
00826   /// reverse post-order, distribute mass to its successors.  Only visits nodes
00827   /// that have not been packaged into sub-loops.
00828   ///
00829   /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
00830   /// \return \c true unless there's an irreducible backedge.
00831   bool computeMassInLoop(LoopData &Loop);
00832 
00833   /// \brief Try to compute mass in the top-level function.
00834   ///
00835   /// Assign mass to the entry block, and then for each block in reverse
00836   /// post-order, distribute mass to its successors.  Skips nodes that have
00837   /// been packaged into loops.
00838   ///
00839   /// \pre \a computeMassInLoops() has been called.
00840   /// \return \c true unless there's an irreducible backedge.
00841   bool tryToComputeMassInFunction();
00842 
00843   /// \brief Compute mass in (and package up) irreducible SCCs.
00844   ///
00845   /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front
00846   /// of \c Insert), and call \a computeMassInLoop() on each of them.
00847   ///
00848   /// If \c OuterLoop is \c nullptr, it refers to the top-level function.
00849   ///
00850   /// \pre \a computeMassInLoop() has been called for each subloop of \c
00851   /// OuterLoop.
00852   /// \pre \c Insert points at the the last loop successfully processed by \a
00853   /// computeMassInLoop().
00854   /// \pre \c OuterLoop has irreducible SCCs.
00855   void computeIrreducibleMass(LoopData *OuterLoop,
00856                               std::list<LoopData>::iterator Insert);
00857 
00858   /// \brief Compute mass in all loops.
00859   ///
00860   /// For each loop bottom-up, call \a computeMassInLoop().
00861   ///
00862   /// \a computeMassInLoop() aborts (and returns \c false) on loops that
00863   /// contain a irreducible sub-SCCs.  Use \a computeIrreducibleMass() and then
00864   /// re-enter \a computeMassInLoop().
00865   ///
00866   /// \post \a computeMassInLoop() has returned \c true for every loop.
00867   void computeMassInLoops();
00868 
00869   /// \brief Compute mass in the top-level function.
00870   ///
00871   /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to
00872   /// compute mass in the top-level function.
00873   ///
00874   /// \post \a tryToComputeMassInFunction() has returned \c true.
00875   void computeMassInFunction();
00876 
00877   std::string getBlockName(const BlockNode &Node) const override {
00878     return bfi_detail::getBlockName(getBlock(Node));
00879   }
00880 
00881 public:
00882   const FunctionT *getFunction() const { return F; }
00883 
00884   void doFunction(const FunctionT *F, const BranchProbabilityInfoT *BPI,
00885                   const LoopInfoT *LI);
00886   BlockFrequencyInfoImpl() : BPI(nullptr), LI(nullptr), F(nullptr) {}
00887 
00888   using BlockFrequencyInfoImplBase::getEntryFreq;
00889   BlockFrequency getBlockFreq(const BlockT *BB) const {
00890     return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
00891   }
00892   Scaled64 getFloatingBlockFreq(const BlockT *BB) const {
00893     return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
00894   }
00895 
00896   /// \brief Print the frequencies for the current function.
00897   ///
00898   /// Prints the frequencies for the blocks in the current function.
00899   ///
00900   /// Blocks are printed in the natural iteration order of the function, rather
00901   /// than reverse post-order.  This provides two advantages:  writing -analyze
00902   /// tests is easier (since blocks come out in source order), and even
00903   /// unreachable blocks are printed.
00904   ///
00905   /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
00906   /// we need to override it here.
00907   raw_ostream &print(raw_ostream &OS) const override;
00908   using BlockFrequencyInfoImplBase::dump;
00909 
00910   using BlockFrequencyInfoImplBase::printBlockFreq;
00911   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
00912     return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
00913   }
00914 };
00915 
00916 template <class BT>
00917 void BlockFrequencyInfoImpl<BT>::doFunction(const FunctionT *F,
00918                                             const BranchProbabilityInfoT *BPI,
00919                                             const LoopInfoT *LI) {
00920   // Save the parameters.
00921   this->BPI = BPI;
00922   this->LI = LI;
00923   this->F = F;
00924 
00925   // Clean up left-over data structures.
00926   BlockFrequencyInfoImplBase::clear();
00927   RPOT.clear();
00928   Nodes.clear();
00929 
00930   // Initialize.
00931   DEBUG(dbgs() << "\nblock-frequency: " << F->getName() << "\n================="
00932                << std::string(F->getName().size(), '=') << "\n");
00933   initializeRPOT();
00934   initializeLoops();
00935 
00936   // Visit loops in post-order to find thelocal mass distribution, and then do
00937   // the full function.
00938   computeMassInLoops();
00939   computeMassInFunction();
00940   unwrapLoops();
00941   finalizeMetrics();
00942 }
00943 
00944 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
00945   const BlockT *Entry = F->begin();
00946   RPOT.reserve(F->size());
00947   std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
00948   std::reverse(RPOT.begin(), RPOT.end());
00949 
00950   assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
00951          "More nodes in function than Block Frequency Info supports");
00952 
00953   DEBUG(dbgs() << "reverse-post-order-traversal\n");
00954   for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
00955     BlockNode Node = getNode(I);
00956     DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) << "\n");
00957     Nodes[*I] = Node;
00958   }
00959 
00960   Working.reserve(RPOT.size());
00961   for (size_t Index = 0; Index < RPOT.size(); ++Index)
00962     Working.emplace_back(Index);
00963   Freqs.resize(RPOT.size());
00964 }
00965 
00966 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
00967   DEBUG(dbgs() << "loop-detection\n");
00968   if (LI->empty())
00969     return;
00970 
00971   // Visit loops top down and assign them an index.
00972   std::deque<std::pair<const LoopT *, LoopData *>> Q;
00973   for (const LoopT *L : *LI)
00974     Q.emplace_back(L, nullptr);
00975   while (!Q.empty()) {
00976     const LoopT *Loop = Q.front().first;
00977     LoopData *Parent = Q.front().second;
00978     Q.pop_front();
00979 
00980     BlockNode Header = getNode(Loop->getHeader());
00981     assert(Header.isValid());
00982 
00983     Loops.emplace_back(Parent, Header);
00984     Working[Header.Index].Loop = &Loops.back();
00985     DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
00986 
00987     for (const LoopT *L : *Loop)
00988       Q.emplace_back(L, &Loops.back());
00989   }
00990 
00991   // Visit nodes in reverse post-order and add them to their deepest containing
00992   // loop.
00993   for (size_t Index = 0; Index < RPOT.size(); ++Index) {
00994     // Loop headers have already been mostly mapped.
00995     if (Working[Index].isLoopHeader()) {
00996       LoopData *ContainingLoop = Working[Index].getContainingLoop();
00997       if (ContainingLoop)
00998         ContainingLoop->Nodes.push_back(Index);
00999       continue;
01000     }
01001 
01002     const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
01003     if (!Loop)
01004       continue;
01005 
01006     // Add this node to its containing loop's member list.
01007     BlockNode Header = getNode(Loop->getHeader());
01008     assert(Header.isValid());
01009     const auto &HeaderData = Working[Header.Index];
01010     assert(HeaderData.isLoopHeader());
01011 
01012     Working[Index].Loop = HeaderData.Loop;
01013     HeaderData.Loop->Nodes.push_back(Index);
01014     DEBUG(dbgs() << " - loop = " << getBlockName(Header)
01015                  << ": member = " << getBlockName(Index) << "\n");
01016   }
01017 }
01018 
01019 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
01020   // Visit loops with the deepest first, and the top-level loops last.
01021   for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) {
01022     if (computeMassInLoop(*L))
01023       continue;
01024     auto Next = std::next(L);
01025     computeIrreducibleMass(&*L, L.base());
01026     L = std::prev(Next);
01027     if (computeMassInLoop(*L))
01028       continue;
01029     llvm_unreachable("unhandled irreducible control flow");
01030   }
01031 }
01032 
01033 template <class BT>
01034 bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
01035   // Compute mass in loop.
01036   DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop) << "\n");
01037 
01038   if (Loop.isIrreducible()) {
01039     BlockMass Remaining = BlockMass::getFull();
01040     for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
01041       auto &Mass = Working[Loop.Nodes[H].Index].getMass();
01042       Mass = Remaining * BranchProbability(1, Loop.NumHeaders - H);
01043       Remaining -= Mass;
01044     }
01045     for (const BlockNode &M : Loop.Nodes)
01046       if (!propagateMassToSuccessors(&Loop, M))
01047         llvm_unreachable("unhandled irreducible control flow");
01048   } else {
01049     Working[Loop.getHeader().Index].getMass() = BlockMass::getFull();
01050     if (!propagateMassToSuccessors(&Loop, Loop.getHeader()))
01051       llvm_unreachable("irreducible control flow to loop header!?");
01052     for (const BlockNode &M : Loop.members())
01053       if (!propagateMassToSuccessors(&Loop, M))
01054         // Irreducible backedge.
01055         return false;
01056   }
01057 
01058   computeLoopScale(Loop);
01059   packageLoop(Loop);
01060   return true;
01061 }
01062 
01063 template <class BT>
01064 bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
01065   // Compute mass in function.
01066   DEBUG(dbgs() << "compute-mass-in-function\n");
01067   assert(!Working.empty() && "no blocks in function");
01068   assert(!Working[0].isLoopHeader() && "entry block is a loop header");
01069 
01070   Working[0].getMass() = BlockMass::getFull();
01071   for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
01072     // Check for nodes that have been packaged.
01073     BlockNode Node = getNode(I);
01074     if (Working[Node.Index].isPackaged())
01075       continue;
01076 
01077     if (!propagateMassToSuccessors(nullptr, Node))
01078       return false;
01079   }
01080   return true;
01081 }
01082 
01083 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
01084   if (tryToComputeMassInFunction())
01085     return;
01086   computeIrreducibleMass(nullptr, Loops.begin());
01087   if (tryToComputeMassInFunction())
01088     return;
01089   llvm_unreachable("unhandled irreducible control flow");
01090 }
01091 
01092 /// \note This should be a lambda, but that crashes GCC 4.7.
01093 namespace bfi_detail {
01094 template <class BT> struct BlockEdgesAdder {
01095   typedef BT BlockT;
01096   typedef BlockFrequencyInfoImplBase::LoopData LoopData;
01097   typedef GraphTraits<const BlockT *> Successor;
01098 
01099   const BlockFrequencyInfoImpl<BT> &BFI;
01100   explicit BlockEdgesAdder(const BlockFrequencyInfoImpl<BT> &BFI)
01101       : BFI(BFI) {}
01102   void operator()(IrreducibleGraph &G, IrreducibleGraph::IrrNode &Irr,
01103                   const LoopData *OuterLoop) {
01104     const BlockT *BB = BFI.RPOT[Irr.Node.Index];
01105     for (auto I = Successor::child_begin(BB), E = Successor::child_end(BB);
01106          I != E; ++I)
01107       G.addEdge(Irr, BFI.getNode(*I), OuterLoop);
01108   }
01109 };
01110 }
01111 template <class BT>
01112 void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
01113     LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
01114   DEBUG(dbgs() << "analyze-irreducible-in-";
01115         if (OuterLoop) dbgs() << "loop: " << getLoopName(*OuterLoop) << "\n";
01116         else dbgs() << "function\n");
01117 
01118   using namespace bfi_detail;
01119   // Ideally, addBlockEdges() would be declared here as a lambda, but that
01120   // crashes GCC 4.7.
01121   BlockEdgesAdder<BT> addBlockEdges(*this);
01122   IrreducibleGraph G(*this, OuterLoop, addBlockEdges);
01123 
01124   for (auto &L : analyzeIrreducible(G, OuterLoop, Insert))
01125     computeMassInLoop(L);
01126 
01127   if (!OuterLoop)
01128     return;
01129   updateLoopWithIrreducible(*OuterLoop);
01130 }
01131 
01132 template <class BT>
01133 bool
01134 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
01135                                                       const BlockNode &Node) {
01136   DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
01137   // Calculate probability for successors.
01138   Distribution Dist;
01139   if (auto *Loop = Working[Node.Index].getPackagedLoop()) {
01140     assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop");
01141     if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
01142       // Irreducible backedge.
01143       return false;
01144   } else {
01145     const BlockT *BB = getBlock(Node);
01146     for (auto SI = Successor::child_begin(BB), SE = Successor::child_end(BB);
01147          SI != SE; ++SI)
01148       // Do not dereference SI, or getEdgeWeight() is linear in the number of
01149       // successors.
01150       if (!addToDist(Dist, OuterLoop, Node, getNode(*SI),
01151                      BPI->getEdgeWeight(BB, SI)))
01152         // Irreducible backedge.
01153         return false;
01154   }
01155 
01156   // Distribute mass to successors, saving exit and backedge data in the
01157   // loop header.
01158   distributeMass(Node, OuterLoop, Dist);
01159   return true;
01160 }
01161 
01162 template <class BT>
01163 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
01164   if (!F)
01165     return OS;
01166   OS << "block-frequency-info: " << F->getName() << "\n";
01167   for (const BlockT &BB : *F)
01168     OS << " - " << bfi_detail::getBlockName(&BB)
01169        << ": float = " << getFloatingBlockFreq(&BB)
01170        << ", int = " << getBlockFreq(&BB).getFrequency() << "\n";
01171 
01172   // Add an extra newline for readability.
01173   OS << "\n";
01174   return OS;
01175 }
01176 
01177 } // end namespace llvm
01178 
01179 #undef DEBUG_TYPE
01180 
01181 #endif