1 //==- BlockFrequencyInfoImpl.h - Block Frequency Implementation -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Shared implementation of BlockFrequency for IR and Machine Instructions.
11 // See the documentation below for BlockFrequencyInfoImpl for details.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
16 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/Support/BlockFrequency.h"
23 #include "llvm/Support/BranchProbability.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ScaledNumber.h"
26 #include "llvm/Support/raw_ostream.h"
32 #define DEBUG_TYPE "block-freq"
34 //===----------------------------------------------------------------------===//
36 // UnsignedFloat definition.
38 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
40 //===----------------------------------------------------------------------===//
43 class UnsignedFloatBase {
45 static const int32_t MaxExponent = 16383;
46 static const int32_t MinExponent = -16382;
47 static const int DefaultPrecision = 10;
49 static void dump(uint64_t D, int16_t E, int Width);
50 static raw_ostream &print(raw_ostream &OS, uint64_t D, int16_t E, int Width,
52 static std::string toString(uint64_t D, int16_t E, int Width,
54 static int countLeadingZeros32(uint32_t N) { return countLeadingZeros(N); }
55 static int countLeadingZeros64(uint64_t N) { return countLeadingZeros(N); }
56 static uint64_t getHalf(uint64_t N) { return (N >> 1) + (N & 1); }
58 static std::pair<uint64_t, bool> splitSigned(int64_t N) {
60 return std::make_pair(N, false);
61 uint64_t Unsigned = N == INT64_MIN ? UINT64_C(1) << 63 : uint64_t(-N);
62 return std::make_pair(Unsigned, true);
64 static int64_t joinSigned(uint64_t U, bool IsNeg) {
65 if (U > uint64_t(INT64_MAX))
66 return IsNeg ? INT64_MIN : INT64_MAX;
67 return IsNeg ? -int64_t(U) : int64_t(U);
71 /// \brief Simple representation of an unsigned floating point.
73 /// UnsignedFloat is a unsigned floating point number. It uses simple
74 /// saturation arithmetic, and every operation is well-defined for every value.
76 /// The number is split into a signed exponent and unsigned digits. The number
77 /// represented is \c getDigits()*2^getExponent(). In this way, the digits are
78 /// much like the mantissa in the x87 long double, but there is no canonical
79 /// form, so the same number can be represented by many bit representations
80 /// (it's always in "denormal" mode).
82 /// UnsignedFloat is templated on the underlying integer type for digits, which
83 /// is expected to be one of uint64_t, uint32_t, uint16_t or uint8_t.
85 /// Unlike builtin floating point types, UnsignedFloat is portable.
87 /// Unlike APFloat, UnsignedFloat does not model architecture floating point
88 /// behaviour (this should make it a little faster), and implements most
89 /// operators (this makes it usable).
91 /// UnsignedFloat is totally ordered. However, there is no canonical form, so
92 /// there are multiple representations of most scalars. E.g.:
94 /// UnsignedFloat(8u, 0) == UnsignedFloat(4u, 1)
95 /// UnsignedFloat(4u, 1) == UnsignedFloat(2u, 2)
96 /// UnsignedFloat(2u, 2) == UnsignedFloat(1u, 3)
98 /// UnsignedFloat implements most arithmetic operations. Precision is kept
99 /// where possible. Uses simple saturation arithmetic, so that operations
100 /// saturate to 0.0 or getLargest() rather than under or overflowing. It has
101 /// some extra arithmetic for unit inversion. 0.0/0.0 is defined to be 0.0.
102 /// Any other division by 0.0 is defined to be getLargest().
104 /// As a convenience for modifying the exponent, left and right shifting are
105 /// both implemented, and both interpret negative shifts as positive shifts in
106 /// the opposite direction.
108 /// Exponents are limited to the range accepted by x87 long double. This makes
109 /// it trivial to add functionality to convert to APFloat (this is already
110 /// relied on for the implementation of printing).
112 /// The current plan is to gut this and make the necessary parts of it (even
113 /// more) private to BlockFrequencyInfo.
114 template <class DigitsT> class UnsignedFloat : UnsignedFloatBase {
116 static_assert(!std::numeric_limits<DigitsT>::is_signed,
117 "only unsigned floats supported");
119 typedef DigitsT DigitsType;
122 typedef std::numeric_limits<DigitsType> DigitsLimits;
124 static const int Width = sizeof(DigitsType) * 8;
125 static_assert(Width <= 64, "invalid integer width for digits");
132 UnsignedFloat() : Digits(0), Exponent(0) {}
134 UnsignedFloat(DigitsType Digits, int16_t Exponent)
135 : Digits(Digits), Exponent(Exponent) {}
138 UnsignedFloat(const std::pair<uint64_t, int16_t> &X)
139 : Digits(X.first), Exponent(X.second) {}
142 static UnsignedFloat getZero() { return UnsignedFloat(0, 0); }
143 static UnsignedFloat getOne() { return UnsignedFloat(1, 0); }
144 static UnsignedFloat getLargest() {
145 return UnsignedFloat(DigitsLimits::max(), MaxExponent);
147 static UnsignedFloat getFloat(uint64_t N) { return adjustToWidth(N, 0); }
148 static UnsignedFloat getInverseFloat(uint64_t N) {
149 return getFloat(N).invert();
151 static UnsignedFloat getFraction(DigitsType N, DigitsType D) {
152 return getQuotient(N, D);
155 int16_t getExponent() const { return Exponent; }
156 DigitsType getDigits() const { return Digits; }
158 /// \brief Convert to the given integer type.
160 /// Convert to \c IntT using simple saturating arithmetic, truncating if
162 template <class IntT> IntT toInt() const;
164 bool isZero() const { return !Digits; }
165 bool isLargest() const { return *this == getLargest(); }
167 if (Exponent > 0 || Exponent <= -Width)
169 return Digits == DigitsType(1) << -Exponent;
172 /// \brief The log base 2, rounded.
174 /// Get the lg of the scalar. lg 0 is defined to be INT32_MIN.
175 int32_t lg() const { return ScaledNumbers::getLg(Digits, Exponent); }
177 /// \brief The log base 2, rounded towards INT32_MIN.
179 /// Get the lg floor. lg 0 is defined to be INT32_MIN.
180 int32_t lgFloor() const {
181 return ScaledNumbers::getLgFloor(Digits, Exponent);
184 /// \brief The log base 2, rounded towards INT32_MAX.
186 /// Get the lg ceiling. lg 0 is defined to be INT32_MIN.
187 int32_t lgCeiling() const {
188 return ScaledNumbers::getLgCeiling(Digits, Exponent);
191 bool operator==(const UnsignedFloat &X) const { return compare(X) == 0; }
192 bool operator<(const UnsignedFloat &X) const { return compare(X) < 0; }
193 bool operator!=(const UnsignedFloat &X) const { return compare(X) != 0; }
194 bool operator>(const UnsignedFloat &X) const { return compare(X) > 0; }
195 bool operator<=(const UnsignedFloat &X) const { return compare(X) <= 0; }
196 bool operator>=(const UnsignedFloat &X) const { return compare(X) >= 0; }
198 bool operator!() const { return isZero(); }
200 /// \brief Convert to a decimal representation in a string.
202 /// Convert to a string. Uses scientific notation for very large/small
203 /// numbers. Scientific notation is used roughly for numbers outside of the
204 /// range 2^-64 through 2^64.
206 /// \c Precision indicates the number of decimal digits of precision to use;
207 /// 0 requests the maximum available.
209 /// As a special case to make debugging easier, if the number is small enough
210 /// to convert without scientific notation and has more than \c Precision
211 /// digits before the decimal place, it's printed accurately to the first
212 /// digit past zero. E.g., assuming 10 digits of precision:
214 /// 98765432198.7654... => 98765432198.8
215 /// 8765432198.7654... => 8765432198.8
216 /// 765432198.7654... => 765432198.8
217 /// 65432198.7654... => 65432198.77
218 /// 5432198.7654... => 5432198.765
219 std::string toString(unsigned Precision = DefaultPrecision) {
220 return UnsignedFloatBase::toString(Digits, Exponent, Width, Precision);
223 /// \brief Print a decimal representation.
225 /// Print a string. See toString for documentation.
226 raw_ostream &print(raw_ostream &OS,
227 unsigned Precision = DefaultPrecision) const {
228 return UnsignedFloatBase::print(OS, Digits, Exponent, Width, Precision);
230 void dump() const { return UnsignedFloatBase::dump(Digits, Exponent, Width); }
232 UnsignedFloat &operator+=(const UnsignedFloat &X);
233 UnsignedFloat &operator-=(const UnsignedFloat &X);
234 UnsignedFloat &operator*=(const UnsignedFloat &X);
235 UnsignedFloat &operator/=(const UnsignedFloat &X);
236 UnsignedFloat &operator<<=(int16_t Shift) { shiftLeft(Shift); return *this; }
237 UnsignedFloat &operator>>=(int16_t Shift) { shiftRight(Shift); return *this; }
240 void shiftLeft(int32_t Shift);
241 void shiftRight(int32_t Shift);
243 /// \brief Adjust two floats to have matching exponents.
245 /// Adjust \c this and \c X to have matching exponents. Returns the new \c X
246 /// by value. Does nothing if \a isZero() for either.
248 /// The value that compares smaller will lose precision, and possibly become
250 UnsignedFloat matchExponents(UnsignedFloat X);
252 /// \brief Increase exponent to match another float.
254 /// Increases \c this to have an exponent matching \c X. May decrease the
255 /// exponent of \c X in the process, and \c this may possibly become \a
257 void increaseExponentToMatch(UnsignedFloat &X, int32_t ExponentDiff);
260 /// \brief Scale a large number accurately.
262 /// Scale N (multiply it by this). Uses full precision multiplication, even
263 /// if Width is smaller than 64, so information is not lost.
264 uint64_t scale(uint64_t N) const;
265 uint64_t scaleByInverse(uint64_t N) const {
266 // TODO: implement directly, rather than relying on inverse. Inverse is
268 return inverse().scale(N);
270 int64_t scale(int64_t N) const {
271 std::pair<uint64_t, bool> Unsigned = splitSigned(N);
272 return joinSigned(scale(Unsigned.first), Unsigned.second);
274 int64_t scaleByInverse(int64_t N) const {
275 std::pair<uint64_t, bool> Unsigned = splitSigned(N);
276 return joinSigned(scaleByInverse(Unsigned.first), Unsigned.second);
279 int compare(const UnsignedFloat &X) const {
280 return ScaledNumbers::compare(Digits, Exponent, X.Digits, X.Exponent);
282 int compareTo(uint64_t N) const {
283 UnsignedFloat Float = getFloat(N);
284 int Compare = compare(Float);
285 if (Width == 64 || Compare != 0)
288 // Check for precision loss. We know *this == RoundTrip.
289 uint64_t RoundTrip = Float.template toInt<uint64_t>();
290 return N == RoundTrip ? 0 : RoundTrip < N ? -1 : 1;
292 int compareTo(int64_t N) const { return N < 0 ? 1 : compareTo(uint64_t(N)); }
294 UnsignedFloat &invert() { return *this = UnsignedFloat::getFloat(1) / *this; }
295 UnsignedFloat inverse() const { return UnsignedFloat(*this).invert(); }
298 static UnsignedFloat getProduct(DigitsType LHS, DigitsType RHS) {
299 return ScaledNumbers::getProduct(LHS, RHS);
301 static UnsignedFloat getQuotient(DigitsType Dividend, DigitsType Divisor) {
302 return ScaledNumbers::getQuotient(Dividend, Divisor);
305 static int countLeadingZerosWidth(DigitsType Digits) {
307 return countLeadingZeros64(Digits);
309 return countLeadingZeros32(Digits);
310 return countLeadingZeros32(Digits) + Width - 32;
313 /// \brief Adjust a number to width, rounding up if necessary.
315 /// Should only be called for \c Shift close to zero.
317 /// \pre Shift >= MinExponent && Shift + 64 <= MaxExponent.
318 static UnsignedFloat adjustToWidth(uint64_t N, int32_t Shift) {
319 assert(Shift >= MinExponent && "Shift should be close to 0");
320 assert(Shift <= MaxExponent - 64 && "Shift should be close to 0");
321 auto Adjusted = ScaledNumbers::getAdjusted<DigitsT>(N, Shift);
325 static UnsignedFloat getRounded(UnsignedFloat P, bool Round) {
330 return ScaledNumbers::getRounded(P.Digits, P.Exponent, Round);
334 #define UNSIGNED_FLOAT_BOP(op, base) \
335 template <class DigitsT> \
336 UnsignedFloat<DigitsT> operator op(const UnsignedFloat<DigitsT> &L, \
337 const UnsignedFloat<DigitsT> &R) { \
338 return UnsignedFloat<DigitsT>(L) base R; \
340 UNSIGNED_FLOAT_BOP(+, += )
341 UNSIGNED_FLOAT_BOP(-, -= )
342 UNSIGNED_FLOAT_BOP(*, *= )
343 UNSIGNED_FLOAT_BOP(/, /= )
344 UNSIGNED_FLOAT_BOP(<<, <<= )
345 UNSIGNED_FLOAT_BOP(>>, >>= )
346 #undef UNSIGNED_FLOAT_BOP
348 template <class DigitsT>
349 raw_ostream &operator<<(raw_ostream &OS, const UnsignedFloat<DigitsT> &X) {
350 return X.print(OS, 10);
353 #define UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, T1, T2) \
354 template <class DigitsT> \
355 bool operator op(const UnsignedFloat<DigitsT> &L, T1 R) { \
356 return L.compareTo(T2(R)) op 0; \
358 template <class DigitsT> \
359 bool operator op(T1 L, const UnsignedFloat<DigitsT> &R) { \
360 return 0 op R.compareTo(T2(L)); \
362 #define UNSIGNED_FLOAT_COMPARE_TO(op) \
363 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, uint64_t, uint64_t) \
364 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, uint32_t, uint64_t) \
365 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, int64_t, int64_t) \
366 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, int32_t, int64_t)
367 UNSIGNED_FLOAT_COMPARE_TO(< )
368 UNSIGNED_FLOAT_COMPARE_TO(> )
369 UNSIGNED_FLOAT_COMPARE_TO(== )
370 UNSIGNED_FLOAT_COMPARE_TO(!= )
371 UNSIGNED_FLOAT_COMPARE_TO(<= )
372 UNSIGNED_FLOAT_COMPARE_TO(>= )
373 #undef UNSIGNED_FLOAT_COMPARE_TO
374 #undef UNSIGNED_FLOAT_COMPARE_TO_TYPE
376 template <class DigitsT>
377 uint64_t UnsignedFloat<DigitsT>::scale(uint64_t N) const {
378 if (Width == 64 || N <= DigitsLimits::max())
379 return (getFloat(N) * *this).template toInt<uint64_t>();
381 // Defer to the 64-bit version.
382 return UnsignedFloat<uint64_t>(Digits, Exponent).scale(N);
385 template <class DigitsT>
386 template <class IntT>
387 IntT UnsignedFloat<DigitsT>::toInt() const {
388 typedef std::numeric_limits<IntT> Limits;
391 if (*this >= Limits::max())
392 return Limits::max();
396 assert(size_t(Exponent) < sizeof(IntT) * 8);
397 return N << Exponent;
400 assert(size_t(-Exponent) < sizeof(IntT) * 8);
401 return N >> -Exponent;
406 template <class DigitsT>
407 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::matchExponents(UnsignedFloat X) {
408 if (isZero() || X.isZero() || Exponent == X.Exponent)
411 int32_t Diff = int32_t(X.Exponent) - int32_t(Exponent);
413 increaseExponentToMatch(X, Diff);
415 X.increaseExponentToMatch(*this, -Diff);
418 template <class DigitsT>
419 void UnsignedFloat<DigitsT>::increaseExponentToMatch(UnsignedFloat &X,
420 int32_t ExponentDiff) {
421 assert(ExponentDiff > 0);
422 if (ExponentDiff >= 2 * Width) {
427 // Use up any leading zeros on X, and then shift this.
428 int32_t ShiftX = std::min(countLeadingZerosWidth(X.Digits), ExponentDiff);
429 assert(ShiftX < Width);
431 int32_t ShiftThis = ExponentDiff - ShiftX;
432 if (ShiftThis >= Width) {
438 X.Exponent -= ShiftX;
439 Digits >>= ShiftThis;
440 Exponent += ShiftThis;
444 template <class DigitsT>
445 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
446 operator+=(const UnsignedFloat &X) {
447 if (isLargest() || X.isZero())
449 if (isZero() || X.isLargest())
452 // Normalize exponents.
453 UnsignedFloat Scaled = matchExponents(X);
455 // Check for zero again.
457 return *this = Scaled;
462 DigitsType Sum = Digits + Scaled.Digits;
463 bool DidOverflow = Sum < Digits;
468 if (Exponent == MaxExponent)
469 return *this = getLargest();
472 Digits = UINT64_C(1) << (Width - 1) | Digits >> 1;
476 template <class DigitsT>
477 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
478 operator-=(const UnsignedFloat &X) {
482 return *this = getZero();
484 // Normalize exponents.
485 UnsignedFloat Scaled = matchExponents(X);
486 assert(Digits >= Scaled.Digits);
488 // Compute difference.
489 if (!Scaled.isZero()) {
490 Digits -= Scaled.Digits;
494 // Check if X just barely lost its last bit. E.g., for 32-bit:
496 // 1*2^32 - 1*2^0 == 0xffffffff != 1*2^32
497 if (*this == UnsignedFloat(1, X.lgFloor() + Width)) {
498 Digits = DigitsType(0) - 1;
503 template <class DigitsT>
504 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
505 operator*=(const UnsignedFloat &X) {
511 // Save the exponents.
512 int32_t Exponents = int32_t(Exponent) + int32_t(X.Exponent);
514 // Get the raw product.
515 *this = getProduct(Digits, X.Digits);
517 // Combine with exponents.
518 return *this <<= Exponents;
520 template <class DigitsT>
521 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
522 operator/=(const UnsignedFloat &X) {
526 return *this = getLargest();
528 // Save the exponents.
529 int32_t Exponents = int32_t(Exponent) - int32_t(X.Exponent);
531 // Get the raw quotient.
532 *this = getQuotient(Digits, X.Digits);
534 // Combine with exponents.
535 return *this <<= Exponents;
537 template <class DigitsT>
538 void UnsignedFloat<DigitsT>::shiftLeft(int32_t Shift) {
539 if (!Shift || isZero())
541 assert(Shift != INT32_MIN);
547 // Shift as much as we can in the exponent.
548 int32_t ExponentShift = std::min(Shift, MaxExponent - Exponent);
549 Exponent += ExponentShift;
550 if (ExponentShift == Shift)
553 // Check this late, since it's rare.
557 // Shift the digits themselves.
558 Shift -= ExponentShift;
559 if (Shift > countLeadingZerosWidth(Digits)) {
561 *this = getLargest();
569 template <class DigitsT>
570 void UnsignedFloat<DigitsT>::shiftRight(int32_t Shift) {
571 if (!Shift || isZero())
573 assert(Shift != INT32_MIN);
579 // Shift as much as we can in the exponent.
580 int32_t ExponentShift = std::min(Shift, Exponent - MinExponent);
581 Exponent -= ExponentShift;
582 if (ExponentShift == Shift)
585 // Shift the digits themselves.
586 Shift -= ExponentShift;
587 if (Shift >= Width) {
597 template <class T> struct isPodLike<UnsignedFloat<T>> {
598 static const bool value = true;
602 //===----------------------------------------------------------------------===//
604 // BlockMass definition.
606 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
608 //===----------------------------------------------------------------------===//
611 /// \brief Mass of a block.
613 /// This class implements a sort of fixed-point fraction always between 0.0 and
614 /// 1.0. getMass() == UINT64_MAX indicates a value of 1.0.
616 /// Masses can be added and subtracted. Simple saturation arithmetic is used,
617 /// so arithmetic operations never overflow or underflow.
619 /// Masses can be multiplied. Multiplication treats full mass as 1.0 and uses
620 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not
621 /// quite, maximum precision).
623 /// Masses can be scaled by \a BranchProbability at maximum precision.
628 BlockMass() : Mass(0) {}
629 explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
631 static BlockMass getEmpty() { return BlockMass(); }
632 static BlockMass getFull() { return BlockMass(UINT64_MAX); }
634 uint64_t getMass() const { return Mass; }
636 bool isFull() const { return Mass == UINT64_MAX; }
637 bool isEmpty() const { return !Mass; }
639 bool operator!() const { return isEmpty(); }
641 /// \brief Add another mass.
643 /// Adds another mass, saturating at \a isFull() rather than overflowing.
644 BlockMass &operator+=(const BlockMass &X) {
645 uint64_t Sum = Mass + X.Mass;
646 Mass = Sum < Mass ? UINT64_MAX : Sum;
650 /// \brief Subtract another mass.
652 /// Subtracts another mass, saturating at \a isEmpty() rather than
654 BlockMass &operator-=(const BlockMass &X) {
655 uint64_t Diff = Mass - X.Mass;
656 Mass = Diff > Mass ? 0 : Diff;
660 BlockMass &operator*=(const BranchProbability &P) {
661 Mass = P.scale(Mass);
665 bool operator==(const BlockMass &X) const { return Mass == X.Mass; }
666 bool operator!=(const BlockMass &X) const { return Mass != X.Mass; }
667 bool operator<=(const BlockMass &X) const { return Mass <= X.Mass; }
668 bool operator>=(const BlockMass &X) const { return Mass >= X.Mass; }
669 bool operator<(const BlockMass &X) const { return Mass < X.Mass; }
670 bool operator>(const BlockMass &X) const { return Mass > X.Mass; }
672 /// \brief Convert to floating point.
674 /// Convert to a float. \a isFull() gives 1.0, while \a isEmpty() gives
675 /// slightly above 0.0.
676 UnsignedFloat<uint64_t> toFloat() const;
679 raw_ostream &print(raw_ostream &OS) const;
682 inline BlockMass operator+(const BlockMass &L, const BlockMass &R) {
683 return BlockMass(L) += R;
685 inline BlockMass operator-(const BlockMass &L, const BlockMass &R) {
686 return BlockMass(L) -= R;
688 inline BlockMass operator*(const BlockMass &L, const BranchProbability &R) {
689 return BlockMass(L) *= R;
691 inline BlockMass operator*(const BranchProbability &L, const BlockMass &R) {
692 return BlockMass(R) *= L;
695 inline raw_ostream &operator<<(raw_ostream &OS, const BlockMass &X) {
699 template <> struct isPodLike<BlockMass> {
700 static const bool value = true;
704 //===----------------------------------------------------------------------===//
706 // BlockFrequencyInfoImpl definition.
708 //===----------------------------------------------------------------------===//
712 class BranchProbabilityInfo;
716 class MachineBasicBlock;
717 class MachineBranchProbabilityInfo;
718 class MachineFunction;
720 class MachineLoopInfo;
722 namespace bfi_detail {
723 struct IrreducibleGraph;
725 // This is part of a workaround for a GCC 4.7 crash on lambdas.
726 template <class BT> struct BlockEdgesAdder;
729 /// \brief Base class for BlockFrequencyInfoImpl
731 /// BlockFrequencyInfoImplBase has supporting data structures and some
732 /// algorithms for BlockFrequencyInfoImplBase. Only algorithms that depend on
733 /// the block type (or that call such algorithms) are skipped here.
735 /// Nevertheless, the majority of the overall algorithm documention lives with
736 /// BlockFrequencyInfoImpl. See there for details.
737 class BlockFrequencyInfoImplBase {
739 typedef UnsignedFloat<uint64_t> Float;
741 /// \brief Representative of a block.
743 /// This is a simple wrapper around an index into the reverse-post-order
744 /// traversal of the blocks.
746 /// Unlike a block pointer, its order has meaning (location in the
747 /// topological sort) and it's class is the same regardless of block type.
749 typedef uint32_t IndexType;
752 bool operator==(const BlockNode &X) const { return Index == X.Index; }
753 bool operator!=(const BlockNode &X) const { return Index != X.Index; }
754 bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
755 bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
756 bool operator<(const BlockNode &X) const { return Index < X.Index; }
757 bool operator>(const BlockNode &X) const { return Index > X.Index; }
759 BlockNode() : Index(UINT32_MAX) {}
760 BlockNode(IndexType Index) : Index(Index) {}
762 bool isValid() const { return Index <= getMaxIndex(); }
763 static size_t getMaxIndex() { return UINT32_MAX - 1; }
766 /// \brief Stats about a block itself.
767 struct FrequencyData {
772 /// \brief Data about a loop.
774 /// Contains the data necessary to represent represent a loop as a
775 /// pseudo-node once it's packaged.
777 typedef SmallVector<std::pair<BlockNode, BlockMass>, 4> ExitMap;
778 typedef SmallVector<BlockNode, 4> NodeList;
779 LoopData *Parent; ///< The parent loop.
780 bool IsPackaged; ///< Whether this has been packaged.
781 uint32_t NumHeaders; ///< Number of headers.
782 ExitMap Exits; ///< Successor edges (and weights).
783 NodeList Nodes; ///< Header and the members of the loop.
784 BlockMass BackedgeMass; ///< Mass returned to loop header.
788 LoopData(LoopData *Parent, const BlockNode &Header)
789 : Parent(Parent), IsPackaged(false), NumHeaders(1), Nodes(1, Header) {}
790 template <class It1, class It2>
791 LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther,
793 : Parent(Parent), IsPackaged(false), Nodes(FirstHeader, LastHeader) {
794 NumHeaders = Nodes.size();
795 Nodes.insert(Nodes.end(), FirstOther, LastOther);
797 bool isHeader(const BlockNode &Node) const {
799 return std::binary_search(Nodes.begin(), Nodes.begin() + NumHeaders,
801 return Node == Nodes[0];
803 BlockNode getHeader() const { return Nodes[0]; }
804 bool isIrreducible() const { return NumHeaders > 1; }
806 NodeList::const_iterator members_begin() const {
807 return Nodes.begin() + NumHeaders;
809 NodeList::const_iterator members_end() const { return Nodes.end(); }
810 iterator_range<NodeList::const_iterator> members() const {
811 return make_range(members_begin(), members_end());
815 /// \brief Index of loop information.
817 BlockNode Node; ///< This node.
818 LoopData *Loop; ///< The loop this block is inside.
819 BlockMass Mass; ///< Mass distribution from the entry block.
821 WorkingData(const BlockNode &Node) : Node(Node), Loop(nullptr) {}
823 bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
824 bool isDoubleLoopHeader() const {
825 return isLoopHeader() && Loop->Parent && Loop->Parent->isIrreducible() &&
826 Loop->Parent->isHeader(Node);
829 LoopData *getContainingLoop() const {
832 if (!isDoubleLoopHeader())
834 return Loop->Parent->Parent;
837 /// \brief Resolve a node to its representative.
839 /// Get the node currently representing Node, which could be a containing
842 /// This function should only be called when distributing mass. As long as
843 /// there are no irreducilbe edges to Node, then it will have complexity
844 /// O(1) in this context.
846 /// In general, the complexity is O(L), where L is the number of loop
847 /// headers Node has been packaged into. Since this method is called in
848 /// the context of distributing mass, L will be the number of loop headers
849 /// an early exit edge jumps out of.
850 BlockNode getResolvedNode() const {
851 auto L = getPackagedLoop();
852 return L ? L->getHeader() : Node;
854 LoopData *getPackagedLoop() const {
855 if (!Loop || !Loop->IsPackaged)
858 while (L->Parent && L->Parent->IsPackaged)
863 /// \brief Get the appropriate mass for a node.
865 /// Get appropriate mass for Node. If Node is a loop-header (whose loop
866 /// has been packaged), returns the mass of its pseudo-node. If it's a
867 /// node inside a packaged loop, it returns the loop's mass.
868 BlockMass &getMass() {
871 if (!isADoublePackage())
873 return Loop->Parent->Mass;
876 /// \brief Has ContainingLoop been packaged up?
877 bool isPackaged() const { return getResolvedNode() != Node; }
878 /// \brief Has Loop been packaged up?
879 bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; }
880 /// \brief Has Loop been packaged up twice?
881 bool isADoublePackage() const {
882 return isDoubleLoopHeader() && Loop->Parent->IsPackaged;
886 /// \brief Unscaled probability weight.
888 /// Probability weight for an edge in the graph (including the
889 /// successor/target node).
891 /// All edges in the original function are 32-bit. However, exit edges from
892 /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
893 /// space in general.
895 /// In addition to the raw weight amount, Weight stores the type of the edge
896 /// in the current context (i.e., the context of the loop being processed).
897 /// Is this a local edge within the loop, an exit from the loop, or a
898 /// backedge to the loop header?
900 enum DistType { Local, Exit, Backedge };
902 BlockNode TargetNode;
904 Weight() : Type(Local), Amount(0) {}
907 /// \brief Distribution of unscaled probability weight.
909 /// Distribution of unscaled probability weight to a set of successors.
911 /// This class collates the successor edge weights for later processing.
913 /// \a DidOverflow indicates whether \a Total did overflow while adding to
914 /// the distribution. It should never overflow twice.
915 struct Distribution {
916 typedef SmallVector<Weight, 4> WeightList;
917 WeightList Weights; ///< Individual successor weights.
918 uint64_t Total; ///< Sum of all weights.
919 bool DidOverflow; ///< Whether \a Total did overflow.
921 Distribution() : Total(0), DidOverflow(false) {}
922 void addLocal(const BlockNode &Node, uint64_t Amount) {
923 add(Node, Amount, Weight::Local);
925 void addExit(const BlockNode &Node, uint64_t Amount) {
926 add(Node, Amount, Weight::Exit);
928 void addBackedge(const BlockNode &Node, uint64_t Amount) {
929 add(Node, Amount, Weight::Backedge);
932 /// \brief Normalize the distribution.
934 /// Combines multiple edges to the same \a Weight::TargetNode and scales
935 /// down so that \a Total fits into 32-bits.
937 /// This is linear in the size of \a Weights. For the vast majority of
938 /// cases, adjacent edge weights are combined by sorting WeightList and
939 /// combining adjacent weights. However, for very large edge lists an
940 /// auxiliary hash table is used.
944 void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
947 /// \brief Data about each block. This is used downstream.
948 std::vector<FrequencyData> Freqs;
950 /// \brief Loop data: see initializeLoops().
951 std::vector<WorkingData> Working;
953 /// \brief Indexed information about loops.
954 std::list<LoopData> Loops;
956 /// \brief Add all edges out of a packaged loop to the distribution.
958 /// Adds all edges from LocalLoopHead to Dist. Calls addToDist() to add each
961 /// \return \c true unless there's an irreducible backedge.
962 bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop,
965 /// \brief Add an edge to the distribution.
967 /// Adds an edge to Succ to Dist. If \c LoopHead.isValid(), then whether the
968 /// edge is local/exit/backedge is in the context of LoopHead. Otherwise,
969 /// every edge should be a local edge (since all the loops are packaged up).
971 /// \return \c true unless aborted due to an irreducible backedge.
972 bool addToDist(Distribution &Dist, const LoopData *OuterLoop,
973 const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
975 LoopData &getLoopPackage(const BlockNode &Head) {
976 assert(Head.Index < Working.size());
977 assert(Working[Head.Index].isLoopHeader());
978 return *Working[Head.Index].Loop;
981 /// \brief Analyze irreducible SCCs.
983 /// Separate irreducible SCCs from \c G, which is an explict graph of \c
984 /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr).
985 /// Insert them into \a Loops before \c Insert.
987 /// \return the \c LoopData nodes representing the irreducible SCCs.
988 iterator_range<std::list<LoopData>::iterator>
989 analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop,
990 std::list<LoopData>::iterator Insert);
992 /// \brief Update a loop after packaging irreducible SCCs inside of it.
994 /// Update \c OuterLoop. Before finding irreducible control flow, it was
995 /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a
996 /// LoopData::BackedgeMass need to be reset. Also, nodes that were packaged
997 /// up need to be removed from \a OuterLoop::Nodes.
998 void updateLoopWithIrreducible(LoopData &OuterLoop);
1000 /// \brief Distribute mass according to a distribution.
1002 /// Distributes the mass in Source according to Dist. If LoopHead.isValid(),
1003 /// backedges and exits are stored in its entry in Loops.
1005 /// Mass is distributed in parallel from two copies of the source mass.
1006 void distributeMass(const BlockNode &Source, LoopData *OuterLoop,
1007 Distribution &Dist);
1009 /// \brief Compute the loop scale for a loop.
1010 void computeLoopScale(LoopData &Loop);
1012 /// \brief Package up a loop.
1013 void packageLoop(LoopData &Loop);
1015 /// \brief Unwrap loops.
1018 /// \brief Finalize frequency metrics.
1020 /// Calculates final frequencies and cleans up no-longer-needed data
1022 void finalizeMetrics();
1024 /// \brief Clear all memory.
1027 virtual std::string getBlockName(const BlockNode &Node) const;
1028 std::string getLoopName(const LoopData &Loop) const;
1030 virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
1031 void dump() const { print(dbgs()); }
1033 Float getFloatingBlockFreq(const BlockNode &Node) const;
1035 BlockFrequency getBlockFreq(const BlockNode &Node) const;
1037 raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
1038 raw_ostream &printBlockFreq(raw_ostream &OS,
1039 const BlockFrequency &Freq) const;
1041 uint64_t getEntryFreq() const {
1042 assert(!Freqs.empty());
1043 return Freqs[0].Integer;
1045 /// \brief Virtual destructor.
1047 /// Need a virtual destructor to mask the compiler warning about
1049 virtual ~BlockFrequencyInfoImplBase() {}
1052 namespace bfi_detail {
1053 template <class BlockT> struct TypeMap {};
1054 template <> struct TypeMap<BasicBlock> {
1055 typedef BasicBlock BlockT;
1056 typedef Function FunctionT;
1057 typedef BranchProbabilityInfo BranchProbabilityInfoT;
1059 typedef LoopInfo LoopInfoT;
1061 template <> struct TypeMap<MachineBasicBlock> {
1062 typedef MachineBasicBlock BlockT;
1063 typedef MachineFunction FunctionT;
1064 typedef MachineBranchProbabilityInfo BranchProbabilityInfoT;
1065 typedef MachineLoop LoopT;
1066 typedef MachineLoopInfo LoopInfoT;
1069 /// \brief Get the name of a MachineBasicBlock.
1071 /// Get the name of a MachineBasicBlock. It's templated so that including from
1072 /// CodeGen is unnecessary (that would be a layering issue).
1074 /// This is used mainly for debug output. The name is similar to
1075 /// MachineBasicBlock::getFullName(), but skips the name of the function.
1076 template <class BlockT> std::string getBlockName(const BlockT *BB) {
1077 assert(BB && "Unexpected nullptr");
1078 auto MachineName = "BB" + Twine(BB->getNumber());
1079 if (BB->getBasicBlock())
1080 return (MachineName + "[" + BB->getName() + "]").str();
1081 return MachineName.str();
1083 /// \brief Get the name of a BasicBlock.
1084 template <> inline std::string getBlockName(const BasicBlock *BB) {
1085 assert(BB && "Unexpected nullptr");
1086 return BB->getName().str();
1089 /// \brief Graph of irreducible control flow.
1091 /// This graph is used for determining the SCCs in a loop (or top-level
1092 /// function) that has irreducible control flow.
1094 /// During the block frequency algorithm, the local graphs are defined in a
1095 /// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock
1096 /// graphs for most edges, but getting others from \a LoopData::ExitMap. The
1097 /// latter only has successor information.
1099 /// \a IrreducibleGraph makes this graph explicit. It's in a form that can use
1100 /// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator),
1101 /// and it explicitly lists predecessors and successors. The initialization
1102 /// that relies on \c MachineBasicBlock is defined in the header.
1103 struct IrreducibleGraph {
1104 typedef BlockFrequencyInfoImplBase BFIBase;
1108 typedef BFIBase::BlockNode BlockNode;
1112 std::deque<const IrrNode *> Edges;
1113 IrrNode(const BlockNode &Node) : Node(Node), NumIn(0) {}
1115 typedef std::deque<const IrrNode *>::const_iterator iterator;
1116 iterator pred_begin() const { return Edges.begin(); }
1117 iterator succ_begin() const { return Edges.begin() + NumIn; }
1118 iterator pred_end() const { return succ_begin(); }
1119 iterator succ_end() const { return Edges.end(); }
1122 const IrrNode *StartIrr;
1123 std::vector<IrrNode> Nodes;
1124 SmallDenseMap<uint32_t, IrrNode *, 4> Lookup;
1126 /// \brief Construct an explicit graph containing irreducible control flow.
1128 /// Construct an explicit graph of the control flow in \c OuterLoop (or the
1129 /// top-level function, if \c OuterLoop is \c nullptr). Uses \c
1130 /// addBlockEdges to add block successors that have not been packaged into
1133 /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected
1135 template <class BlockEdgesAdder>
1136 IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop,
1137 BlockEdgesAdder addBlockEdges)
1138 : BFI(BFI), StartIrr(nullptr) {
1139 initialize(OuterLoop, addBlockEdges);
1142 template <class BlockEdgesAdder>
1143 void initialize(const BFIBase::LoopData *OuterLoop,
1144 BlockEdgesAdder addBlockEdges);
1145 void addNodesInLoop(const BFIBase::LoopData &OuterLoop);
1146 void addNodesInFunction();
1147 void addNode(const BlockNode &Node) {
1148 Nodes.emplace_back(Node);
1149 BFI.Working[Node.Index].getMass() = BlockMass::getEmpty();
1152 template <class BlockEdgesAdder>
1153 void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop,
1154 BlockEdgesAdder addBlockEdges);
1155 void addEdge(IrrNode &Irr, const BlockNode &Succ,
1156 const BFIBase::LoopData *OuterLoop);
1158 template <class BlockEdgesAdder>
1159 void IrreducibleGraph::initialize(const BFIBase::LoopData *OuterLoop,
1160 BlockEdgesAdder addBlockEdges) {
1162 addNodesInLoop(*OuterLoop);
1163 for (auto N : OuterLoop->Nodes)
1164 addEdges(N, OuterLoop, addBlockEdges);
1166 addNodesInFunction();
1167 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
1168 addEdges(Index, OuterLoop, addBlockEdges);
1170 StartIrr = Lookup[Start.Index];
1172 template <class BlockEdgesAdder>
1173 void IrreducibleGraph::addEdges(const BlockNode &Node,
1174 const BFIBase::LoopData *OuterLoop,
1175 BlockEdgesAdder addBlockEdges) {
1176 auto L = Lookup.find(Node.Index);
1177 if (L == Lookup.end())
1179 IrrNode &Irr = *L->second;
1180 const auto &Working = BFI.Working[Node.Index];
1182 if (Working.isAPackage())
1183 for (const auto &I : Working.Loop->Exits)
1184 addEdge(Irr, I.first, OuterLoop);
1186 addBlockEdges(*this, Irr, OuterLoop);
1190 /// \brief Shared implementation for block frequency analysis.
1192 /// This is a shared implementation of BlockFrequencyInfo and
1193 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
1196 /// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block,
1197 /// which is called the header. A given loop, L, can have sub-loops, which are
1198 /// loops within the subgraph of L that exclude its header. (A "trivial" SCC
1199 /// consists of a single block that does not have a self-edge.)
1201 /// In addition to loops, this algorithm has limited support for irreducible
1202 /// SCCs, which are SCCs with multiple entry blocks. Irreducible SCCs are
1203 /// discovered on they fly, and modelled as loops with multiple headers.
1205 /// The headers of irreducible sub-SCCs consist of its entry blocks and all
1206 /// nodes that are targets of a backedge within it (excluding backedges within
1207 /// true sub-loops). Block frequency calculations act as if a block is
1208 /// inserted that intercepts all the edges to the headers. All backedges and
1209 /// entries point to this block. Its successors are the headers, which split
1210 /// the frequency evenly.
1212 /// This algorithm leverages BlockMass and UnsignedFloat to maintain precision,
1213 /// separates mass distribution from loop scaling, and dithers to eliminate
1214 /// probability mass loss.
1216 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
1217 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
1218 /// BlockFrequencyInfoImplBase, which doesn't. The base class uses \a
1219 /// BlockNode, a wrapper around a uint32_t. BlockNode is numbered from 0 in
1220 /// reverse-post order. This gives two advantages: it's easy to compare the
1221 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
1224 /// This algorithm is O(V+E), unless there is irreducible control flow, in
1225 /// which case it's O(V*E) in the worst case.
1227 /// These are the main stages:
1229 /// 0. Reverse post-order traversal (\a initializeRPOT()).
1231 /// Run a single post-order traversal and save it (in reverse) in RPOT.
1232 /// All other stages make use of this ordering. Save a lookup from BlockT
1233 /// to BlockNode (the index into RPOT) in Nodes.
1235 /// 1. Loop initialization (\a initializeLoops()).
1237 /// Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
1238 /// the algorithm. In particular, store the immediate members of each loop
1239 /// in reverse post-order.
1241 /// 2. Calculate mass and scale in loops (\a computeMassInLoops()).
1243 /// For each loop (bottom-up), distribute mass through the DAG resulting
1244 /// from ignoring backedges and treating sub-loops as a single pseudo-node.
1245 /// Track the backedge mass distributed to the loop header, and use it to
1246 /// calculate the loop scale (number of loop iterations). Immediate
1247 /// members that represent sub-loops will already have been visited and
1248 /// packaged into a pseudo-node.
1250 /// Distributing mass in a loop is a reverse-post-order traversal through
1251 /// the loop. Start by assigning full mass to the Loop header. For each
1252 /// node in the loop:
1254 /// - Fetch and categorize the weight distribution for its successors.
1255 /// If this is a packaged-subloop, the weight distribution is stored
1256 /// in \a LoopData::Exits. Otherwise, fetch it from
1257 /// BranchProbabilityInfo.
1259 /// - Each successor is categorized as \a Weight::Local, a local edge
1260 /// within the current loop, \a Weight::Backedge, a backedge to the
1261 /// loop header, or \a Weight::Exit, any successor outside the loop.
1262 /// The weight, the successor, and its category are stored in \a
1263 /// Distribution. There can be multiple edges to each successor.
1265 /// - If there's a backedge to a non-header, there's an irreducible SCC.
1266 /// The usual flow is temporarily aborted. \a
1267 /// computeIrreducibleMass() finds the irreducible SCCs within the
1268 /// loop, packages them up, and restarts the flow.
1270 /// - Normalize the distribution: scale weights down so that their sum
1271 /// is 32-bits, and coalesce multiple edges to the same node.
1273 /// - Distribute the mass accordingly, dithering to minimize mass loss,
1274 /// as described in \a distributeMass().
1276 /// Finally, calculate the loop scale from the accumulated backedge mass.
1278 /// 3. Distribute mass in the function (\a computeMassInFunction()).
1280 /// Finally, distribute mass through the DAG resulting from packaging all
1281 /// loops in the function. This uses the same algorithm as distributing
1282 /// mass in a loop, except that there are no exit or backedge edges.
1284 /// 4. Unpackage loops (\a unwrapLoops()).
1286 /// Initialize each block's frequency to a floating point representation of
1289 /// Visit loops top-down, scaling the frequencies of its immediate members
1290 /// by the loop's pseudo-node's frequency.
1292 /// 5. Convert frequencies to a 64-bit range (\a finalizeMetrics()).
1294 /// Using the min and max frequencies as a guide, translate floating point
1295 /// frequencies to an appropriate range in uint64_t.
1297 /// It has some known flaws.
1299 /// - Loop scale is limited to 4096 per loop (2^12) to avoid exhausting
1300 /// BlockFrequency's 64-bit integer precision.
1302 /// - The model of irreducible control flow is a rough approximation.
1304 /// Modelling irreducible control flow exactly involves setting up and
1305 /// solving a group of infinite geometric series. Such precision is
1306 /// unlikely to be worthwhile, since most of our algorithms give up on
1307 /// irreducible control flow anyway.
1309 /// Nevertheless, we might find that we need to get closer. Here's a sort
1310 /// of TODO list for the model with diminishing returns, to be completed as
1313 /// - The headers for the \a LoopData representing an irreducible SCC
1314 /// include non-entry blocks. When these extra blocks exist, they
1315 /// indicate a self-contained irreducible sub-SCC. We could treat them
1316 /// as sub-loops, rather than arbitrarily shoving the problematic
1317 /// blocks into the headers of the main irreducible SCC.
1319 /// - Backedge frequencies are assumed to be evenly split between the
1320 /// headers of a given irreducible SCC. Instead, we could track the
1321 /// backedge mass separately for each header, and adjust their relative
1324 /// - Entry frequencies are assumed to be evenly split between the
1325 /// headers of a given irreducible SCC, which is the only option if we
1326 /// need to compute mass in the SCC before its parent loop. Instead,
1327 /// we could partially compute mass in the parent loop, and stop when
1328 /// we get to the SCC. Here, we have the correct ratio of entry
1329 /// masses, which we can use to adjust their relative frequencies.
1330 /// Compute mass in the SCC, and then continue propagation in the
1333 /// - We can propagate mass iteratively through the SCC, for some fixed
1334 /// number of iterations. Each iteration starts by assigning the entry
1335 /// blocks their backedge mass from the prior iteration. The final
1336 /// mass for each block (and each exit, and the total backedge mass
1337 /// used for computing loop scale) is the sum of all iterations.
1338 /// (Running this until fixed point would "solve" the geometric
1339 /// series by simulation.)
1340 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
1341 typedef typename bfi_detail::TypeMap<BT>::BlockT BlockT;
1342 typedef typename bfi_detail::TypeMap<BT>::FunctionT FunctionT;
1343 typedef typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT
1344 BranchProbabilityInfoT;
1345 typedef typename bfi_detail::TypeMap<BT>::LoopT LoopT;
1346 typedef typename bfi_detail::TypeMap<BT>::LoopInfoT LoopInfoT;
1348 // This is part of a workaround for a GCC 4.7 crash on lambdas.
1349 friend struct bfi_detail::BlockEdgesAdder<BT>;
1351 typedef GraphTraits<const BlockT *> Successor;
1352 typedef GraphTraits<Inverse<const BlockT *>> Predecessor;
1354 const BranchProbabilityInfoT *BPI;
1355 const LoopInfoT *LI;
1358 // All blocks in reverse postorder.
1359 std::vector<const BlockT *> RPOT;
1360 DenseMap<const BlockT *, BlockNode> Nodes;
1362 typedef typename std::vector<const BlockT *>::const_iterator rpot_iterator;
1364 rpot_iterator rpot_begin() const { return RPOT.begin(); }
1365 rpot_iterator rpot_end() const { return RPOT.end(); }
1367 size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
1369 BlockNode getNode(const rpot_iterator &I) const {
1370 return BlockNode(getIndex(I));
1372 BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB); }
1374 const BlockT *getBlock(const BlockNode &Node) const {
1375 assert(Node.Index < RPOT.size());
1376 return RPOT[Node.Index];
1379 /// \brief Run (and save) a post-order traversal.
1381 /// Saves a reverse post-order traversal of all the nodes in \a F.
1382 void initializeRPOT();
1384 /// \brief Initialize loop data.
1386 /// Build up \a Loops using \a LoopInfo. \a LoopInfo gives us a mapping from
1387 /// each block to the deepest loop it's in, but we need the inverse. For each
1388 /// loop, we store in reverse post-order its "immediate" members, defined as
1389 /// the header, the headers of immediate sub-loops, and all other blocks in
1390 /// the loop that are not in sub-loops.
1391 void initializeLoops();
1393 /// \brief Propagate to a block's successors.
1395 /// In the context of distributing mass through \c OuterLoop, divide the mass
1396 /// currently assigned to \c Node between its successors.
1398 /// \return \c true unless there's an irreducible backedge.
1399 bool propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node);
1401 /// \brief Compute mass in a particular loop.
1403 /// Assign mass to \c Loop's header, and then for each block in \c Loop in
1404 /// reverse post-order, distribute mass to its successors. Only visits nodes
1405 /// that have not been packaged into sub-loops.
1407 /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
1408 /// \return \c true unless there's an irreducible backedge.
1409 bool computeMassInLoop(LoopData &Loop);
1411 /// \brief Try to compute mass in the top-level function.
1413 /// Assign mass to the entry block, and then for each block in reverse
1414 /// post-order, distribute mass to its successors. Skips nodes that have
1415 /// been packaged into loops.
1417 /// \pre \a computeMassInLoops() has been called.
1418 /// \return \c true unless there's an irreducible backedge.
1419 bool tryToComputeMassInFunction();
1421 /// \brief Compute mass in (and package up) irreducible SCCs.
1423 /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front
1424 /// of \c Insert), and call \a computeMassInLoop() on each of them.
1426 /// If \c OuterLoop is \c nullptr, it refers to the top-level function.
1428 /// \pre \a computeMassInLoop() has been called for each subloop of \c
1430 /// \pre \c Insert points at the the last loop successfully processed by \a
1431 /// computeMassInLoop().
1432 /// \pre \c OuterLoop has irreducible SCCs.
1433 void computeIrreducibleMass(LoopData *OuterLoop,
1434 std::list<LoopData>::iterator Insert);
1436 /// \brief Compute mass in all loops.
1438 /// For each loop bottom-up, call \a computeMassInLoop().
1440 /// \a computeMassInLoop() aborts (and returns \c false) on loops that
1441 /// contain a irreducible sub-SCCs. Use \a computeIrreducibleMass() and then
1442 /// re-enter \a computeMassInLoop().
1444 /// \post \a computeMassInLoop() has returned \c true for every loop.
1445 void computeMassInLoops();
1447 /// \brief Compute mass in the top-level function.
1449 /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to
1450 /// compute mass in the top-level function.
1452 /// \post \a tryToComputeMassInFunction() has returned \c true.
1453 void computeMassInFunction();
1455 std::string getBlockName(const BlockNode &Node) const override {
1456 return bfi_detail::getBlockName(getBlock(Node));
1460 const FunctionT *getFunction() const { return F; }
1462 void doFunction(const FunctionT *F, const BranchProbabilityInfoT *BPI,
1463 const LoopInfoT *LI);
1464 BlockFrequencyInfoImpl() : BPI(nullptr), LI(nullptr), F(nullptr) {}
1466 using BlockFrequencyInfoImplBase::getEntryFreq;
1467 BlockFrequency getBlockFreq(const BlockT *BB) const {
1468 return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
1470 Float getFloatingBlockFreq(const BlockT *BB) const {
1471 return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
1474 /// \brief Print the frequencies for the current function.
1476 /// Prints the frequencies for the blocks in the current function.
1478 /// Blocks are printed in the natural iteration order of the function, rather
1479 /// than reverse post-order. This provides two advantages: writing -analyze
1480 /// tests is easier (since blocks come out in source order), and even
1481 /// unreachable blocks are printed.
1483 /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
1484 /// we need to override it here.
1485 raw_ostream &print(raw_ostream &OS) const override;
1486 using BlockFrequencyInfoImplBase::dump;
1488 using BlockFrequencyInfoImplBase::printBlockFreq;
1489 raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
1490 return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
1495 void BlockFrequencyInfoImpl<BT>::doFunction(const FunctionT *F,
1496 const BranchProbabilityInfoT *BPI,
1497 const LoopInfoT *LI) {
1498 // Save the parameters.
1503 // Clean up left-over data structures.
1504 BlockFrequencyInfoImplBase::clear();
1509 DEBUG(dbgs() << "\nblock-frequency: " << F->getName() << "\n================="
1510 << std::string(F->getName().size(), '=') << "\n");
1514 // Visit loops in post-order to find thelocal mass distribution, and then do
1515 // the full function.
1516 computeMassInLoops();
1517 computeMassInFunction();
1522 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1523 const BlockT *Entry = F->begin();
1524 RPOT.reserve(F->size());
1525 std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
1526 std::reverse(RPOT.begin(), RPOT.end());
1528 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1529 "More nodes in function than Block Frequency Info supports");
1531 DEBUG(dbgs() << "reverse-post-order-traversal\n");
1532 for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
1533 BlockNode Node = getNode(I);
1534 DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) << "\n");
1538 Working.reserve(RPOT.size());
1539 for (size_t Index = 0; Index < RPOT.size(); ++Index)
1540 Working.emplace_back(Index);
1541 Freqs.resize(RPOT.size());
1544 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1545 DEBUG(dbgs() << "loop-detection\n");
1549 // Visit loops top down and assign them an index.
1550 std::deque<std::pair<const LoopT *, LoopData *>> Q;
1551 for (const LoopT *L : *LI)
1552 Q.emplace_back(L, nullptr);
1553 while (!Q.empty()) {
1554 const LoopT *Loop = Q.front().first;
1555 LoopData *Parent = Q.front().second;
1558 BlockNode Header = getNode(Loop->getHeader());
1559 assert(Header.isValid());
1561 Loops.emplace_back(Parent, Header);
1562 Working[Header.Index].Loop = &Loops.back();
1563 DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1565 for (const LoopT *L : *Loop)
1566 Q.emplace_back(L, &Loops.back());
1569 // Visit nodes in reverse post-order and add them to their deepest containing
1571 for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1572 // Loop headers have already been mostly mapped.
1573 if (Working[Index].isLoopHeader()) {
1574 LoopData *ContainingLoop = Working[Index].getContainingLoop();
1576 ContainingLoop->Nodes.push_back(Index);
1580 const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1584 // Add this node to its containing loop's member list.
1585 BlockNode Header = getNode(Loop->getHeader());
1586 assert(Header.isValid());
1587 const auto &HeaderData = Working[Header.Index];
1588 assert(HeaderData.isLoopHeader());
1590 Working[Index].Loop = HeaderData.Loop;
1591 HeaderData.Loop->Nodes.push_back(Index);
1592 DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1593 << ": member = " << getBlockName(Index) << "\n");
1597 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1598 // Visit loops with the deepest first, and the top-level loops last.
1599 for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) {
1600 if (computeMassInLoop(*L))
1602 auto Next = std::next(L);
1603 computeIrreducibleMass(&*L, L.base());
1604 L = std::prev(Next);
1605 if (computeMassInLoop(*L))
1607 llvm_unreachable("unhandled irreducible control flow");
1612 bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
1613 // Compute mass in loop.
1614 DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop) << "\n");
1616 if (Loop.isIrreducible()) {
1617 BlockMass Remaining = BlockMass::getFull();
1618 for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
1619 auto &Mass = Working[Loop.Nodes[H].Index].getMass();
1620 Mass = Remaining * BranchProbability(1, Loop.NumHeaders - H);
1623 for (const BlockNode &M : Loop.Nodes)
1624 if (!propagateMassToSuccessors(&Loop, M))
1625 llvm_unreachable("unhandled irreducible control flow");
1627 Working[Loop.getHeader().Index].getMass() = BlockMass::getFull();
1628 if (!propagateMassToSuccessors(&Loop, Loop.getHeader()))
1629 llvm_unreachable("irreducible control flow to loop header!?");
1630 for (const BlockNode &M : Loop.members())
1631 if (!propagateMassToSuccessors(&Loop, M))
1632 // Irreducible backedge.
1636 computeLoopScale(Loop);
1642 bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
1643 // Compute mass in function.
1644 DEBUG(dbgs() << "compute-mass-in-function\n");
1645 assert(!Working.empty() && "no blocks in function");
1646 assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1648 Working[0].getMass() = BlockMass::getFull();
1649 for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
1650 // Check for nodes that have been packaged.
1651 BlockNode Node = getNode(I);
1652 if (Working[Node.Index].isPackaged())
1655 if (!propagateMassToSuccessors(nullptr, Node))
1661 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1662 if (tryToComputeMassInFunction())
1664 computeIrreducibleMass(nullptr, Loops.begin());
1665 if (tryToComputeMassInFunction())
1667 llvm_unreachable("unhandled irreducible control flow");
1670 /// \note This should be a lambda, but that crashes GCC 4.7.
1671 namespace bfi_detail {
1672 template <class BT> struct BlockEdgesAdder {
1674 typedef BlockFrequencyInfoImplBase::LoopData LoopData;
1675 typedef GraphTraits<const BlockT *> Successor;
1677 const BlockFrequencyInfoImpl<BT> &BFI;
1678 explicit BlockEdgesAdder(const BlockFrequencyInfoImpl<BT> &BFI)
1680 void operator()(IrreducibleGraph &G, IrreducibleGraph::IrrNode &Irr,
1681 const LoopData *OuterLoop) {
1682 const BlockT *BB = BFI.RPOT[Irr.Node.Index];
1683 for (auto I = Successor::child_begin(BB), E = Successor::child_end(BB);
1685 G.addEdge(Irr, BFI.getNode(*I), OuterLoop);
1690 void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1691 LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1692 DEBUG(dbgs() << "analyze-irreducible-in-";
1693 if (OuterLoop) dbgs() << "loop: " << getLoopName(*OuterLoop) << "\n";
1694 else dbgs() << "function\n");
1696 using namespace bfi_detail;
1697 // Ideally, addBlockEdges() would be declared here as a lambda, but that
1699 BlockEdgesAdder<BT> addBlockEdges(*this);
1700 IrreducibleGraph G(*this, OuterLoop, addBlockEdges);
1702 for (auto &L : analyzeIrreducible(G, OuterLoop, Insert))
1703 computeMassInLoop(L);
1707 updateLoopWithIrreducible(*OuterLoop);
1712 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1713 const BlockNode &Node) {
1714 DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1715 // Calculate probability for successors.
1717 if (auto *Loop = Working[Node.Index].getPackagedLoop()) {
1718 assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop");
1719 if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
1720 // Irreducible backedge.
1723 const BlockT *BB = getBlock(Node);
1724 for (auto SI = Successor::child_begin(BB), SE = Successor::child_end(BB);
1726 // Do not dereference SI, or getEdgeWeight() is linear in the number of
1728 if (!addToDist(Dist, OuterLoop, Node, getNode(*SI),
1729 BPI->getEdgeWeight(BB, SI)))
1730 // Irreducible backedge.
1734 // Distribute mass to successors, saving exit and backedge data in the
1736 distributeMass(Node, OuterLoop, Dist);
1741 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
1744 OS << "block-frequency-info: " << F->getName() << "\n";
1745 for (const BlockT &BB : *F)
1746 OS << " - " << bfi_detail::getBlockName(&BB)
1747 << ": float = " << getFloatingBlockFreq(&BB)
1748 << ", int = " << getBlockFreq(&BB).getFrequency() << "\n";
1750 // Add an extra newline for readability.