Coverage Report

Created: 2019-02-20 00:17

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