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