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.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
15 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/PostOrderIterator.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/Support/BlockFrequency.h"
21 #include "llvm/Support/BranchProbability.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
27 //===----------------------------------------------------------------------===//
29 // UnsignedFloat definition.
31 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
33 //===----------------------------------------------------------------------===//
36 class UnsignedFloatBase {
38 static const int32_t MaxExponent = 16383;
39 static const int32_t MinExponent = -16382;
40 static const int DefaultPrecision = 10;
42 static void dump(uint64_t D, int16_t E, int Width);
43 static raw_ostream &print(raw_ostream &OS, uint64_t D, int16_t E, int Width,
45 static std::string toString(uint64_t D, int16_t E, int Width,
47 static int countLeadingZeros32(uint32_t N) { return countLeadingZeros(N); }
48 static int countLeadingZeros64(uint64_t N) { return countLeadingZeros(N); }
49 static uint64_t getHalf(uint64_t N) { return (N >> 1) + (N & 1); }
51 static std::pair<uint64_t, bool> splitSigned(int64_t N) {
53 return std::make_pair(N, false);
54 uint64_t Unsigned = N == INT64_MIN ? UINT64_C(1) << 63 : uint64_t(-N);
55 return std::make_pair(Unsigned, true);
57 static int64_t joinSigned(uint64_t U, bool IsNeg) {
58 if (U > uint64_t(INT64_MAX))
59 return IsNeg ? INT64_MIN : INT64_MAX;
60 return IsNeg ? -int64_t(U) : int64_t(U);
63 static int32_t extractLg(const std::pair<int32_t, int> &Lg) {
66 static int32_t extractLgFloor(const std::pair<int32_t, int> &Lg) {
67 return Lg.first - (Lg.second > 0);
69 static int32_t extractLgCeiling(const std::pair<int32_t, int> &Lg) {
70 return Lg.first + (Lg.second < 0);
73 static std::pair<uint64_t, int16_t> divide64(uint64_t L, uint64_t R);
74 static std::pair<uint64_t, int16_t> multiply64(uint64_t L, uint64_t R);
76 static int compare(uint64_t L, uint64_t R, int Shift) {
80 uint64_t L_adjusted = L >> Shift;
86 return L > L_adjusted << Shift ? 1 : 0;
90 /// \brief Simple representation of an unsigned floating point.
92 /// UnsignedFloat is a unsigned floating point number. It uses simple
93 /// saturation arithmetic, and every operation is well-defined for every value.
95 /// The number is split into a signed exponent and unsigned digits. The number
96 /// represented is \c getDigits()*2^getExponent(). In this way, the digits are
97 /// much like the mantissa in the x87 long double, but there is no canonical
98 /// form, so the same number can be represented by many bit representations
99 /// (it's always in "denormal" mode).
101 /// UnsignedFloat is templated on the underlying integer type for digits, which
102 /// is expected to be one of uint64_t, uint32_t, uint16_t or uint8_t.
104 /// Unlike builtin floating point types, UnsignedFloat is portable.
106 /// Unlike APFloat, UnsignedFloat does not model architecture floating point
107 /// behaviour (this should make it a little faster), and implements most
108 /// operators (this makes it usable).
110 /// UnsignedFloat is totally ordered. However, there is no canonical form, so
111 /// there are multiple representations of most scalars. E.g.:
113 /// UnsignedFloat(8u, 0) == UnsignedFloat(4u, 1)
114 /// UnsignedFloat(4u, 1) == UnsignedFloat(2u, 2)
115 /// UnsignedFloat(2u, 2) == UnsignedFloat(1u, 3)
117 /// UnsignedFloat implements most arithmetic operations. Precision is kept
118 /// where possible. Uses simple saturation arithmetic, so that operations
119 /// saturate to 0.0 or getLargest() rather than under or overflowing. It has
120 /// some extra arithmetic for unit inversion. 0.0/0.0 is defined to be 0.0.
121 /// Any other division by 0.0 is defined to be getLargest().
123 /// As a convenience for modifying the exponent, left and right shifting are
124 /// both implemented, and both interpret negative shifts as positive shifts in
125 /// the opposite direction.
127 /// Exponents are limited to the range accepted by x87 long double. This makes
128 /// it trivial to add functionality to convert to APFloat (this is already
129 /// relied on for the implementation of printing).
131 /// The current plan is to gut this and make the necessary parts of it (even
132 /// more) private to BlockFrequencyInfo.
133 template <class DigitsT> class UnsignedFloat : UnsignedFloatBase {
135 static_assert(!std::numeric_limits<DigitsT>::is_signed,
136 "only unsigned floats supported");
138 typedef DigitsT DigitsType;
141 typedef std::numeric_limits<DigitsType> DigitsLimits;
143 static const int Width = sizeof(DigitsType) * 8;
144 static_assert(Width <= 64, "invalid integer width for digits");
151 UnsignedFloat() : Digits(0), Exponent(0) {}
153 UnsignedFloat(DigitsType Digits, int16_t Exponent)
154 : Digits(Digits), Exponent(Exponent) {}
157 UnsignedFloat(const std::pair<uint64_t, int16_t> &X)
158 : Digits(X.first), Exponent(X.second) {}
161 static UnsignedFloat getZero() { return UnsignedFloat(0, 0); }
162 static UnsignedFloat getOne() { return UnsignedFloat(1, 0); }
163 static UnsignedFloat getLargest() {
164 return UnsignedFloat(DigitsLimits::max(), MaxExponent);
166 static UnsignedFloat getFloat(uint64_t N) { return adjustToWidth(N, 0); }
167 static UnsignedFloat getInverseFloat(uint64_t N) {
168 return getFloat(N).invert();
170 static UnsignedFloat getFraction(DigitsType N, DigitsType D) {
171 return getQuotient(N, D);
174 int16_t getExponent() const { return Exponent; }
175 DigitsType getDigits() const { return Digits; }
177 /// \brief Convert to the given integer type.
179 /// Convert to \c IntT using simple saturating arithmetic, truncating if
181 template <class IntT> IntT toInt() const;
183 bool isZero() const { return !Digits; }
184 bool isLargest() const { return *this == getLargest(); }
186 if (Exponent > 0 || Exponent <= -Width)
188 return Digits == DigitsType(1) << -Exponent;
191 /// \brief The log base 2, rounded.
193 /// Get the lg of the scalar. lg 0 is defined to be INT32_MIN.
194 int32_t lg() const { return extractLg(lgImpl()); }
196 /// \brief The log base 2, rounded towards INT32_MIN.
198 /// Get the lg floor. lg 0 is defined to be INT32_MIN.
199 int32_t lgFloor() const { return extractLgFloor(lgImpl()); }
201 /// \brief The log base 2, rounded towards INT32_MAX.
203 /// Get the lg ceiling. lg 0 is defined to be INT32_MIN.
204 int32_t lgCeiling() const { return extractLgCeiling(lgImpl()); }
206 bool operator==(const UnsignedFloat &X) const { return compare(X) == 0; }
207 bool operator<(const UnsignedFloat &X) const { return compare(X) < 0; }
208 bool operator!=(const UnsignedFloat &X) const { return compare(X) != 0; }
209 bool operator>(const UnsignedFloat &X) const { return compare(X) > 0; }
210 bool operator<=(const UnsignedFloat &X) const { return compare(X) <= 0; }
211 bool operator>=(const UnsignedFloat &X) const { return compare(X) >= 0; }
213 bool operator!() const { return isZero(); }
215 /// \brief Convert to a decimal representation in a string.
217 /// Convert to a string. Uses scientific notation for very large/small
218 /// numbers. Scientific notation is used roughly for numbers outside of the
219 /// range 2^-64 through 2^64.
221 /// \c Precision indicates the number of decimal digits of precision to use;
222 /// 0 requests the maximum available.
224 /// As a special case to make debugging easier, if the number is small enough
225 /// to convert without scientific notation and has more than \c Precision
226 /// digits before the decimal place, it's printed accurately to the first
227 /// digit past zero. E.g., assuming 10 digits of precision:
229 /// 98765432198.7654... => 98765432198.8
230 /// 8765432198.7654... => 8765432198.8
231 /// 765432198.7654... => 765432198.8
232 /// 65432198.7654... => 65432198.77
233 /// 5432198.7654... => 5432198.765
234 std::string toString(unsigned Precision = DefaultPrecision) {
235 return UnsignedFloatBase::toString(Digits, Exponent, Width, Precision);
238 /// \brief Print a decimal representation.
240 /// Print a string. See toString for documentation.
241 raw_ostream &print(raw_ostream &OS,
242 unsigned Precision = DefaultPrecision) const {
243 return UnsignedFloatBase::print(OS, Digits, Exponent, Width, Precision);
245 void dump() const { return UnsignedFloatBase::dump(Digits, Exponent, Width); }
247 UnsignedFloat &operator+=(const UnsignedFloat &X);
248 UnsignedFloat &operator-=(const UnsignedFloat &X);
249 UnsignedFloat &operator*=(const UnsignedFloat &X);
250 UnsignedFloat &operator/=(const UnsignedFloat &X);
251 UnsignedFloat &operator<<=(int16_t Shift) { shiftLeft(Shift); return *this; }
252 UnsignedFloat &operator>>=(int16_t Shift) { shiftRight(Shift); return *this; }
255 void shiftLeft(int32_t Shift);
256 void shiftRight(int32_t Shift);
258 /// \brief Adjust two floats to have matching exponents.
260 /// Adjust \c this and \c X to have matching exponents. Returns the new \c X
261 /// by value. Does nothing if \a isZero() for either.
263 /// The value that compares smaller will lose precision, and possibly become
265 UnsignedFloat matchExponents(UnsignedFloat X);
267 /// \brief Increase exponent to match another float.
269 /// Increases \c this to have an exponent matching \c X. May decrease the
270 /// exponent of \c X in the process, and \c this may possibly become \a
272 void increaseExponentToMatch(UnsignedFloat &X, int32_t ExponentDiff);
275 /// \brief Scale a large number accurately.
277 /// Scale N (multiply it by this). Uses full precision multiplication, even
278 /// if Width is smaller than 64, so information is not lost.
279 uint64_t scale(uint64_t N) const;
280 uint64_t scaleByInverse(uint64_t N) const {
281 // TODO: implement directly, rather than relying on inverse. Inverse is
283 return inverse().scale(N);
285 int64_t scale(int64_t N) const {
286 std::pair<uint64_t, bool> Unsigned = splitSigned(N);
287 return joinSigned(scale(Unsigned.first), Unsigned.second);
289 int64_t scaleByInverse(int64_t N) const {
290 std::pair<uint64_t, bool> Unsigned = splitSigned(N);
291 return joinSigned(scaleByInverse(Unsigned.first), Unsigned.second);
294 int compare(const UnsignedFloat &X) const;
295 int compareTo(uint64_t N) const {
296 UnsignedFloat Float = getFloat(N);
297 int Compare = compare(Float);
298 if (Width == 64 || Compare != 0)
301 // Check for precision loss. We know *this == RoundTrip.
302 uint64_t RoundTrip = Float.template toInt<uint64_t>();
303 return N == RoundTrip ? 0 : RoundTrip < N ? -1 : 1;
305 int compareTo(int64_t N) const { return N < 0 ? 1 : compareTo(uint64_t(N)); }
307 UnsignedFloat &invert() { return *this = UnsignedFloat::getFloat(1) / *this; }
308 UnsignedFloat inverse() const { return UnsignedFloat(*this).invert(); }
311 static UnsignedFloat getProduct(DigitsType L, DigitsType R);
312 static UnsignedFloat getQuotient(DigitsType Dividend, DigitsType Divisor);
314 std::pair<int32_t, int> lgImpl() const;
315 static int countLeadingZerosWidth(DigitsType Digits) {
317 return countLeadingZeros64(Digits);
319 return countLeadingZeros32(Digits);
320 return countLeadingZeros32(Digits) + Width - 32;
323 static UnsignedFloat adjustToWidth(uint64_t N, int32_t S) {
324 assert(S >= MinExponent);
325 assert(S <= MaxExponent);
326 if (Width == 64 || N <= DigitsLimits::max())
327 return UnsignedFloat(N, S);
330 int Shift = 64 - Width - countLeadingZeros64(N);
331 DigitsType Shifted = N >> Shift;
334 assert(S + Shift <= MaxExponent);
335 return getRounded(UnsignedFloat(Shifted, S + Shift),
336 N & UINT64_C(1) << (Shift - 1));
339 static UnsignedFloat getRounded(UnsignedFloat P, bool Round) {
342 if (P.Digits == DigitsLimits::max())
343 // Careful of overflow in the exponent.
344 return UnsignedFloat(1, P.Exponent) <<= Width;
345 return UnsignedFloat(P.Digits + 1, P.Exponent);
349 #define UNSIGNED_FLOAT_BOP(op, base) \
350 template <class DigitsT> \
351 UnsignedFloat<DigitsT> operator op(const UnsignedFloat<DigitsT> &L, \
352 const UnsignedFloat<DigitsT> &R) { \
353 return UnsignedFloat<DigitsT>(L) base R; \
355 UNSIGNED_FLOAT_BOP(+, += )
356 UNSIGNED_FLOAT_BOP(-, -= )
357 UNSIGNED_FLOAT_BOP(*, *= )
358 UNSIGNED_FLOAT_BOP(/, /= )
359 UNSIGNED_FLOAT_BOP(<<, <<= )
360 UNSIGNED_FLOAT_BOP(>>, >>= )
361 #undef UNSIGNED_FLOAT_BOP
363 template <class DigitsT>
364 raw_ostream &operator<<(raw_ostream &OS, const UnsignedFloat<DigitsT> &X) {
365 return X.print(OS, 10);
368 #define UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, T1, T2) \
369 template <class DigitsT> \
370 bool operator op(const UnsignedFloat<DigitsT> &L, T1 R) { \
371 return L.compareTo(T2(R)) op 0; \
373 template <class DigitsT> \
374 bool operator op(T1 L, const UnsignedFloat<DigitsT> &R) { \
375 return 0 op R.compareTo(T2(L)); \
377 #define UNSIGNED_FLOAT_COMPARE_TO(op) \
378 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, uint64_t, uint64_t) \
379 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, uint32_t, uint64_t) \
380 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, int64_t, int64_t) \
381 UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, int32_t, int64_t)
382 UNSIGNED_FLOAT_COMPARE_TO(< )
383 UNSIGNED_FLOAT_COMPARE_TO(> )
384 UNSIGNED_FLOAT_COMPARE_TO(== )
385 UNSIGNED_FLOAT_COMPARE_TO(!= )
386 UNSIGNED_FLOAT_COMPARE_TO(<= )
387 UNSIGNED_FLOAT_COMPARE_TO(>= )
388 #undef UNSIGNED_FLOAT_COMPARE_TO
389 #undef UNSIGNED_FLOAT_COMPARE_TO_TYPE
391 template <class DigitsT>
392 uint64_t UnsignedFloat<DigitsT>::scale(uint64_t N) const {
393 if (Width == 64 || N <= DigitsLimits::max())
394 return (getFloat(N) * *this).template toInt<uint64_t>();
396 // Defer to the 64-bit version.
397 return UnsignedFloat<uint64_t>(Digits, Exponent).scale(N);
400 template <class DigitsT>
401 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::getProduct(DigitsType L,
407 // Check for numbers that we can compute with 64-bit math.
408 if (Width <= 32 || (L <= UINT32_MAX && R <= UINT32_MAX))
409 return adjustToWidth(uint64_t(L) * uint64_t(R), 0);
411 // Do the full thing.
412 return UnsignedFloat(multiply64(L, R));
414 template <class DigitsT>
415 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::getQuotient(DigitsType Dividend,
416 DigitsType Divisor) {
424 return UnsignedFloat(divide64(Dividend, Divisor));
426 // We can compute this with 64-bit math.
427 int Shift = countLeadingZeros64(Dividend);
428 uint64_t Shifted = uint64_t(Dividend) << Shift;
429 uint64_t Quotient = Shifted / Divisor;
431 // If Quotient needs to be shifted, then adjustToWidth will round.
432 if (Quotient > DigitsLimits::max())
433 return adjustToWidth(Quotient, -Shift);
435 // Round based on the value of the next bit.
436 return getRounded(UnsignedFloat(Quotient, -Shift),
437 Shifted % Divisor >= getHalf(Divisor));
440 template <class DigitsT>
441 template <class IntT>
442 IntT UnsignedFloat<DigitsT>::toInt() const {
443 typedef std::numeric_limits<IntT> Limits;
446 if (*this >= Limits::max())
447 return Limits::max();
451 assert(size_t(Exponent) < sizeof(IntT) * 8);
452 return N << Exponent;
455 assert(size_t(-Exponent) < sizeof(IntT) * 8);
456 return N >> -Exponent;
461 template <class DigitsT>
462 std::pair<int32_t, int> UnsignedFloat<DigitsT>::lgImpl() const {
464 return std::make_pair(INT32_MIN, 0);
466 // Get the floor of the lg of Digits.
467 int32_t LocalFloor = Width - countLeadingZerosWidth(Digits) - 1;
469 // Get the floor of the lg of this.
470 int32_t Floor = Exponent + LocalFloor;
471 if (Digits == UINT64_C(1) << LocalFloor)
472 return std::make_pair(Floor, 0);
474 // Round based on the next digit.
475 assert(LocalFloor >= 1);
476 bool Round = Digits & UINT64_C(1) << (LocalFloor - 1);
477 return std::make_pair(Floor + Round, Round ? 1 : -1);
480 template <class DigitsT>
481 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::matchExponents(UnsignedFloat X) {
482 if (isZero() || X.isZero() || Exponent == X.Exponent)
485 int32_t Diff = int32_t(X.Exponent) - int32_t(Exponent);
487 increaseExponentToMatch(X, Diff);
489 X.increaseExponentToMatch(*this, -Diff);
492 template <class DigitsT>
493 void UnsignedFloat<DigitsT>::increaseExponentToMatch(UnsignedFloat &X,
494 int32_t ExponentDiff) {
495 assert(ExponentDiff > 0);
496 if (ExponentDiff >= 2 * Width) {
501 // Use up any leading zeros on X, and then shift this.
502 int32_t ShiftX = std::min(countLeadingZerosWidth(X.Digits), ExponentDiff);
503 assert(ShiftX < Width);
505 int32_t ShiftThis = ExponentDiff - ShiftX;
506 if (ShiftThis >= Width) {
512 X.Exponent -= ShiftX;
513 Digits >>= ShiftThis;
514 Exponent += ShiftThis;
518 template <class DigitsT>
519 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
520 operator+=(const UnsignedFloat &X) {
521 if (isLargest() || X.isZero())
523 if (isZero() || X.isLargest())
526 // Normalize exponents.
527 UnsignedFloat Scaled = matchExponents(X);
529 // Check for zero again.
531 return *this = Scaled;
536 DigitsType Sum = Digits + Scaled.Digits;
537 bool DidOverflow = Sum < Digits;
542 if (Exponent == MaxExponent)
543 return *this = getLargest();
546 Digits = UINT64_C(1) << (Width - 1) | Digits >> 1;
550 template <class DigitsT>
551 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
552 operator-=(const UnsignedFloat &X) {
556 return *this = getZero();
558 // Normalize exponents.
559 UnsignedFloat Scaled = matchExponents(X);
560 assert(Digits >= Scaled.Digits);
562 // Compute difference.
563 if (!Scaled.isZero()) {
564 Digits -= Scaled.Digits;
568 // Check if X just barely lost its last bit. E.g., for 32-bit:
570 // 1*2^32 - 1*2^0 == 0xffffffff != 1*2^32
571 if (*this == UnsignedFloat(1, X.lgFloor() + Width)) {
572 Digits = DigitsType(0) - 1;
577 template <class DigitsT>
578 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
579 operator*=(const UnsignedFloat &X) {
585 // Save the exponents.
586 int32_t Exponents = int32_t(Exponent) + int32_t(X.Exponent);
588 // Get the raw product.
589 *this = getProduct(Digits, X.Digits);
591 // Combine with exponents.
592 return *this <<= Exponents;
594 template <class DigitsT>
595 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
596 operator/=(const UnsignedFloat &X) {
600 return *this = getLargest();
602 // Save the exponents.
603 int32_t Exponents = int32_t(Exponent) - int32_t(X.Exponent);
605 // Get the raw quotient.
606 *this = getQuotient(Digits, X.Digits);
608 // Combine with exponents.
609 return *this <<= Exponents;
611 template <class DigitsT>
612 void UnsignedFloat<DigitsT>::shiftLeft(int32_t Shift) {
613 if (!Shift || isZero())
615 assert(Shift != INT32_MIN);
621 // Shift as much as we can in the exponent.
622 int32_t ExponentShift = std::min(Shift, MaxExponent - Exponent);
623 Exponent += ExponentShift;
624 if (ExponentShift == Shift)
627 // Check this late, since it's rare.
631 // Shift the digits themselves.
632 Shift -= ExponentShift;
633 if (Shift > countLeadingZerosWidth(Digits)) {
635 *this = getLargest();
643 template <class DigitsT>
644 void UnsignedFloat<DigitsT>::shiftRight(int32_t Shift) {
645 if (!Shift || isZero())
647 assert(Shift != INT32_MIN);
653 // Shift as much as we can in the exponent.
654 int32_t ExponentShift = std::min(Shift, Exponent - MinExponent);
655 Exponent -= ExponentShift;
656 if (ExponentShift == Shift)
659 // Shift the digits themselves.
660 Shift -= ExponentShift;
661 if (Shift >= Width) {
671 template <class DigitsT>
672 int UnsignedFloat<DigitsT>::compare(const UnsignedFloat &X) const {
675 return X.isZero() ? 0 : -1;
679 // Check for the scale. Use lgFloor to be sure that the exponent difference
680 // is always lower than 64.
681 int32_t lgL = lgFloor(), lgR = X.lgFloor();
683 return lgL < lgR ? -1 : 1;
686 if (Exponent < X.Exponent)
687 return UnsignedFloatBase::compare(Digits, X.Digits, X.Exponent - Exponent);
689 return -UnsignedFloatBase::compare(X.Digits, Digits, Exponent - X.Exponent);
692 template <class T> struct isPodLike<UnsignedFloat<T>> {
693 static const bool value = true;
697 //===----------------------------------------------------------------------===//
699 // BlockMass definition.
701 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
703 //===----------------------------------------------------------------------===//
706 /// \brief Mass of a block.
708 /// This class implements a sort of fixed-point fraction always between 0.0 and
709 /// 1.0. getMass() == UINT64_MAX indicates a value of 1.0.
711 /// Masses can be added and subtracted. Simple saturation arithmetic is used,
712 /// so arithmetic operations never overflow or underflow.
714 /// Masses can be multiplied. Multiplication treats full mass as 1.0 and uses
715 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not
716 /// quite, maximum precision).
718 /// Masses can be scaled by \a BranchProbability at maximum precision.
723 BlockMass() : Mass(0) {}
724 explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
726 static BlockMass getEmpty() { return BlockMass(); }
727 static BlockMass getFull() { return BlockMass(UINT64_MAX); }
729 uint64_t getMass() const { return Mass; }
731 bool isFull() const { return Mass == UINT64_MAX; }
732 bool isEmpty() const { return !Mass; }
734 bool operator!() const { return isEmpty(); }
736 /// \brief Add another mass.
738 /// Adds another mass, saturating at \a isFull() rather than overflowing.
739 BlockMass &operator+=(const BlockMass &X) {
740 uint64_t Sum = Mass + X.Mass;
741 Mass = Sum < Mass ? UINT64_MAX : Sum;
745 /// \brief Subtract another mass.
747 /// Subtracts another mass, saturating at \a isEmpty() rather than
749 BlockMass &operator-=(const BlockMass &X) {
750 uint64_t Diff = Mass - X.Mass;
751 Mass = Diff > Mass ? 0 : Diff;
755 /// \brief Scale by another mass.
757 /// The current implementation is a little imprecise, but it's relatively
758 /// fast, never overflows, and maintains the property that 1.0*1.0==1.0
759 /// (where isFull represents the number 1.0). It's an approximation of
760 /// 128-bit multiply that gets right-shifted by 64-bits.
762 /// For a given digit size, multiplying two-digit numbers looks like:
768 /// + 0 . U1*L2 . 0 // (shift left once by a digit-size)
769 /// + 0 . U2*L1 . 0 // (shift left once by a digit-size)
770 /// + U1*L2 . 0 . 0 // (shift left twice by a digit-size)
772 /// BlockMass has 64-bit numbers. Split each into two 32-bit digits, stored
773 /// 64-bit. Add 1 to the lower digits, to model isFull as 1.0; this won't
774 /// overflow, since we have 64-bit storage for each digit.
776 /// To do this accurately, (a) multiply into two 64-bit digits, incrementing
777 /// the upper digit on overflows of the lower digit (carry), (b) subtract 1
778 /// from the lower digit, decrementing the upper digit on underflow (carry),
779 /// and (c) truncate the lower digit. For the 1.0*1.0 case, the upper digit
780 /// will be 0 at the end of step (a), and then will underflow back to isFull
781 /// (1.0) in step (b).
783 /// Instead, the implementation does something a little faster with a small
784 /// loss of accuracy: ignore the lower 64-bit digit entirely. The loss of
785 /// accuracy is small, since the sum of the unmodelled carries is 0 or 1
786 /// (i.e., step (a) will overflow at most once, and step (b) will underflow
787 /// only if step (a) overflows).
789 /// This is the formula we're calculating:
791 /// U1.L1 * U2.L2 == U1 * U2 + (U1 * (L2+1))>>32 + (U2 * (L1+1))>>32
793 /// As a demonstration of 1.0*1.0, consider two 4-bit numbers that are both
796 /// U1.L1 * U2.L2 == U1 * U2 + (U1 * (L2+1))>>2 + (U2 * (L1+1))>>2
797 /// 11.11 * 11.11 == 11 * 11 + (11 * (11+1))/4 + (11 * (11+1))/4
798 /// == 1001 + (11 * 100)/4 + (11 * 100)/4
799 /// == 1001 + 1100/4 + 1100/4
800 /// == 1001 + 0011 + 0011
802 BlockMass &operator*=(const BlockMass &X) {
803 uint64_t U1 = Mass >> 32, L1 = Mass & UINT32_MAX, U2 = X.Mass >> 32,
804 L2 = X.Mass & UINT32_MAX;
805 Mass = U1 * U2 + (U1 * (L2 + 1) >> 32) + ((L1 + 1) * U2 >> 32);
809 /// \brief Multiply by a branch probability.
811 /// Multiply by P. Guarantees full precision.
813 /// This could be naively implemented by multiplying by the numerator and
814 /// dividing by the denominator, but in what order? Multiplying first can
815 /// overflow, while dividing first will lose precision (potentially, changing
816 /// a non-zero mass to zero).
818 /// The implementation mixes the two methods. Since \a BranchProbability
819 /// uses 32-bits and \a BlockMass 64-bits, shift the mass as far to the left
820 /// as there is room, then divide by the denominator to get a quotient.
821 /// Multiplying by the numerator and right shifting gives a first
824 /// Calculate the error in this first approximation by calculating the
825 /// opposite mass (multiply by the opposite numerator and shift) and
826 /// subtracting both from teh original mass.
828 /// Add to the first approximation the correct fraction of this error value.
829 /// This time, multiply first and then divide, since there is no danger of
832 /// \pre P represents a fraction between 0.0 and 1.0.
833 BlockMass &operator*=(const BranchProbability &P);
835 bool operator==(const BlockMass &X) const { return Mass == X.Mass; }
836 bool operator!=(const BlockMass &X) const { return Mass != X.Mass; }
837 bool operator<=(const BlockMass &X) const { return Mass <= X.Mass; }
838 bool operator>=(const BlockMass &X) const { return Mass >= X.Mass; }
839 bool operator<(const BlockMass &X) const { return Mass < X.Mass; }
840 bool operator>(const BlockMass &X) const { return Mass > X.Mass; }
842 /// \brief Convert to floating point.
844 /// Convert to a float. \a isFull() gives 1.0, while \a isEmpty() gives
845 /// slightly above 0.0.
846 UnsignedFloat<uint64_t> toFloat() const;
849 raw_ostream &print(raw_ostream &OS) const;
852 inline BlockMass operator+(const BlockMass &L, const BlockMass &R) {
853 return BlockMass(L) += R;
855 inline BlockMass operator-(const BlockMass &L, const BlockMass &R) {
856 return BlockMass(L) -= R;
858 inline BlockMass operator*(const BlockMass &L, const BlockMass &R) {
859 return BlockMass(L) *= R;
861 inline BlockMass operator*(const BlockMass &L, const BranchProbability &R) {
862 return BlockMass(L) *= R;
864 inline BlockMass operator*(const BranchProbability &L, const BlockMass &R) {
865 return BlockMass(R) *= L;
868 inline raw_ostream &operator<<(raw_ostream &OS, const BlockMass &X) {
872 template <> struct isPodLike<BlockMass> {
873 static const bool value = true;
877 //===----------------------------------------------------------------------===//
879 // BlockFrequencyInfoImpl definition.
881 //===----------------------------------------------------------------------===//
885 class BranchProbabilityInfo;
889 class MachineBasicBlock;
890 class MachineBranchProbabilityInfo;
891 class MachineFunction;
893 class MachineLoopInfo;
895 /// \brief Base class for BlockFrequencyInfoImpl
897 /// BlockFrequencyInfoImplBase has supporting data structures and some
898 /// algorithms for BlockFrequencyInfoImplBase. Only algorithms that depend on
899 /// the block type (or that call such algorithms) are skipped here.
901 /// Nevertheless, the majority of the overall algorithm documention lives with
902 /// BlockFrequencyInfoImpl. See there for details.
903 class BlockFrequencyInfoImplBase {
905 typedef UnsignedFloat<uint64_t> Float;
907 /// \brief Representative of a block.
909 /// This is a simple wrapper around an index into the reverse-post-order
910 /// traversal of the blocks.
912 /// Unlike a block pointer, its order has meaning (location in the
913 /// topological sort) and it's class is the same regardless of block type.
915 typedef uint32_t IndexType;
918 bool operator==(const BlockNode &X) const { return Index == X.Index; }
919 bool operator!=(const BlockNode &X) const { return Index != X.Index; }
920 bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
921 bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
922 bool operator<(const BlockNode &X) const { return Index < X.Index; }
923 bool operator>(const BlockNode &X) const { return Index > X.Index; }
925 BlockNode() : Index(UINT32_MAX) {}
926 BlockNode(IndexType Index) : Index(Index) {}
928 bool isValid() const { return Index <= getMaxIndex(); }
929 static size_t getMaxIndex() { return UINT32_MAX - 1; }
932 /// \brief Stats about a block itself.
933 struct FrequencyData {
938 /// \brief Index of loop information.
940 BlockNode ContainingLoop; ///< The block whose loop this block is inside.
941 uint32_t LoopIndex; ///< Index into PackagedLoops.
942 bool IsPackaged; ///< Has ContainingLoop been packaged up?
943 bool IsAPackage; ///< Has this block's loop been packaged up?
944 BlockMass Mass; ///< Mass distribution from the entry block.
947 : LoopIndex(UINT32_MAX), IsPackaged(false), IsAPackage(false) {}
949 bool hasLoopHeader() const { return ContainingLoop.isValid(); }
950 bool isLoopHeader() const { return LoopIndex != UINT32_MAX; }
953 /// \brief Unscaled probability weight.
955 /// Probability weight for an edge in the graph (including the
956 /// successor/target node).
958 /// All edges in the original function are 32-bit. However, exit edges from
959 /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
960 /// space in general.
962 /// In addition to the raw weight amount, Weight stores the type of the edge
963 /// in the current context (i.e., the context of the loop being processed).
964 /// Is this a local edge within the loop, an exit from the loop, or a
965 /// backedge to the loop header?
967 enum DistType { Local, Exit, Backedge };
969 BlockNode TargetNode;
971 Weight() : Type(Local), Amount(0) {}
974 /// \brief Distribution of unscaled probability weight.
976 /// Distribution of unscaled probability weight to a set of successors.
978 /// This class collates the successor edge weights for later processing.
980 /// \a DidOverflow indicates whether \a Total did overflow while adding to
981 /// the distribution. It should never overflow twice. There's no flag for
982 /// whether \a ForwardTotal overflows, since when \a Total exceeds 32-bits
983 /// they both get re-computed during \a normalize().
984 struct Distribution {
985 typedef SmallVector<Weight, 4> WeightList;
986 WeightList Weights; ///< Individual successor weights.
987 uint64_t Total; ///< Sum of all weights.
988 bool DidOverflow; ///< Whether \a Total did overflow.
989 uint32_t ForwardTotal; ///< Total excluding backedges.
991 Distribution() : Total(0), DidOverflow(false), ForwardTotal(0) {}
992 void addLocal(const BlockNode &Node, uint64_t Amount) {
993 add(Node, Amount, Weight::Local);
995 void addExit(const BlockNode &Node, uint64_t Amount) {
996 add(Node, Amount, Weight::Exit);
998 void addBackedge(const BlockNode &Node, uint64_t Amount) {
999 add(Node, Amount, Weight::Backedge);
1002 /// \brief Normalize the distribution.
1004 /// Combines multiple edges to the same \a Weight::TargetNode and scales
1005 /// down so that \a Total fits into 32-bits.
1007 /// This is linear in the size of \a Weights. For the vast majority of
1008 /// cases, adjacent edge weights are combined by sorting WeightList and
1009 /// combining adjacent weights. However, for very large edge lists an
1010 /// auxiliary hash table is used.
1014 void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
1017 /// \brief Data for a packaged loop.
1019 /// Contains the data necessary to represent represent a loop as a node once
1022 /// PackagedLoopData inherits from BlockData to give the node the necessary
1023 /// stats. Further, it has a list of successors, list of members, and stores
1024 /// the backedge mass assigned to this loop.
1025 struct PackagedLoopData {
1026 typedef SmallVector<std::pair<BlockNode, BlockMass>, 4> ExitMap;
1027 typedef SmallVector<BlockNode, 4> MemberList;
1028 BlockNode Header; ///< Header.
1029 ExitMap Exits; ///< Successor edges (and weights).
1030 MemberList Members; ///< Members of the loop.
1031 BlockMass BackedgeMass; ///< Mass returned to loop header.
1035 PackagedLoopData(const BlockNode &Header) : Header(Header) {}
1038 /// \brief Data about each block. This is used downstream.
1039 std::vector<FrequencyData> Freqs;
1041 /// \brief Loop data: see initializeLoops().
1042 std::vector<WorkingData> Working;
1044 /// \brief Indexed information about packaged loops.
1045 std::vector<PackagedLoopData> PackagedLoops;
1047 /// \brief Create the initial loop packages.
1049 /// Initializes PackagedLoops using the data in Working about backedges
1050 /// and containing loops. Called by initializeLoops().
1052 /// \post WorkingData::LoopIndex has been initialized for every loop header
1053 /// and PackagedLoopData::Members has been initialized.
1055 /// \brief Add all edges out of a packaged loop to the distribution.
1057 /// Adds all edges from LocalLoopHead to Dist. Calls addToDist() to add each
1059 void addLoopSuccessorsToDist(const BlockNode &LoopHead,
1060 const BlockNode &LocalLoopHead,
1061 Distribution &Dist);
1063 /// \brief Add an edge to the distribution.
1065 /// Adds an edge to Succ to Dist. If \c LoopHead.isValid(), then whether the
1066 /// edge is forward/exit/backedge is in the context of LoopHead. Otherwise,
1067 /// every edge should be a forward edge (since all the loops are packaged
1069 void addToDist(Distribution &Dist, const BlockNode &LoopHead,
1070 const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
1072 PackagedLoopData &getLoopPackage(const BlockNode &Head) {
1073 assert(Head.Index < Working.size());
1074 size_t Index = Working[Head.Index].LoopIndex;
1075 assert(Index < PackagedLoops.size());
1076 return PackagedLoops[Index];
1079 /// \brief Distribute mass according to a distribution.
1081 /// Distributes the mass in Source according to Dist. If LoopHead.isValid(),
1082 /// backedges and exits are stored in its entry in PackagedLoops.
1084 /// Mass is distributed in parallel from two copies of the source mass.
1086 /// The first mass (forward) represents the distribution of mass through the
1087 /// local DAG. This distribution should lose mass at loop exits and ignore
1090 /// The second mass (general) represents the behavior of the loop in the
1091 /// global context. In a given distribution from the head, how much mass
1092 /// exits, and to where? How much mass returns to the loop head?
1094 /// The forward mass should be split up between local successors and exits,
1095 /// but only actually distributed to the local successors. The general mass
1096 /// should be split up between all three types of successors, but distributed
1097 /// only to exits and backedges.
1098 void distributeMass(const BlockNode &Source, const BlockNode &LoopHead,
1099 Distribution &Dist);
1101 /// \brief Compute the loop scale for a loop.
1102 void computeLoopScale(const BlockNode &LoopHead);
1104 /// \brief Package up a loop.
1105 void packageLoop(const BlockNode &LoopHead);
1107 /// \brief Finalize frequency metrics.
1109 /// Unwraps loop packages, calculates final frequencies, and cleans up
1110 /// no-longer-needed data structures.
1111 void finalizeMetrics();
1113 /// \brief Clear all memory.
1116 virtual std::string getBlockName(const BlockNode &Node) const;
1118 virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
1119 void dump() const { print(dbgs()); }
1121 Float getFloatingBlockFreq(const BlockNode &Node) const;
1123 BlockFrequency getBlockFreq(const BlockNode &Node) const;
1125 raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
1126 raw_ostream &printBlockFreq(raw_ostream &OS,
1127 const BlockFrequency &Freq) const;
1129 uint64_t getEntryFreq() const {
1130 assert(!Freqs.empty());
1131 return Freqs[0].Integer;
1133 /// \brief Virtual destructor.
1135 /// Need a virtual destructor to mask the compiler warning about
1137 virtual ~BlockFrequencyInfoImplBase() {}
1140 namespace bfi_detail {
1141 template <class BlockT> struct TypeMap {};
1142 template <> struct TypeMap<BasicBlock> {
1143 typedef BasicBlock BlockT;
1144 typedef Function FunctionT;
1145 typedef BranchProbabilityInfo BranchProbabilityInfoT;
1147 typedef LoopInfo LoopInfoT;
1149 template <> struct TypeMap<MachineBasicBlock> {
1150 typedef MachineBasicBlock BlockT;
1151 typedef MachineFunction FunctionT;
1152 typedef MachineBranchProbabilityInfo BranchProbabilityInfoT;
1153 typedef MachineLoop LoopT;
1154 typedef MachineLoopInfo LoopInfoT;
1157 /// \brief Get the name of a MachineBasicBlock.
1159 /// Get the name of a MachineBasicBlock. It's templated so that including from
1160 /// CodeGen is unnecessary (that would be a layering issue).
1162 /// This is used mainly for debug output. The name is similar to
1163 /// MachineBasicBlock::getFullName(), but skips the name of the function.
1164 template <class BlockT> std::string getBlockName(const BlockT *BB) {
1165 assert(BB && "Unexpected nullptr");
1166 auto MachineName = "BB" + Twine(BB->getNumber());
1167 if (BB->getBasicBlock())
1168 return (MachineName + "[" + BB->getName() + "]").str();
1169 return MachineName.str();
1171 /// \brief Get the name of a BasicBlock.
1172 template <> inline std::string getBlockName(const BasicBlock *BB) {
1173 assert(BB && "Unexpected nullptr");
1174 return BB->getName().str();
1178 /// \brief Shared implementation for block frequency analysis.
1180 /// This is a shared implementation of BlockFrequencyInfo and
1181 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
1184 /// This algorithm leverages BlockMass and UnsignedFloat to maintain precision,
1185 /// separates mass distribution from loop scaling, and dithers to eliminate
1186 /// probability mass loss.
1188 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
1189 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
1190 /// BlockFrequencyInfoImplBase, which doesn't. The base class uses \a
1191 /// BlockNode, a wrapper around a uint32_t. BlockNode is numbered from 0 in
1192 /// reverse-post order. This gives two advantages: it's easy to compare the
1193 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
1196 /// This algorithm is O(V+E), unless there is irreducible control flow, in
1197 /// which case it's O(V*E) in the worst case.
1199 /// These are the main stages:
1201 /// 0. Reverse post-order traversal (\a initializeRPOT()).
1203 /// Run a single post-order traversal and save it (in reverse) in RPOT.
1204 /// All other stages make use of this ordering. Save a lookup from BlockT
1205 /// to BlockNode (the index into RPOT) in Nodes.
1207 /// 1. Loop indexing (\a initializeLoops()).
1209 /// Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
1210 /// the algorithm. In particular, store the immediate members of each loop
1211 /// in reverse post-order.
1213 /// 2. Calculate mass and scale in loops (\a computeMassInLoops()).
1215 /// For each loop (bottom-up), distribute mass through the DAG resulting
1216 /// from ignoring backedges and treating sub-loops as a single pseudo-node.
1217 /// Track the backedge mass distributed to the loop header, and use it to
1218 /// calculate the loop scale (number of loop iterations).
1220 /// Visiting loops bottom-up is a post-order traversal of loop headers.
1221 /// For each loop, immediate members that represent sub-loops will already
1222 /// have been visited and packaged into a pseudo-node.
1224 /// Distributing mass in a loop is a reverse-post-order traversal through
1225 /// the loop. Start by assigning full mass to the Loop header. For each
1226 /// node in the loop:
1228 /// - Fetch and categorize the weight distribution for its successors.
1229 /// If this is a packaged-subloop, the weight distribution is stored
1230 /// in \a PackagedLoopData::Exits. Otherwise, fetch it from
1231 /// BranchProbabilityInfo.
1233 /// - Each successor is categorized as \a Weight::Local, a normal
1234 /// forward edge within the current loop, \a Weight::Backedge, a
1235 /// backedge to the loop header, or \a Weight::Exit, any successor
1236 /// outside the loop. The weight, the successor, and its category
1237 /// are stored in \a Distribution. There can be multiple edges to
1240 /// - Normalize the distribution: scale weights down so that their sum
1241 /// is 32-bits, and coalesce multiple edges to the same node.
1243 /// - Distribute the mass accordingly, dithering to minimize mass loss,
1244 /// as described in \a distributeMass(). Mass is distributed in
1245 /// parallel in two ways: forward, and general. Local successors
1246 /// take their mass from the forward mass, while exit and backedge
1247 /// successors take their mass from the general mass. Additionally,
1248 /// exit edges use up (ignored) mass from the forward mass, and local
1249 /// edges use up (ignored) mass from the general distribution.
1251 /// Finally, calculate the loop scale from the accumulated backedge mass.
1253 /// 3. Distribute mass in the function (\a computeMassInFunction()).
1255 /// Finally, distribute mass through the DAG resulting from packaging all
1256 /// loops in the function. This uses the same algorithm as distributing
1257 /// mass in a loop, except that there are no exit or backedge edges.
1259 /// 4. Loop unpackaging and cleanup (\a finalizeMetrics()).
1261 /// Initialize the frequency to a floating point representation of its
1264 /// Visit loops top-down (reverse post-order), scaling the loop header's
1265 /// frequency by its psuedo-node's mass and loop scale. Keep track of the
1266 /// minimum and maximum final frequencies.
1268 /// Using the min and max frequencies as a guide, translate floating point
1269 /// frequencies to an appropriate range in uint64_t.
1271 /// It has some known flaws.
1273 /// - Irreducible control flow isn't modelled correctly. In particular,
1274 /// LoopInfo and MachineLoopInfo ignore irreducible backedges. The main
1275 /// result is that irreducible SCCs will under-scaled. No mass is lost,
1276 /// but the computed branch weights for the loop pseudo-node will be
1279 /// Modelling irreducible control flow exactly involves setting up and
1280 /// solving a group of infinite geometric series. Such precision is
1281 /// unlikely to be worthwhile, since most of our algorithms give up on
1282 /// irreducible control flow anyway.
1284 /// Nevertheless, we might find that we need to get closer. If
1285 /// LoopInfo/MachineLoopInfo flags loops with irreducible control flow
1286 /// (and/or the function as a whole), we can find the SCCs, compute an
1287 /// approximate exit frequency for the SCC as a whole, and scale up
1290 /// - Loop scale is limited to 4096 per loop (2^12) to avoid exhausting
1291 /// BlockFrequency's 64-bit integer precision.
1292 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
1293 typedef typename bfi_detail::TypeMap<BT>::BlockT BlockT;
1294 typedef typename bfi_detail::TypeMap<BT>::FunctionT FunctionT;
1295 typedef typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT
1296 BranchProbabilityInfoT;
1297 typedef typename bfi_detail::TypeMap<BT>::LoopT LoopT;
1298 typedef typename bfi_detail::TypeMap<BT>::LoopInfoT LoopInfoT;
1300 typedef GraphTraits<const BlockT *> Successor;
1301 typedef GraphTraits<Inverse<const BlockT *>> Predecessor;
1303 const BranchProbabilityInfoT *BPI;
1304 const LoopInfoT *LI;
1307 // All blocks in reverse postorder.
1308 std::vector<const BlockT *> RPOT;
1309 DenseMap<const BlockT *, BlockNode> Nodes;
1311 typedef typename std::vector<const BlockT *>::const_iterator rpot_iterator;
1313 rpot_iterator rpot_begin() const { return RPOT.begin(); }
1314 rpot_iterator rpot_end() const { return RPOT.end(); }
1316 size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
1318 BlockNode getNode(const rpot_iterator &I) const {
1319 return BlockNode(getIndex(I));
1321 BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB); }
1323 const BlockT *getBlock(const BlockNode &Node) const {
1324 assert(Node.Index < RPOT.size());
1325 return RPOT[Node.Index];
1328 void initializeRPOT();
1329 void initializeLoops();
1330 void runOnFunction(const FunctionT *F);
1332 void propagateMassToSuccessors(const BlockNode &LoopHead,
1333 const BlockNode &Node);
1334 void computeMassInLoops();
1335 void computeMassInLoop(const BlockNode &LoopHead);
1336 void computeMassInFunction();
1338 std::string getBlockName(const BlockNode &Node) const override {
1339 return bfi_detail::getBlockName(getBlock(Node));
1343 const FunctionT *getFunction() const { return F; }
1345 void doFunction(const FunctionT *F, const BranchProbabilityInfoT *BPI,
1346 const LoopInfoT *LI);
1347 BlockFrequencyInfoImpl() : BPI(0), LI(0), F(0) {}
1349 using BlockFrequencyInfoImplBase::getEntryFreq;
1350 BlockFrequency getBlockFreq(const BlockT *BB) const {
1351 return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
1353 Float getFloatingBlockFreq(const BlockT *BB) const {
1354 return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
1357 /// \brief Print the frequencies for the current function.
1359 /// Prints the frequencies for the blocks in the current function.
1361 /// Blocks are printed in the natural iteration order of the function, rather
1362 /// than reverse post-order. This provides two advantages: writing -analyze
1363 /// tests is easier (since blocks come out in source order), and even
1364 /// unreachable blocks are printed.
1366 /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
1367 /// we need to override it here.
1368 raw_ostream &print(raw_ostream &OS) const override;
1369 using BlockFrequencyInfoImplBase::dump;
1371 using BlockFrequencyInfoImplBase::printBlockFreq;
1372 raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
1373 return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
1378 void BlockFrequencyInfoImpl<BT>::doFunction(const FunctionT *F,
1379 const BranchProbabilityInfoT *BPI,
1380 const LoopInfoT *LI) {
1381 // Save the parameters.
1386 // Clean up left-over data structures.
1387 BlockFrequencyInfoImplBase::clear();
1392 DEBUG(dbgs() << "\nblock-frequency: " << F->getName() << "\n================="
1393 << std::string(F->getName().size(), '=') << "\n");
1397 // Visit loops in post-order to find thelocal mass distribution, and then do
1398 // the full function.
1399 computeMassInLoops();
1400 computeMassInFunction();
1404 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1405 const BlockT *Entry = F->begin();
1406 RPOT.reserve(F->size());
1407 std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
1408 std::reverse(RPOT.begin(), RPOT.end());
1410 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1411 "More nodes in function than Block Frequency Info supports");
1413 DEBUG(dbgs() << "reverse-post-order-traversal\n");
1414 for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
1415 BlockNode Node = getNode(I);
1416 DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) << "\n");
1420 Working.resize(RPOT.size());
1421 Freqs.resize(RPOT.size());
1424 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1425 DEBUG(dbgs() << "loop-detection\n");
1429 // Visit loops top down and assign them an index.
1430 std::deque<const LoopT *> Q;
1431 Q.insert(Q.end(), LI->begin(), LI->end());
1432 while (!Q.empty()) {
1433 const LoopT *Loop = Q.front();
1435 Q.insert(Q.end(), Loop->begin(), Loop->end());
1437 // Save the order this loop was visited.
1438 BlockNode Header = getNode(Loop->getHeader());
1439 assert(Header.isValid());
1441 Working[Header.Index].LoopIndex = PackagedLoops.size();
1442 PackagedLoops.emplace_back(Header);
1443 DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1446 // Visit nodes in reverse post-order and add them to their deepest containing
1448 for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1449 const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1453 // If this is a loop header, find its parent loop (if any).
1454 if (Working[Index].isLoopHeader())
1455 if (!(Loop = Loop->getParentLoop()))
1458 // Add this node to its containing loop's member list.
1459 BlockNode Header = getNode(Loop->getHeader());
1460 assert(Header.isValid());
1461 const auto &HeaderData = Working[Header.Index];
1462 assert(HeaderData.isLoopHeader());
1464 Working[Index].ContainingLoop = Header;
1465 PackagedLoops[HeaderData.LoopIndex].Members.push_back(Index);
1466 DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1467 << ": member = " << getBlockName(Index) << "\n");
1471 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1472 // Visit loops with the deepest first, and the top-level loops last.
1473 for (auto L = PackagedLoops.rbegin(), LE = PackagedLoops.rend(); L != LE; ++L)
1474 computeMassInLoop(L->Header);
1478 void BlockFrequencyInfoImpl<BT>::computeMassInLoop(const BlockNode &LoopHead) {
1479 // Compute mass in loop.
1480 DEBUG(dbgs() << "compute-mass-in-loop: " << getBlockName(LoopHead) << "\n");
1482 Working[LoopHead.Index].Mass = BlockMass::getFull();
1483 propagateMassToSuccessors(LoopHead, LoopHead);
1485 for (const BlockNode &M : getLoopPackage(LoopHead).Members)
1486 propagateMassToSuccessors(LoopHead, M);
1488 computeLoopScale(LoopHead);
1489 packageLoop(LoopHead);
1492 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1493 // Compute mass in function.
1494 DEBUG(dbgs() << "compute-mass-in-function\n");
1495 assert(!Working.empty() && "no blocks in function");
1496 assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1498 Working[0].Mass = BlockMass::getFull();
1499 for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
1500 // Check for nodes that have been packaged.
1501 BlockNode Node = getNode(I);
1502 if (Working[Node.Index].hasLoopHeader())
1505 propagateMassToSuccessors(BlockNode(), Node);
1511 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(const BlockNode &LoopHead,
1512 const BlockNode &Node) {
1513 DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1514 // Calculate probability for successors.
1516 if (Node != LoopHead && Working[Node.Index].isLoopHeader())
1517 addLoopSuccessorsToDist(LoopHead, Node, Dist);
1519 const BlockT *BB = getBlock(Node);
1520 for (auto SI = Successor::child_begin(BB), SE = Successor::child_end(BB);
1522 // Do not dereference SI, or getEdgeWeight() is linear in the number of
1524 addToDist(Dist, LoopHead, Node, getNode(*SI), BPI->getEdgeWeight(BB, SI));
1527 // Distribute mass to successors, saving exit and backedge data in the
1529 distributeMass(Node, LoopHead, Dist);
1533 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
1536 OS << "block-frequency-info: " << F->getName() << "\n";
1537 for (const BlockT &BB : *F)
1538 OS << " - " << bfi_detail::getBlockName(&BB)
1539 << ": float = " << getFloatingBlockFreq(&BB)
1540 << ", int = " << getBlockFreq(&BB).getFrequency() << "\n";
1542 // Add an extra newline for readability.