Support: Write ScaledNumber::getQuotient() and getProduct()
[oota-llvm.git] / include / llvm / Analysis / BlockFrequencyInfoImpl.h
1 //==- BlockFrequencyInfoImpl.h - Block Frequency Implementation -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Shared implementation of BlockFrequency for IR and Machine Instructions.
11 // See the documentation below for BlockFrequencyInfoImpl for details.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
16 #define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
17
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"
27 #include <deque>
28 #include <list>
29 #include <string>
30 #include <vector>
31
32 #define DEBUG_TYPE "block-freq"
33
34 //===----------------------------------------------------------------------===//
35 //
36 // UnsignedFloat definition.
37 //
38 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
39 //
40 //===----------------------------------------------------------------------===//
41 namespace llvm {
42
43 class UnsignedFloatBase {
44 public:
45   static const int32_t MaxExponent = 16383;
46   static const int32_t MinExponent = -16382;
47   static const int DefaultPrecision = 10;
48
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,
51                             unsigned Precision);
52   static std::string toString(uint64_t D, int16_t E, int Width,
53                               unsigned Precision);
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); }
57
58   static std::pair<uint64_t, bool> splitSigned(int64_t N) {
59     if (N >= 0)
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);
63   }
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);
68   }
69
70   static int32_t extractLg(const std::pair<int32_t, int> &Lg) {
71     return Lg.first;
72   }
73   static int32_t extractLgFloor(const std::pair<int32_t, int> &Lg) {
74     return Lg.first - (Lg.second > 0);
75   }
76   static int32_t extractLgCeiling(const std::pair<int32_t, int> &Lg) {
77     return Lg.first + (Lg.second < 0);
78   }
79
80   static int compare(uint64_t L, uint64_t R, int Shift) {
81     assert(Shift >= 0);
82     assert(Shift < 64);
83
84     uint64_t L_adjusted = L >> Shift;
85     if (L_adjusted < R)
86       return -1;
87     if (L_adjusted > R)
88       return 1;
89
90     return L > L_adjusted << Shift ? 1 : 0;
91   }
92 };
93
94 /// \brief Simple representation of an unsigned floating point.
95 ///
96 /// UnsignedFloat is a unsigned floating point number.  It uses simple
97 /// saturation arithmetic, and every operation is well-defined for every value.
98 ///
99 /// The number is split into a signed exponent and unsigned digits.  The number
100 /// represented is \c getDigits()*2^getExponent().  In this way, the digits are
101 /// much like the mantissa in the x87 long double, but there is no canonical
102 /// form, so the same number can be represented by many bit representations
103 /// (it's always in "denormal" mode).
104 ///
105 /// UnsignedFloat is templated on the underlying integer type for digits, which
106 /// is expected to be one of uint64_t, uint32_t, uint16_t or uint8_t.
107 ///
108 /// Unlike builtin floating point types, UnsignedFloat is portable.
109 ///
110 /// Unlike APFloat, UnsignedFloat does not model architecture floating point
111 /// behaviour (this should make it a little faster), and implements most
112 /// operators (this makes it usable).
113 ///
114 /// UnsignedFloat is totally ordered.  However, there is no canonical form, so
115 /// there are multiple representations of most scalars.  E.g.:
116 ///
117 ///     UnsignedFloat(8u, 0) == UnsignedFloat(4u, 1)
118 ///     UnsignedFloat(4u, 1) == UnsignedFloat(2u, 2)
119 ///     UnsignedFloat(2u, 2) == UnsignedFloat(1u, 3)
120 ///
121 /// UnsignedFloat implements most arithmetic operations.  Precision is kept
122 /// where possible.  Uses simple saturation arithmetic, so that operations
123 /// saturate to 0.0 or getLargest() rather than under or overflowing.  It has
124 /// some extra arithmetic for unit inversion.  0.0/0.0 is defined to be 0.0.
125 /// Any other division by 0.0 is defined to be getLargest().
126 ///
127 /// As a convenience for modifying the exponent, left and right shifting are
128 /// both implemented, and both interpret negative shifts as positive shifts in
129 /// the opposite direction.
130 ///
131 /// Exponents are limited to the range accepted by x87 long double.  This makes
132 /// it trivial to add functionality to convert to APFloat (this is already
133 /// relied on for the implementation of printing).
134 ///
135 /// The current plan is to gut this and make the necessary parts of it (even
136 /// more) private to BlockFrequencyInfo.
137 template <class DigitsT> class UnsignedFloat : UnsignedFloatBase {
138 public:
139   static_assert(!std::numeric_limits<DigitsT>::is_signed,
140                 "only unsigned floats supported");
141
142   typedef DigitsT DigitsType;
143
144 private:
145   typedef std::numeric_limits<DigitsType> DigitsLimits;
146
147   static const int Width = sizeof(DigitsType) * 8;
148   static_assert(Width <= 64, "invalid integer width for digits");
149
150 private:
151   DigitsType Digits;
152   int16_t Exponent;
153
154 public:
155   UnsignedFloat() : Digits(0), Exponent(0) {}
156
157   UnsignedFloat(DigitsType Digits, int16_t Exponent)
158       : Digits(Digits), Exponent(Exponent) {}
159
160 private:
161   UnsignedFloat(const std::pair<uint64_t, int16_t> &X)
162       : Digits(X.first), Exponent(X.second) {}
163
164 public:
165   static UnsignedFloat getZero() { return UnsignedFloat(0, 0); }
166   static UnsignedFloat getOne() { return UnsignedFloat(1, 0); }
167   static UnsignedFloat getLargest() {
168     return UnsignedFloat(DigitsLimits::max(), MaxExponent);
169   }
170   static UnsignedFloat getFloat(uint64_t N) { return adjustToWidth(N, 0); }
171   static UnsignedFloat getInverseFloat(uint64_t N) {
172     return getFloat(N).invert();
173   }
174   static UnsignedFloat getFraction(DigitsType N, DigitsType D) {
175     return getQuotient(N, D);
176   }
177
178   int16_t getExponent() const { return Exponent; }
179   DigitsType getDigits() const { return Digits; }
180
181   /// \brief Convert to the given integer type.
182   ///
183   /// Convert to \c IntT using simple saturating arithmetic, truncating if
184   /// necessary.
185   template <class IntT> IntT toInt() const;
186
187   bool isZero() const { return !Digits; }
188   bool isLargest() const { return *this == getLargest(); }
189   bool isOne() const {
190     if (Exponent > 0 || Exponent <= -Width)
191       return false;
192     return Digits == DigitsType(1) << -Exponent;
193   }
194
195   /// \brief The log base 2, rounded.
196   ///
197   /// Get the lg of the scalar.  lg 0 is defined to be INT32_MIN.
198   int32_t lg() const { return extractLg(lgImpl()); }
199
200   /// \brief The log base 2, rounded towards INT32_MIN.
201   ///
202   /// Get the lg floor.  lg 0 is defined to be INT32_MIN.
203   int32_t lgFloor() const { return extractLgFloor(lgImpl()); }
204
205   /// \brief The log base 2, rounded towards INT32_MAX.
206   ///
207   /// Get the lg ceiling.  lg 0 is defined to be INT32_MIN.
208   int32_t lgCeiling() const { return extractLgCeiling(lgImpl()); }
209
210   bool operator==(const UnsignedFloat &X) const { return compare(X) == 0; }
211   bool operator<(const UnsignedFloat &X) const { return compare(X) < 0; }
212   bool operator!=(const UnsignedFloat &X) const { return compare(X) != 0; }
213   bool operator>(const UnsignedFloat &X) const { return compare(X) > 0; }
214   bool operator<=(const UnsignedFloat &X) const { return compare(X) <= 0; }
215   bool operator>=(const UnsignedFloat &X) const { return compare(X) >= 0; }
216
217   bool operator!() const { return isZero(); }
218
219   /// \brief Convert to a decimal representation in a string.
220   ///
221   /// Convert to a string.  Uses scientific notation for very large/small
222   /// numbers.  Scientific notation is used roughly for numbers outside of the
223   /// range 2^-64 through 2^64.
224   ///
225   /// \c Precision indicates the number of decimal digits of precision to use;
226   /// 0 requests the maximum available.
227   ///
228   /// As a special case to make debugging easier, if the number is small enough
229   /// to convert without scientific notation and has more than \c Precision
230   /// digits before the decimal place, it's printed accurately to the first
231   /// digit past zero.  E.g., assuming 10 digits of precision:
232   ///
233   ///     98765432198.7654... => 98765432198.8
234   ///      8765432198.7654... =>  8765432198.8
235   ///       765432198.7654... =>   765432198.8
236   ///        65432198.7654... =>    65432198.77
237   ///         5432198.7654... =>     5432198.765
238   std::string toString(unsigned Precision = DefaultPrecision) {
239     return UnsignedFloatBase::toString(Digits, Exponent, Width, Precision);
240   }
241
242   /// \brief Print a decimal representation.
243   ///
244   /// Print a string.  See toString for documentation.
245   raw_ostream &print(raw_ostream &OS,
246                      unsigned Precision = DefaultPrecision) const {
247     return UnsignedFloatBase::print(OS, Digits, Exponent, Width, Precision);
248   }
249   void dump() const { return UnsignedFloatBase::dump(Digits, Exponent, Width); }
250
251   UnsignedFloat &operator+=(const UnsignedFloat &X);
252   UnsignedFloat &operator-=(const UnsignedFloat &X);
253   UnsignedFloat &operator*=(const UnsignedFloat &X);
254   UnsignedFloat &operator/=(const UnsignedFloat &X);
255   UnsignedFloat &operator<<=(int16_t Shift) { shiftLeft(Shift); return *this; }
256   UnsignedFloat &operator>>=(int16_t Shift) { shiftRight(Shift); return *this; }
257
258 private:
259   void shiftLeft(int32_t Shift);
260   void shiftRight(int32_t Shift);
261
262   /// \brief Adjust two floats to have matching exponents.
263   ///
264   /// Adjust \c this and \c X to have matching exponents.  Returns the new \c X
265   /// by value.  Does nothing if \a isZero() for either.
266   ///
267   /// The value that compares smaller will lose precision, and possibly become
268   /// \a isZero().
269   UnsignedFloat matchExponents(UnsignedFloat X);
270
271   /// \brief Increase exponent to match another float.
272   ///
273   /// Increases \c this to have an exponent matching \c X.  May decrease the
274   /// exponent of \c X in the process, and \c this may possibly become \a
275   /// isZero().
276   void increaseExponentToMatch(UnsignedFloat &X, int32_t ExponentDiff);
277
278 public:
279   /// \brief Scale a large number accurately.
280   ///
281   /// Scale N (multiply it by this).  Uses full precision multiplication, even
282   /// if Width is smaller than 64, so information is not lost.
283   uint64_t scale(uint64_t N) const;
284   uint64_t scaleByInverse(uint64_t N) const {
285     // TODO: implement directly, rather than relying on inverse.  Inverse is
286     // expensive.
287     return inverse().scale(N);
288   }
289   int64_t scale(int64_t N) const {
290     std::pair<uint64_t, bool> Unsigned = splitSigned(N);
291     return joinSigned(scale(Unsigned.first), Unsigned.second);
292   }
293   int64_t scaleByInverse(int64_t N) const {
294     std::pair<uint64_t, bool> Unsigned = splitSigned(N);
295     return joinSigned(scaleByInverse(Unsigned.first), Unsigned.second);
296   }
297
298   int compare(const UnsignedFloat &X) const;
299   int compareTo(uint64_t N) const {
300     UnsignedFloat Float = getFloat(N);
301     int Compare = compare(Float);
302     if (Width == 64 || Compare != 0)
303       return Compare;
304
305     // Check for precision loss.  We know *this == RoundTrip.
306     uint64_t RoundTrip = Float.template toInt<uint64_t>();
307     return N == RoundTrip ? 0 : RoundTrip < N ? -1 : 1;
308   }
309   int compareTo(int64_t N) const { return N < 0 ? 1 : compareTo(uint64_t(N)); }
310
311   UnsignedFloat &invert() { return *this = UnsignedFloat::getFloat(1) / *this; }
312   UnsignedFloat inverse() const { return UnsignedFloat(*this).invert(); }
313
314 private:
315   static UnsignedFloat getProduct(DigitsType LHS, DigitsType RHS) {
316     return ScaledNumbers::getProduct(LHS, RHS);
317   }
318   static UnsignedFloat getQuotient(DigitsType Dividend, DigitsType Divisor) {
319     return ScaledNumbers::getQuotient(Dividend, Divisor);
320   }
321
322   std::pair<int32_t, int> lgImpl() const;
323   static int countLeadingZerosWidth(DigitsType Digits) {
324     if (Width == 64)
325       return countLeadingZeros64(Digits);
326     if (Width == 32)
327       return countLeadingZeros32(Digits);
328     return countLeadingZeros32(Digits) + Width - 32;
329   }
330
331   /// \brief Adjust a number to width, rounding up if necessary.
332   ///
333   /// Should only be called for \c Shift close to zero.
334   ///
335   /// \pre Shift >= MinExponent && Shift + 64 <= MaxExponent.
336   static UnsignedFloat adjustToWidth(uint64_t N, int32_t Shift) {
337     assert(Shift >= MinExponent && "Shift should be close to 0");
338     assert(Shift <= MaxExponent - 64 && "Shift should be close to 0");
339     auto Adjusted = ScaledNumbers::getAdjusted<DigitsT>(N, Shift);
340     return Adjusted;
341   }
342
343   static UnsignedFloat getRounded(UnsignedFloat P, bool Round) {
344     // Saturate.
345     if (P.isLargest())
346       return P;
347
348     return ScaledNumbers::getRounded(P.Digits, P.Exponent, Round);
349   }
350 };
351
352 #define UNSIGNED_FLOAT_BOP(op, base)                                           \
353   template <class DigitsT>                                                     \
354   UnsignedFloat<DigitsT> operator op(const UnsignedFloat<DigitsT> &L,          \
355                                      const UnsignedFloat<DigitsT> &R) {        \
356     return UnsignedFloat<DigitsT>(L) base R;                                   \
357   }
358 UNSIGNED_FLOAT_BOP(+, += )
359 UNSIGNED_FLOAT_BOP(-, -= )
360 UNSIGNED_FLOAT_BOP(*, *= )
361 UNSIGNED_FLOAT_BOP(/, /= )
362 UNSIGNED_FLOAT_BOP(<<, <<= )
363 UNSIGNED_FLOAT_BOP(>>, >>= )
364 #undef UNSIGNED_FLOAT_BOP
365
366 template <class DigitsT>
367 raw_ostream &operator<<(raw_ostream &OS, const UnsignedFloat<DigitsT> &X) {
368   return X.print(OS, 10);
369 }
370
371 #define UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, T1, T2)                             \
372   template <class DigitsT>                                                     \
373   bool operator op(const UnsignedFloat<DigitsT> &L, T1 R) {                    \
374     return L.compareTo(T2(R)) op 0;                                            \
375   }                                                                            \
376   template <class DigitsT>                                                     \
377   bool operator op(T1 L, const UnsignedFloat<DigitsT> &R) {                    \
378     return 0 op R.compareTo(T2(L));                                            \
379   }
380 #define UNSIGNED_FLOAT_COMPARE_TO(op)                                          \
381   UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, uint64_t, uint64_t)                       \
382   UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, uint32_t, uint64_t)                       \
383   UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, int64_t, int64_t)                         \
384   UNSIGNED_FLOAT_COMPARE_TO_TYPE(op, int32_t, int64_t)
385 UNSIGNED_FLOAT_COMPARE_TO(< )
386 UNSIGNED_FLOAT_COMPARE_TO(> )
387 UNSIGNED_FLOAT_COMPARE_TO(== )
388 UNSIGNED_FLOAT_COMPARE_TO(!= )
389 UNSIGNED_FLOAT_COMPARE_TO(<= )
390 UNSIGNED_FLOAT_COMPARE_TO(>= )
391 #undef UNSIGNED_FLOAT_COMPARE_TO
392 #undef UNSIGNED_FLOAT_COMPARE_TO_TYPE
393
394 template <class DigitsT>
395 uint64_t UnsignedFloat<DigitsT>::scale(uint64_t N) const {
396   if (Width == 64 || N <= DigitsLimits::max())
397     return (getFloat(N) * *this).template toInt<uint64_t>();
398
399   // Defer to the 64-bit version.
400   return UnsignedFloat<uint64_t>(Digits, Exponent).scale(N);
401 }
402
403 template <class DigitsT>
404 template <class IntT>
405 IntT UnsignedFloat<DigitsT>::toInt() const {
406   typedef std::numeric_limits<IntT> Limits;
407   if (*this < 1)
408     return 0;
409   if (*this >= Limits::max())
410     return Limits::max();
411
412   IntT N = Digits;
413   if (Exponent > 0) {
414     assert(size_t(Exponent) < sizeof(IntT) * 8);
415     return N << Exponent;
416   }
417   if (Exponent < 0) {
418     assert(size_t(-Exponent) < sizeof(IntT) * 8);
419     return N >> -Exponent;
420   }
421   return N;
422 }
423
424 template <class DigitsT>
425 std::pair<int32_t, int> UnsignedFloat<DigitsT>::lgImpl() const {
426   if (isZero())
427     return std::make_pair(INT32_MIN, 0);
428
429   // Get the floor of the lg of Digits.
430   int32_t LocalFloor = Width - countLeadingZerosWidth(Digits) - 1;
431
432   // Get the floor of the lg of this.
433   int32_t Floor = Exponent + LocalFloor;
434   if (Digits == UINT64_C(1) << LocalFloor)
435     return std::make_pair(Floor, 0);
436
437   // Round based on the next digit.
438   assert(LocalFloor >= 1);
439   bool Round = Digits & UINT64_C(1) << (LocalFloor - 1);
440   return std::make_pair(Floor + Round, Round ? 1 : -1);
441 }
442
443 template <class DigitsT>
444 UnsignedFloat<DigitsT> UnsignedFloat<DigitsT>::matchExponents(UnsignedFloat X) {
445   if (isZero() || X.isZero() || Exponent == X.Exponent)
446     return X;
447
448   int32_t Diff = int32_t(X.Exponent) - int32_t(Exponent);
449   if (Diff > 0)
450     increaseExponentToMatch(X, Diff);
451   else
452     X.increaseExponentToMatch(*this, -Diff);
453   return X;
454 }
455 template <class DigitsT>
456 void UnsignedFloat<DigitsT>::increaseExponentToMatch(UnsignedFloat &X,
457                                                      int32_t ExponentDiff) {
458   assert(ExponentDiff > 0);
459   if (ExponentDiff >= 2 * Width) {
460     *this = getZero();
461     return;
462   }
463
464   // Use up any leading zeros on X, and then shift this.
465   int32_t ShiftX = std::min(countLeadingZerosWidth(X.Digits), ExponentDiff);
466   assert(ShiftX < Width);
467
468   int32_t ShiftThis = ExponentDiff - ShiftX;
469   if (ShiftThis >= Width) {
470     *this = getZero();
471     return;
472   }
473
474   X.Digits <<= ShiftX;
475   X.Exponent -= ShiftX;
476   Digits >>= ShiftThis;
477   Exponent += ShiftThis;
478   return;
479 }
480
481 template <class DigitsT>
482 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
483 operator+=(const UnsignedFloat &X) {
484   if (isLargest() || X.isZero())
485     return *this;
486   if (isZero() || X.isLargest())
487     return *this = X;
488
489   // Normalize exponents.
490   UnsignedFloat Scaled = matchExponents(X);
491
492   // Check for zero again.
493   if (isZero())
494     return *this = Scaled;
495   if (Scaled.isZero())
496     return *this;
497
498   // Compute sum.
499   DigitsType Sum = Digits + Scaled.Digits;
500   bool DidOverflow = Sum < Digits;
501   Digits = Sum;
502   if (!DidOverflow)
503     return *this;
504
505   if (Exponent == MaxExponent)
506     return *this = getLargest();
507
508   ++Exponent;
509   Digits = UINT64_C(1) << (Width - 1) | Digits >> 1;
510
511   return *this;
512 }
513 template <class DigitsT>
514 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
515 operator-=(const UnsignedFloat &X) {
516   if (X.isZero())
517     return *this;
518   if (*this <= X)
519     return *this = getZero();
520
521   // Normalize exponents.
522   UnsignedFloat Scaled = matchExponents(X);
523   assert(Digits >= Scaled.Digits);
524
525   // Compute difference.
526   if (!Scaled.isZero()) {
527     Digits -= Scaled.Digits;
528     return *this;
529   }
530
531   // Check if X just barely lost its last bit.  E.g., for 32-bit:
532   //
533   //   1*2^32 - 1*2^0 == 0xffffffff != 1*2^32
534   if (*this == UnsignedFloat(1, X.lgFloor() + Width)) {
535     Digits = DigitsType(0) - 1;
536     --Exponent;
537   }
538   return *this;
539 }
540 template <class DigitsT>
541 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
542 operator*=(const UnsignedFloat &X) {
543   if (isZero())
544     return *this;
545   if (X.isZero())
546     return *this = X;
547
548   // Save the exponents.
549   int32_t Exponents = int32_t(Exponent) + int32_t(X.Exponent);
550
551   // Get the raw product.
552   *this = getProduct(Digits, X.Digits);
553
554   // Combine with exponents.
555   return *this <<= Exponents;
556 }
557 template <class DigitsT>
558 UnsignedFloat<DigitsT> &UnsignedFloat<DigitsT>::
559 operator/=(const UnsignedFloat &X) {
560   if (isZero())
561     return *this;
562   if (X.isZero())
563     return *this = getLargest();
564
565   // Save the exponents.
566   int32_t Exponents = int32_t(Exponent) - int32_t(X.Exponent);
567
568   // Get the raw quotient.
569   *this = getQuotient(Digits, X.Digits);
570
571   // Combine with exponents.
572   return *this <<= Exponents;
573 }
574 template <class DigitsT>
575 void UnsignedFloat<DigitsT>::shiftLeft(int32_t Shift) {
576   if (!Shift || isZero())
577     return;
578   assert(Shift != INT32_MIN);
579   if (Shift < 0) {
580     shiftRight(-Shift);
581     return;
582   }
583
584   // Shift as much as we can in the exponent.
585   int32_t ExponentShift = std::min(Shift, MaxExponent - Exponent);
586   Exponent += ExponentShift;
587   if (ExponentShift == Shift)
588     return;
589
590   // Check this late, since it's rare.
591   if (isLargest())
592     return;
593
594   // Shift the digits themselves.
595   Shift -= ExponentShift;
596   if (Shift > countLeadingZerosWidth(Digits)) {
597     // Saturate.
598     *this = getLargest();
599     return;
600   }
601
602   Digits <<= Shift;
603   return;
604 }
605
606 template <class DigitsT>
607 void UnsignedFloat<DigitsT>::shiftRight(int32_t Shift) {
608   if (!Shift || isZero())
609     return;
610   assert(Shift != INT32_MIN);
611   if (Shift < 0) {
612     shiftLeft(-Shift);
613     return;
614   }
615
616   // Shift as much as we can in the exponent.
617   int32_t ExponentShift = std::min(Shift, Exponent - MinExponent);
618   Exponent -= ExponentShift;
619   if (ExponentShift == Shift)
620     return;
621
622   // Shift the digits themselves.
623   Shift -= ExponentShift;
624   if (Shift >= Width) {
625     // Saturate.
626     *this = getZero();
627     return;
628   }
629
630   Digits >>= Shift;
631   return;
632 }
633
634 template <class DigitsT>
635 int UnsignedFloat<DigitsT>::compare(const UnsignedFloat &X) const {
636   // Check for zero.
637   if (isZero())
638     return X.isZero() ? 0 : -1;
639   if (X.isZero())
640     return 1;
641
642   // Check for the scale.  Use lgFloor to be sure that the exponent difference
643   // is always lower than 64.
644   int32_t lgL = lgFloor(), lgR = X.lgFloor();
645   if (lgL != lgR)
646     return lgL < lgR ? -1 : 1;
647
648   // Compare digits.
649   if (Exponent < X.Exponent)
650     return UnsignedFloatBase::compare(Digits, X.Digits, X.Exponent - Exponent);
651
652   return -UnsignedFloatBase::compare(X.Digits, Digits, Exponent - X.Exponent);
653 }
654
655 template <class T> struct isPodLike<UnsignedFloat<T>> {
656   static const bool value = true;
657 };
658 }
659
660 //===----------------------------------------------------------------------===//
661 //
662 // BlockMass definition.
663 //
664 // TODO: Make this private to BlockFrequencyInfoImpl or delete.
665 //
666 //===----------------------------------------------------------------------===//
667 namespace llvm {
668
669 /// \brief Mass of a block.
670 ///
671 /// This class implements a sort of fixed-point fraction always between 0.0 and
672 /// 1.0.  getMass() == UINT64_MAX indicates a value of 1.0.
673 ///
674 /// Masses can be added and subtracted.  Simple saturation arithmetic is used,
675 /// so arithmetic operations never overflow or underflow.
676 ///
677 /// Masses can be multiplied.  Multiplication treats full mass as 1.0 and uses
678 /// an inexpensive floating-point algorithm that's off-by-one (almost, but not
679 /// quite, maximum precision).
680 ///
681 /// Masses can be scaled by \a BranchProbability at maximum precision.
682 class BlockMass {
683   uint64_t Mass;
684
685 public:
686   BlockMass() : Mass(0) {}
687   explicit BlockMass(uint64_t Mass) : Mass(Mass) {}
688
689   static BlockMass getEmpty() { return BlockMass(); }
690   static BlockMass getFull() { return BlockMass(UINT64_MAX); }
691
692   uint64_t getMass() const { return Mass; }
693
694   bool isFull() const { return Mass == UINT64_MAX; }
695   bool isEmpty() const { return !Mass; }
696
697   bool operator!() const { return isEmpty(); }
698
699   /// \brief Add another mass.
700   ///
701   /// Adds another mass, saturating at \a isFull() rather than overflowing.
702   BlockMass &operator+=(const BlockMass &X) {
703     uint64_t Sum = Mass + X.Mass;
704     Mass = Sum < Mass ? UINT64_MAX : Sum;
705     return *this;
706   }
707
708   /// \brief Subtract another mass.
709   ///
710   /// Subtracts another mass, saturating at \a isEmpty() rather than
711   /// undeflowing.
712   BlockMass &operator-=(const BlockMass &X) {
713     uint64_t Diff = Mass - X.Mass;
714     Mass = Diff > Mass ? 0 : Diff;
715     return *this;
716   }
717
718   BlockMass &operator*=(const BranchProbability &P) {
719     Mass = P.scale(Mass);
720     return *this;
721   }
722
723   bool operator==(const BlockMass &X) const { return Mass == X.Mass; }
724   bool operator!=(const BlockMass &X) const { return Mass != X.Mass; }
725   bool operator<=(const BlockMass &X) const { return Mass <= X.Mass; }
726   bool operator>=(const BlockMass &X) const { return Mass >= X.Mass; }
727   bool operator<(const BlockMass &X) const { return Mass < X.Mass; }
728   bool operator>(const BlockMass &X) const { return Mass > X.Mass; }
729
730   /// \brief Convert to floating point.
731   ///
732   /// Convert to a float.  \a isFull() gives 1.0, while \a isEmpty() gives
733   /// slightly above 0.0.
734   UnsignedFloat<uint64_t> toFloat() const;
735
736   void dump() const;
737   raw_ostream &print(raw_ostream &OS) const;
738 };
739
740 inline BlockMass operator+(const BlockMass &L, const BlockMass &R) {
741   return BlockMass(L) += R;
742 }
743 inline BlockMass operator-(const BlockMass &L, const BlockMass &R) {
744   return BlockMass(L) -= R;
745 }
746 inline BlockMass operator*(const BlockMass &L, const BranchProbability &R) {
747   return BlockMass(L) *= R;
748 }
749 inline BlockMass operator*(const BranchProbability &L, const BlockMass &R) {
750   return BlockMass(R) *= L;
751 }
752
753 inline raw_ostream &operator<<(raw_ostream &OS, const BlockMass &X) {
754   return X.print(OS);
755 }
756
757 template <> struct isPodLike<BlockMass> {
758   static const bool value = true;
759 };
760 }
761
762 //===----------------------------------------------------------------------===//
763 //
764 // BlockFrequencyInfoImpl definition.
765 //
766 //===----------------------------------------------------------------------===//
767 namespace llvm {
768
769 class BasicBlock;
770 class BranchProbabilityInfo;
771 class Function;
772 class Loop;
773 class LoopInfo;
774 class MachineBasicBlock;
775 class MachineBranchProbabilityInfo;
776 class MachineFunction;
777 class MachineLoop;
778 class MachineLoopInfo;
779
780 namespace bfi_detail {
781 struct IrreducibleGraph;
782
783 // This is part of a workaround for a GCC 4.7 crash on lambdas.
784 template <class BT> struct BlockEdgesAdder;
785 }
786
787 /// \brief Base class for BlockFrequencyInfoImpl
788 ///
789 /// BlockFrequencyInfoImplBase has supporting data structures and some
790 /// algorithms for BlockFrequencyInfoImplBase.  Only algorithms that depend on
791 /// the block type (or that call such algorithms) are skipped here.
792 ///
793 /// Nevertheless, the majority of the overall algorithm documention lives with
794 /// BlockFrequencyInfoImpl.  See there for details.
795 class BlockFrequencyInfoImplBase {
796 public:
797   typedef UnsignedFloat<uint64_t> Float;
798
799   /// \brief Representative of a block.
800   ///
801   /// This is a simple wrapper around an index into the reverse-post-order
802   /// traversal of the blocks.
803   ///
804   /// Unlike a block pointer, its order has meaning (location in the
805   /// topological sort) and it's class is the same regardless of block type.
806   struct BlockNode {
807     typedef uint32_t IndexType;
808     IndexType Index;
809
810     bool operator==(const BlockNode &X) const { return Index == X.Index; }
811     bool operator!=(const BlockNode &X) const { return Index != X.Index; }
812     bool operator<=(const BlockNode &X) const { return Index <= X.Index; }
813     bool operator>=(const BlockNode &X) const { return Index >= X.Index; }
814     bool operator<(const BlockNode &X) const { return Index < X.Index; }
815     bool operator>(const BlockNode &X) const { return Index > X.Index; }
816
817     BlockNode() : Index(UINT32_MAX) {}
818     BlockNode(IndexType Index) : Index(Index) {}
819
820     bool isValid() const { return Index <= getMaxIndex(); }
821     static size_t getMaxIndex() { return UINT32_MAX - 1; }
822   };
823
824   /// \brief Stats about a block itself.
825   struct FrequencyData {
826     Float Floating;
827     uint64_t Integer;
828   };
829
830   /// \brief Data about a loop.
831   ///
832   /// Contains the data necessary to represent represent a loop as a
833   /// pseudo-node once it's packaged.
834   struct LoopData {
835     typedef SmallVector<std::pair<BlockNode, BlockMass>, 4> ExitMap;
836     typedef SmallVector<BlockNode, 4> NodeList;
837     LoopData *Parent;       ///< The parent loop.
838     bool IsPackaged;        ///< Whether this has been packaged.
839     uint32_t NumHeaders;    ///< Number of headers.
840     ExitMap Exits;          ///< Successor edges (and weights).
841     NodeList Nodes;         ///< Header and the members of the loop.
842     BlockMass BackedgeMass; ///< Mass returned to loop header.
843     BlockMass Mass;
844     Float Scale;
845
846     LoopData(LoopData *Parent, const BlockNode &Header)
847         : Parent(Parent), IsPackaged(false), NumHeaders(1), Nodes(1, Header) {}
848     template <class It1, class It2>
849     LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther,
850              It2 LastOther)
851         : Parent(Parent), IsPackaged(false), Nodes(FirstHeader, LastHeader) {
852       NumHeaders = Nodes.size();
853       Nodes.insert(Nodes.end(), FirstOther, LastOther);
854     }
855     bool isHeader(const BlockNode &Node) const {
856       if (isIrreducible())
857         return std::binary_search(Nodes.begin(), Nodes.begin() + NumHeaders,
858                                   Node);
859       return Node == Nodes[0];
860     }
861     BlockNode getHeader() const { return Nodes[0]; }
862     bool isIrreducible() const { return NumHeaders > 1; }
863
864     NodeList::const_iterator members_begin() const {
865       return Nodes.begin() + NumHeaders;
866     }
867     NodeList::const_iterator members_end() const { return Nodes.end(); }
868     iterator_range<NodeList::const_iterator> members() const {
869       return make_range(members_begin(), members_end());
870     }
871   };
872
873   /// \brief Index of loop information.
874   struct WorkingData {
875     BlockNode Node; ///< This node.
876     LoopData *Loop; ///< The loop this block is inside.
877     BlockMass Mass; ///< Mass distribution from the entry block.
878
879     WorkingData(const BlockNode &Node) : Node(Node), Loop(nullptr) {}
880
881     bool isLoopHeader() const { return Loop && Loop->isHeader(Node); }
882     bool isDoubleLoopHeader() const {
883       return isLoopHeader() && Loop->Parent && Loop->Parent->isIrreducible() &&
884              Loop->Parent->isHeader(Node);
885     }
886
887     LoopData *getContainingLoop() const {
888       if (!isLoopHeader())
889         return Loop;
890       if (!isDoubleLoopHeader())
891         return Loop->Parent;
892       return Loop->Parent->Parent;
893     }
894
895     /// \brief Resolve a node to its representative.
896     ///
897     /// Get the node currently representing Node, which could be a containing
898     /// loop.
899     ///
900     /// This function should only be called when distributing mass.  As long as
901     /// there are no irreducilbe edges to Node, then it will have complexity
902     /// O(1) in this context.
903     ///
904     /// In general, the complexity is O(L), where L is the number of loop
905     /// headers Node has been packaged into.  Since this method is called in
906     /// the context of distributing mass, L will be the number of loop headers
907     /// an early exit edge jumps out of.
908     BlockNode getResolvedNode() const {
909       auto L = getPackagedLoop();
910       return L ? L->getHeader() : Node;
911     }
912     LoopData *getPackagedLoop() const {
913       if (!Loop || !Loop->IsPackaged)
914         return nullptr;
915       auto L = Loop;
916       while (L->Parent && L->Parent->IsPackaged)
917         L = L->Parent;
918       return L;
919     }
920
921     /// \brief Get the appropriate mass for a node.
922     ///
923     /// Get appropriate mass for Node.  If Node is a loop-header (whose loop
924     /// has been packaged), returns the mass of its pseudo-node.  If it's a
925     /// node inside a packaged loop, it returns the loop's mass.
926     BlockMass &getMass() {
927       if (!isAPackage())
928         return Mass;
929       if (!isADoublePackage())
930         return Loop->Mass;
931       return Loop->Parent->Mass;
932     }
933
934     /// \brief Has ContainingLoop been packaged up?
935     bool isPackaged() const { return getResolvedNode() != Node; }
936     /// \brief Has Loop been packaged up?
937     bool isAPackage() const { return isLoopHeader() && Loop->IsPackaged; }
938     /// \brief Has Loop been packaged up twice?
939     bool isADoublePackage() const {
940       return isDoubleLoopHeader() && Loop->Parent->IsPackaged;
941     }
942   };
943
944   /// \brief Unscaled probability weight.
945   ///
946   /// Probability weight for an edge in the graph (including the
947   /// successor/target node).
948   ///
949   /// All edges in the original function are 32-bit.  However, exit edges from
950   /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
951   /// space in general.
952   ///
953   /// In addition to the raw weight amount, Weight stores the type of the edge
954   /// in the current context (i.e., the context of the loop being processed).
955   /// Is this a local edge within the loop, an exit from the loop, or a
956   /// backedge to the loop header?
957   struct Weight {
958     enum DistType { Local, Exit, Backedge };
959     DistType Type;
960     BlockNode TargetNode;
961     uint64_t Amount;
962     Weight() : Type(Local), Amount(0) {}
963   };
964
965   /// \brief Distribution of unscaled probability weight.
966   ///
967   /// Distribution of unscaled probability weight to a set of successors.
968   ///
969   /// This class collates the successor edge weights for later processing.
970   ///
971   /// \a DidOverflow indicates whether \a Total did overflow while adding to
972   /// the distribution.  It should never overflow twice.
973   struct Distribution {
974     typedef SmallVector<Weight, 4> WeightList;
975     WeightList Weights;    ///< Individual successor weights.
976     uint64_t Total;        ///< Sum of all weights.
977     bool DidOverflow;      ///< Whether \a Total did overflow.
978
979     Distribution() : Total(0), DidOverflow(false) {}
980     void addLocal(const BlockNode &Node, uint64_t Amount) {
981       add(Node, Amount, Weight::Local);
982     }
983     void addExit(const BlockNode &Node, uint64_t Amount) {
984       add(Node, Amount, Weight::Exit);
985     }
986     void addBackedge(const BlockNode &Node, uint64_t Amount) {
987       add(Node, Amount, Weight::Backedge);
988     }
989
990     /// \brief Normalize the distribution.
991     ///
992     /// Combines multiple edges to the same \a Weight::TargetNode and scales
993     /// down so that \a Total fits into 32-bits.
994     ///
995     /// This is linear in the size of \a Weights.  For the vast majority of
996     /// cases, adjacent edge weights are combined by sorting WeightList and
997     /// combining adjacent weights.  However, for very large edge lists an
998     /// auxiliary hash table is used.
999     void normalize();
1000
1001   private:
1002     void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
1003   };
1004
1005   /// \brief Data about each block.  This is used downstream.
1006   std::vector<FrequencyData> Freqs;
1007
1008   /// \brief Loop data: see initializeLoops().
1009   std::vector<WorkingData> Working;
1010
1011   /// \brief Indexed information about loops.
1012   std::list<LoopData> Loops;
1013
1014   /// \brief Add all edges out of a packaged loop to the distribution.
1015   ///
1016   /// Adds all edges from LocalLoopHead to Dist.  Calls addToDist() to add each
1017   /// successor edge.
1018   ///
1019   /// \return \c true unless there's an irreducible backedge.
1020   bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop,
1021                                Distribution &Dist);
1022
1023   /// \brief Add an edge to the distribution.
1024   ///
1025   /// Adds an edge to Succ to Dist.  If \c LoopHead.isValid(), then whether the
1026   /// edge is local/exit/backedge is in the context of LoopHead.  Otherwise,
1027   /// every edge should be a local edge (since all the loops are packaged up).
1028   ///
1029   /// \return \c true unless aborted due to an irreducible backedge.
1030   bool addToDist(Distribution &Dist, const LoopData *OuterLoop,
1031                  const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
1032
1033   LoopData &getLoopPackage(const BlockNode &Head) {
1034     assert(Head.Index < Working.size());
1035     assert(Working[Head.Index].isLoopHeader());
1036     return *Working[Head.Index].Loop;
1037   }
1038
1039   /// \brief Analyze irreducible SCCs.
1040   ///
1041   /// Separate irreducible SCCs from \c G, which is an explict graph of \c
1042   /// OuterLoop (or the top-level function, if \c OuterLoop is \c nullptr).
1043   /// Insert them into \a Loops before \c Insert.
1044   ///
1045   /// \return the \c LoopData nodes representing the irreducible SCCs.
1046   iterator_range<std::list<LoopData>::iterator>
1047   analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop,
1048                      std::list<LoopData>::iterator Insert);
1049
1050   /// \brief Update a loop after packaging irreducible SCCs inside of it.
1051   ///
1052   /// Update \c OuterLoop.  Before finding irreducible control flow, it was
1053   /// partway through \a computeMassInLoop(), so \a LoopData::Exits and \a
1054   /// LoopData::BackedgeMass need to be reset.  Also, nodes that were packaged
1055   /// up need to be removed from \a OuterLoop::Nodes.
1056   void updateLoopWithIrreducible(LoopData &OuterLoop);
1057
1058   /// \brief Distribute mass according to a distribution.
1059   ///
1060   /// Distributes the mass in Source according to Dist.  If LoopHead.isValid(),
1061   /// backedges and exits are stored in its entry in Loops.
1062   ///
1063   /// Mass is distributed in parallel from two copies of the source mass.
1064   void distributeMass(const BlockNode &Source, LoopData *OuterLoop,
1065                       Distribution &Dist);
1066
1067   /// \brief Compute the loop scale for a loop.
1068   void computeLoopScale(LoopData &Loop);
1069
1070   /// \brief Package up a loop.
1071   void packageLoop(LoopData &Loop);
1072
1073   /// \brief Unwrap loops.
1074   void unwrapLoops();
1075
1076   /// \brief Finalize frequency metrics.
1077   ///
1078   /// Calculates final frequencies and cleans up no-longer-needed data
1079   /// structures.
1080   void finalizeMetrics();
1081
1082   /// \brief Clear all memory.
1083   void clear();
1084
1085   virtual std::string getBlockName(const BlockNode &Node) const;
1086   std::string getLoopName(const LoopData &Loop) const;
1087
1088   virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
1089   void dump() const { print(dbgs()); }
1090
1091   Float getFloatingBlockFreq(const BlockNode &Node) const;
1092
1093   BlockFrequency getBlockFreq(const BlockNode &Node) const;
1094
1095   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
1096   raw_ostream &printBlockFreq(raw_ostream &OS,
1097                               const BlockFrequency &Freq) const;
1098
1099   uint64_t getEntryFreq() const {
1100     assert(!Freqs.empty());
1101     return Freqs[0].Integer;
1102   }
1103   /// \brief Virtual destructor.
1104   ///
1105   /// Need a virtual destructor to mask the compiler warning about
1106   /// getBlockName().
1107   virtual ~BlockFrequencyInfoImplBase() {}
1108 };
1109
1110 namespace bfi_detail {
1111 template <class BlockT> struct TypeMap {};
1112 template <> struct TypeMap<BasicBlock> {
1113   typedef BasicBlock BlockT;
1114   typedef Function FunctionT;
1115   typedef BranchProbabilityInfo BranchProbabilityInfoT;
1116   typedef Loop LoopT;
1117   typedef LoopInfo LoopInfoT;
1118 };
1119 template <> struct TypeMap<MachineBasicBlock> {
1120   typedef MachineBasicBlock BlockT;
1121   typedef MachineFunction FunctionT;
1122   typedef MachineBranchProbabilityInfo BranchProbabilityInfoT;
1123   typedef MachineLoop LoopT;
1124   typedef MachineLoopInfo LoopInfoT;
1125 };
1126
1127 /// \brief Get the name of a MachineBasicBlock.
1128 ///
1129 /// Get the name of a MachineBasicBlock.  It's templated so that including from
1130 /// CodeGen is unnecessary (that would be a layering issue).
1131 ///
1132 /// This is used mainly for debug output.  The name is similar to
1133 /// MachineBasicBlock::getFullName(), but skips the name of the function.
1134 template <class BlockT> std::string getBlockName(const BlockT *BB) {
1135   assert(BB && "Unexpected nullptr");
1136   auto MachineName = "BB" + Twine(BB->getNumber());
1137   if (BB->getBasicBlock())
1138     return (MachineName + "[" + BB->getName() + "]").str();
1139   return MachineName.str();
1140 }
1141 /// \brief Get the name of a BasicBlock.
1142 template <> inline std::string getBlockName(const BasicBlock *BB) {
1143   assert(BB && "Unexpected nullptr");
1144   return BB->getName().str();
1145 }
1146
1147 /// \brief Graph of irreducible control flow.
1148 ///
1149 /// This graph is used for determining the SCCs in a loop (or top-level
1150 /// function) that has irreducible control flow.
1151 ///
1152 /// During the block frequency algorithm, the local graphs are defined in a
1153 /// light-weight way, deferring to the \a BasicBlock or \a MachineBasicBlock
1154 /// graphs for most edges, but getting others from \a LoopData::ExitMap.  The
1155 /// latter only has successor information.
1156 ///
1157 /// \a IrreducibleGraph makes this graph explicit.  It's in a form that can use
1158 /// \a GraphTraits (so that \a analyzeIrreducible() can use \a scc_iterator),
1159 /// and it explicitly lists predecessors and successors.  The initialization
1160 /// that relies on \c MachineBasicBlock is defined in the header.
1161 struct IrreducibleGraph {
1162   typedef BlockFrequencyInfoImplBase BFIBase;
1163
1164   BFIBase &BFI;
1165
1166   typedef BFIBase::BlockNode BlockNode;
1167   struct IrrNode {
1168     BlockNode Node;
1169     unsigned NumIn;
1170     std::deque<const IrrNode *> Edges;
1171     IrrNode(const BlockNode &Node) : Node(Node), NumIn(0) {}
1172
1173     typedef std::deque<const IrrNode *>::const_iterator iterator;
1174     iterator pred_begin() const { return Edges.begin(); }
1175     iterator succ_begin() const { return Edges.begin() + NumIn; }
1176     iterator pred_end() const { return succ_begin(); }
1177     iterator succ_end() const { return Edges.end(); }
1178   };
1179   BlockNode Start;
1180   const IrrNode *StartIrr;
1181   std::vector<IrrNode> Nodes;
1182   SmallDenseMap<uint32_t, IrrNode *, 4> Lookup;
1183
1184   /// \brief Construct an explicit graph containing irreducible control flow.
1185   ///
1186   /// Construct an explicit graph of the control flow in \c OuterLoop (or the
1187   /// top-level function, if \c OuterLoop is \c nullptr).  Uses \c
1188   /// addBlockEdges to add block successors that have not been packaged into
1189   /// loops.
1190   ///
1191   /// \a BlockFrequencyInfoImpl::computeIrreducibleMass() is the only expected
1192   /// user of this.
1193   template <class BlockEdgesAdder>
1194   IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop,
1195                    BlockEdgesAdder addBlockEdges)
1196       : BFI(BFI), StartIrr(nullptr) {
1197     initialize(OuterLoop, addBlockEdges);
1198   }
1199
1200   template <class BlockEdgesAdder>
1201   void initialize(const BFIBase::LoopData *OuterLoop,
1202                   BlockEdgesAdder addBlockEdges);
1203   void addNodesInLoop(const BFIBase::LoopData &OuterLoop);
1204   void addNodesInFunction();
1205   void addNode(const BlockNode &Node) {
1206     Nodes.emplace_back(Node);
1207     BFI.Working[Node.Index].getMass() = BlockMass::getEmpty();
1208   }
1209   void indexNodes();
1210   template <class BlockEdgesAdder>
1211   void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop,
1212                 BlockEdgesAdder addBlockEdges);
1213   void addEdge(IrrNode &Irr, const BlockNode &Succ,
1214                const BFIBase::LoopData *OuterLoop);
1215 };
1216 template <class BlockEdgesAdder>
1217 void IrreducibleGraph::initialize(const BFIBase::LoopData *OuterLoop,
1218                                   BlockEdgesAdder addBlockEdges) {
1219   if (OuterLoop) {
1220     addNodesInLoop(*OuterLoop);
1221     for (auto N : OuterLoop->Nodes)
1222       addEdges(N, OuterLoop, addBlockEdges);
1223   } else {
1224     addNodesInFunction();
1225     for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
1226       addEdges(Index, OuterLoop, addBlockEdges);
1227   }
1228   StartIrr = Lookup[Start.Index];
1229 }
1230 template <class BlockEdgesAdder>
1231 void IrreducibleGraph::addEdges(const BlockNode &Node,
1232                                 const BFIBase::LoopData *OuterLoop,
1233                                 BlockEdgesAdder addBlockEdges) {
1234   auto L = Lookup.find(Node.Index);
1235   if (L == Lookup.end())
1236     return;
1237   IrrNode &Irr = *L->second;
1238   const auto &Working = BFI.Working[Node.Index];
1239
1240   if (Working.isAPackage())
1241     for (const auto &I : Working.Loop->Exits)
1242       addEdge(Irr, I.first, OuterLoop);
1243   else
1244     addBlockEdges(*this, Irr, OuterLoop);
1245 }
1246 }
1247
1248 /// \brief Shared implementation for block frequency analysis.
1249 ///
1250 /// This is a shared implementation of BlockFrequencyInfo and
1251 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
1252 /// blocks.
1253 ///
1254 /// LoopInfo defines a loop as a "non-trivial" SCC dominated by a single block,
1255 /// which is called the header.  A given loop, L, can have sub-loops, which are
1256 /// loops within the subgraph of L that exclude its header.  (A "trivial" SCC
1257 /// consists of a single block that does not have a self-edge.)
1258 ///
1259 /// In addition to loops, this algorithm has limited support for irreducible
1260 /// SCCs, which are SCCs with multiple entry blocks.  Irreducible SCCs are
1261 /// discovered on they fly, and modelled as loops with multiple headers.
1262 ///
1263 /// The headers of irreducible sub-SCCs consist of its entry blocks and all
1264 /// nodes that are targets of a backedge within it (excluding backedges within
1265 /// true sub-loops).  Block frequency calculations act as if a block is
1266 /// inserted that intercepts all the edges to the headers.  All backedges and
1267 /// entries point to this block.  Its successors are the headers, which split
1268 /// the frequency evenly.
1269 ///
1270 /// This algorithm leverages BlockMass and UnsignedFloat to maintain precision,
1271 /// separates mass distribution from loop scaling, and dithers to eliminate
1272 /// probability mass loss.
1273 ///
1274 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
1275 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
1276 /// BlockFrequencyInfoImplBase, which doesn't.  The base class uses \a
1277 /// BlockNode, a wrapper around a uint32_t.  BlockNode is numbered from 0 in
1278 /// reverse-post order.  This gives two advantages:  it's easy to compare the
1279 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
1280 /// by vectors.
1281 ///
1282 /// This algorithm is O(V+E), unless there is irreducible control flow, in
1283 /// which case it's O(V*E) in the worst case.
1284 ///
1285 /// These are the main stages:
1286 ///
1287 ///  0. Reverse post-order traversal (\a initializeRPOT()).
1288 ///
1289 ///     Run a single post-order traversal and save it (in reverse) in RPOT.
1290 ///     All other stages make use of this ordering.  Save a lookup from BlockT
1291 ///     to BlockNode (the index into RPOT) in Nodes.
1292 ///
1293 ///  1. Loop initialization (\a initializeLoops()).
1294 ///
1295 ///     Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
1296 ///     the algorithm.  In particular, store the immediate members of each loop
1297 ///     in reverse post-order.
1298 ///
1299 ///  2. Calculate mass and scale in loops (\a computeMassInLoops()).
1300 ///
1301 ///     For each loop (bottom-up), distribute mass through the DAG resulting
1302 ///     from ignoring backedges and treating sub-loops as a single pseudo-node.
1303 ///     Track the backedge mass distributed to the loop header, and use it to
1304 ///     calculate the loop scale (number of loop iterations).  Immediate
1305 ///     members that represent sub-loops will already have been visited and
1306 ///     packaged into a pseudo-node.
1307 ///
1308 ///     Distributing mass in a loop is a reverse-post-order traversal through
1309 ///     the loop.  Start by assigning full mass to the Loop header.  For each
1310 ///     node in the loop:
1311 ///
1312 ///         - Fetch and categorize the weight distribution for its successors.
1313 ///           If this is a packaged-subloop, the weight distribution is stored
1314 ///           in \a LoopData::Exits.  Otherwise, fetch it from
1315 ///           BranchProbabilityInfo.
1316 ///
1317 ///         - Each successor is categorized as \a Weight::Local, a local edge
1318 ///           within the current loop, \a Weight::Backedge, a backedge to the
1319 ///           loop header, or \a Weight::Exit, any successor outside the loop.
1320 ///           The weight, the successor, and its category are stored in \a
1321 ///           Distribution.  There can be multiple edges to each successor.
1322 ///
1323 ///         - If there's a backedge to a non-header, there's an irreducible SCC.
1324 ///           The usual flow is temporarily aborted.  \a
1325 ///           computeIrreducibleMass() finds the irreducible SCCs within the
1326 ///           loop, packages them up, and restarts the flow.
1327 ///
1328 ///         - Normalize the distribution:  scale weights down so that their sum
1329 ///           is 32-bits, and coalesce multiple edges to the same node.
1330 ///
1331 ///         - Distribute the mass accordingly, dithering to minimize mass loss,
1332 ///           as described in \a distributeMass().
1333 ///
1334 ///     Finally, calculate the loop scale from the accumulated backedge mass.
1335 ///
1336 ///  3. Distribute mass in the function (\a computeMassInFunction()).
1337 ///
1338 ///     Finally, distribute mass through the DAG resulting from packaging all
1339 ///     loops in the function.  This uses the same algorithm as distributing
1340 ///     mass in a loop, except that there are no exit or backedge edges.
1341 ///
1342 ///  4. Unpackage loops (\a unwrapLoops()).
1343 ///
1344 ///     Initialize each block's frequency to a floating point representation of
1345 ///     its mass.
1346 ///
1347 ///     Visit loops top-down, scaling the frequencies of its immediate members
1348 ///     by the loop's pseudo-node's frequency.
1349 ///
1350 ///  5. Convert frequencies to a 64-bit range (\a finalizeMetrics()).
1351 ///
1352 ///     Using the min and max frequencies as a guide, translate floating point
1353 ///     frequencies to an appropriate range in uint64_t.
1354 ///
1355 /// It has some known flaws.
1356 ///
1357 ///   - Loop scale is limited to 4096 per loop (2^12) to avoid exhausting
1358 ///     BlockFrequency's 64-bit integer precision.
1359 ///
1360 ///   - The model of irreducible control flow is a rough approximation.
1361 ///
1362 ///     Modelling irreducible control flow exactly involves setting up and
1363 ///     solving a group of infinite geometric series.  Such precision is
1364 ///     unlikely to be worthwhile, since most of our algorithms give up on
1365 ///     irreducible control flow anyway.
1366 ///
1367 ///     Nevertheless, we might find that we need to get closer.  Here's a sort
1368 ///     of TODO list for the model with diminishing returns, to be completed as
1369 ///     necessary.
1370 ///
1371 ///       - The headers for the \a LoopData representing an irreducible SCC
1372 ///         include non-entry blocks.  When these extra blocks exist, they
1373 ///         indicate a self-contained irreducible sub-SCC.  We could treat them
1374 ///         as sub-loops, rather than arbitrarily shoving the problematic
1375 ///         blocks into the headers of the main irreducible SCC.
1376 ///
1377 ///       - Backedge frequencies are assumed to be evenly split between the
1378 ///         headers of a given irreducible SCC.  Instead, we could track the
1379 ///         backedge mass separately for each header, and adjust their relative
1380 ///         frequencies.
1381 ///
1382 ///       - Entry frequencies are assumed to be evenly split between the
1383 ///         headers of a given irreducible SCC, which is the only option if we
1384 ///         need to compute mass in the SCC before its parent loop.  Instead,
1385 ///         we could partially compute mass in the parent loop, and stop when
1386 ///         we get to the SCC.  Here, we have the correct ratio of entry
1387 ///         masses, which we can use to adjust their relative frequencies.
1388 ///         Compute mass in the SCC, and then continue propagation in the
1389 ///         parent.
1390 ///
1391 ///       - We can propagate mass iteratively through the SCC, for some fixed
1392 ///         number of iterations.  Each iteration starts by assigning the entry
1393 ///         blocks their backedge mass from the prior iteration.  The final
1394 ///         mass for each block (and each exit, and the total backedge mass
1395 ///         used for computing loop scale) is the sum of all iterations.
1396 ///         (Running this until fixed point would "solve" the geometric
1397 ///         series by simulation.)
1398 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
1399   typedef typename bfi_detail::TypeMap<BT>::BlockT BlockT;
1400   typedef typename bfi_detail::TypeMap<BT>::FunctionT FunctionT;
1401   typedef typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT
1402   BranchProbabilityInfoT;
1403   typedef typename bfi_detail::TypeMap<BT>::LoopT LoopT;
1404   typedef typename bfi_detail::TypeMap<BT>::LoopInfoT LoopInfoT;
1405
1406   // This is part of a workaround for a GCC 4.7 crash on lambdas.
1407   friend struct bfi_detail::BlockEdgesAdder<BT>;
1408
1409   typedef GraphTraits<const BlockT *> Successor;
1410   typedef GraphTraits<Inverse<const BlockT *>> Predecessor;
1411
1412   const BranchProbabilityInfoT *BPI;
1413   const LoopInfoT *LI;
1414   const FunctionT *F;
1415
1416   // All blocks in reverse postorder.
1417   std::vector<const BlockT *> RPOT;
1418   DenseMap<const BlockT *, BlockNode> Nodes;
1419
1420   typedef typename std::vector<const BlockT *>::const_iterator rpot_iterator;
1421
1422   rpot_iterator rpot_begin() const { return RPOT.begin(); }
1423   rpot_iterator rpot_end() const { return RPOT.end(); }
1424
1425   size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
1426
1427   BlockNode getNode(const rpot_iterator &I) const {
1428     return BlockNode(getIndex(I));
1429   }
1430   BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB); }
1431
1432   const BlockT *getBlock(const BlockNode &Node) const {
1433     assert(Node.Index < RPOT.size());
1434     return RPOT[Node.Index];
1435   }
1436
1437   /// \brief Run (and save) a post-order traversal.
1438   ///
1439   /// Saves a reverse post-order traversal of all the nodes in \a F.
1440   void initializeRPOT();
1441
1442   /// \brief Initialize loop data.
1443   ///
1444   /// Build up \a Loops using \a LoopInfo.  \a LoopInfo gives us a mapping from
1445   /// each block to the deepest loop it's in, but we need the inverse.  For each
1446   /// loop, we store in reverse post-order its "immediate" members, defined as
1447   /// the header, the headers of immediate sub-loops, and all other blocks in
1448   /// the loop that are not in sub-loops.
1449   void initializeLoops();
1450
1451   /// \brief Propagate to a block's successors.
1452   ///
1453   /// In the context of distributing mass through \c OuterLoop, divide the mass
1454   /// currently assigned to \c Node between its successors.
1455   ///
1456   /// \return \c true unless there's an irreducible backedge.
1457   bool propagateMassToSuccessors(LoopData *OuterLoop, const BlockNode &Node);
1458
1459   /// \brief Compute mass in a particular loop.
1460   ///
1461   /// Assign mass to \c Loop's header, and then for each block in \c Loop in
1462   /// reverse post-order, distribute mass to its successors.  Only visits nodes
1463   /// that have not been packaged into sub-loops.
1464   ///
1465   /// \pre \a computeMassInLoop() has been called for each subloop of \c Loop.
1466   /// \return \c true unless there's an irreducible backedge.
1467   bool computeMassInLoop(LoopData &Loop);
1468
1469   /// \brief Try to compute mass in the top-level function.
1470   ///
1471   /// Assign mass to the entry block, and then for each block in reverse
1472   /// post-order, distribute mass to its successors.  Skips nodes that have
1473   /// been packaged into loops.
1474   ///
1475   /// \pre \a computeMassInLoops() has been called.
1476   /// \return \c true unless there's an irreducible backedge.
1477   bool tryToComputeMassInFunction();
1478
1479   /// \brief Compute mass in (and package up) irreducible SCCs.
1480   ///
1481   /// Find the irreducible SCCs in \c OuterLoop, add them to \a Loops (in front
1482   /// of \c Insert), and call \a computeMassInLoop() on each of them.
1483   ///
1484   /// If \c OuterLoop is \c nullptr, it refers to the top-level function.
1485   ///
1486   /// \pre \a computeMassInLoop() has been called for each subloop of \c
1487   /// OuterLoop.
1488   /// \pre \c Insert points at the the last loop successfully processed by \a
1489   /// computeMassInLoop().
1490   /// \pre \c OuterLoop has irreducible SCCs.
1491   void computeIrreducibleMass(LoopData *OuterLoop,
1492                               std::list<LoopData>::iterator Insert);
1493
1494   /// \brief Compute mass in all loops.
1495   ///
1496   /// For each loop bottom-up, call \a computeMassInLoop().
1497   ///
1498   /// \a computeMassInLoop() aborts (and returns \c false) on loops that
1499   /// contain a irreducible sub-SCCs.  Use \a computeIrreducibleMass() and then
1500   /// re-enter \a computeMassInLoop().
1501   ///
1502   /// \post \a computeMassInLoop() has returned \c true for every loop.
1503   void computeMassInLoops();
1504
1505   /// \brief Compute mass in the top-level function.
1506   ///
1507   /// Uses \a tryToComputeMassInFunction() and \a computeIrreducibleMass() to
1508   /// compute mass in the top-level function.
1509   ///
1510   /// \post \a tryToComputeMassInFunction() has returned \c true.
1511   void computeMassInFunction();
1512
1513   std::string getBlockName(const BlockNode &Node) const override {
1514     return bfi_detail::getBlockName(getBlock(Node));
1515   }
1516
1517 public:
1518   const FunctionT *getFunction() const { return F; }
1519
1520   void doFunction(const FunctionT *F, const BranchProbabilityInfoT *BPI,
1521                   const LoopInfoT *LI);
1522   BlockFrequencyInfoImpl() : BPI(nullptr), LI(nullptr), F(nullptr) {}
1523
1524   using BlockFrequencyInfoImplBase::getEntryFreq;
1525   BlockFrequency getBlockFreq(const BlockT *BB) const {
1526     return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
1527   }
1528   Float getFloatingBlockFreq(const BlockT *BB) const {
1529     return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
1530   }
1531
1532   /// \brief Print the frequencies for the current function.
1533   ///
1534   /// Prints the frequencies for the blocks in the current function.
1535   ///
1536   /// Blocks are printed in the natural iteration order of the function, rather
1537   /// than reverse post-order.  This provides two advantages:  writing -analyze
1538   /// tests is easier (since blocks come out in source order), and even
1539   /// unreachable blocks are printed.
1540   ///
1541   /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
1542   /// we need to override it here.
1543   raw_ostream &print(raw_ostream &OS) const override;
1544   using BlockFrequencyInfoImplBase::dump;
1545
1546   using BlockFrequencyInfoImplBase::printBlockFreq;
1547   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
1548     return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
1549   }
1550 };
1551
1552 template <class BT>
1553 void BlockFrequencyInfoImpl<BT>::doFunction(const FunctionT *F,
1554                                             const BranchProbabilityInfoT *BPI,
1555                                             const LoopInfoT *LI) {
1556   // Save the parameters.
1557   this->BPI = BPI;
1558   this->LI = LI;
1559   this->F = F;
1560
1561   // Clean up left-over data structures.
1562   BlockFrequencyInfoImplBase::clear();
1563   RPOT.clear();
1564   Nodes.clear();
1565
1566   // Initialize.
1567   DEBUG(dbgs() << "\nblock-frequency: " << F->getName() << "\n================="
1568                << std::string(F->getName().size(), '=') << "\n");
1569   initializeRPOT();
1570   initializeLoops();
1571
1572   // Visit loops in post-order to find thelocal mass distribution, and then do
1573   // the full function.
1574   computeMassInLoops();
1575   computeMassInFunction();
1576   unwrapLoops();
1577   finalizeMetrics();
1578 }
1579
1580 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1581   const BlockT *Entry = F->begin();
1582   RPOT.reserve(F->size());
1583   std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
1584   std::reverse(RPOT.begin(), RPOT.end());
1585
1586   assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1587          "More nodes in function than Block Frequency Info supports");
1588
1589   DEBUG(dbgs() << "reverse-post-order-traversal\n");
1590   for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
1591     BlockNode Node = getNode(I);
1592     DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) << "\n");
1593     Nodes[*I] = Node;
1594   }
1595
1596   Working.reserve(RPOT.size());
1597   for (size_t Index = 0; Index < RPOT.size(); ++Index)
1598     Working.emplace_back(Index);
1599   Freqs.resize(RPOT.size());
1600 }
1601
1602 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1603   DEBUG(dbgs() << "loop-detection\n");
1604   if (LI->empty())
1605     return;
1606
1607   // Visit loops top down and assign them an index.
1608   std::deque<std::pair<const LoopT *, LoopData *>> Q;
1609   for (const LoopT *L : *LI)
1610     Q.emplace_back(L, nullptr);
1611   while (!Q.empty()) {
1612     const LoopT *Loop = Q.front().first;
1613     LoopData *Parent = Q.front().second;
1614     Q.pop_front();
1615
1616     BlockNode Header = getNode(Loop->getHeader());
1617     assert(Header.isValid());
1618
1619     Loops.emplace_back(Parent, Header);
1620     Working[Header.Index].Loop = &Loops.back();
1621     DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1622
1623     for (const LoopT *L : *Loop)
1624       Q.emplace_back(L, &Loops.back());
1625   }
1626
1627   // Visit nodes in reverse post-order and add them to their deepest containing
1628   // loop.
1629   for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1630     // Loop headers have already been mostly mapped.
1631     if (Working[Index].isLoopHeader()) {
1632       LoopData *ContainingLoop = Working[Index].getContainingLoop();
1633       if (ContainingLoop)
1634         ContainingLoop->Nodes.push_back(Index);
1635       continue;
1636     }
1637
1638     const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1639     if (!Loop)
1640       continue;
1641
1642     // Add this node to its containing loop's member list.
1643     BlockNode Header = getNode(Loop->getHeader());
1644     assert(Header.isValid());
1645     const auto &HeaderData = Working[Header.Index];
1646     assert(HeaderData.isLoopHeader());
1647
1648     Working[Index].Loop = HeaderData.Loop;
1649     HeaderData.Loop->Nodes.push_back(Index);
1650     DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1651                  << ": member = " << getBlockName(Index) << "\n");
1652   }
1653 }
1654
1655 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1656   // Visit loops with the deepest first, and the top-level loops last.
1657   for (auto L = Loops.rbegin(), E = Loops.rend(); L != E; ++L) {
1658     if (computeMassInLoop(*L))
1659       continue;
1660     auto Next = std::next(L);
1661     computeIrreducibleMass(&*L, L.base());
1662     L = std::prev(Next);
1663     if (computeMassInLoop(*L))
1664       continue;
1665     llvm_unreachable("unhandled irreducible control flow");
1666   }
1667 }
1668
1669 template <class BT>
1670 bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
1671   // Compute mass in loop.
1672   DEBUG(dbgs() << "compute-mass-in-loop: " << getLoopName(Loop) << "\n");
1673
1674   if (Loop.isIrreducible()) {
1675     BlockMass Remaining = BlockMass::getFull();
1676     for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
1677       auto &Mass = Working[Loop.Nodes[H].Index].getMass();
1678       Mass = Remaining * BranchProbability(1, Loop.NumHeaders - H);
1679       Remaining -= Mass;
1680     }
1681     for (const BlockNode &M : Loop.Nodes)
1682       if (!propagateMassToSuccessors(&Loop, M))
1683         llvm_unreachable("unhandled irreducible control flow");
1684   } else {
1685     Working[Loop.getHeader().Index].getMass() = BlockMass::getFull();
1686     if (!propagateMassToSuccessors(&Loop, Loop.getHeader()))
1687       llvm_unreachable("irreducible control flow to loop header!?");
1688     for (const BlockNode &M : Loop.members())
1689       if (!propagateMassToSuccessors(&Loop, M))
1690         // Irreducible backedge.
1691         return false;
1692   }
1693
1694   computeLoopScale(Loop);
1695   packageLoop(Loop);
1696   return true;
1697 }
1698
1699 template <class BT>
1700 bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
1701   // Compute mass in function.
1702   DEBUG(dbgs() << "compute-mass-in-function\n");
1703   assert(!Working.empty() && "no blocks in function");
1704   assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1705
1706   Working[0].getMass() = BlockMass::getFull();
1707   for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
1708     // Check for nodes that have been packaged.
1709     BlockNode Node = getNode(I);
1710     if (Working[Node.Index].isPackaged())
1711       continue;
1712
1713     if (!propagateMassToSuccessors(nullptr, Node))
1714       return false;
1715   }
1716   return true;
1717 }
1718
1719 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1720   if (tryToComputeMassInFunction())
1721     return;
1722   computeIrreducibleMass(nullptr, Loops.begin());
1723   if (tryToComputeMassInFunction())
1724     return;
1725   llvm_unreachable("unhandled irreducible control flow");
1726 }
1727
1728 /// \note This should be a lambda, but that crashes GCC 4.7.
1729 namespace bfi_detail {
1730 template <class BT> struct BlockEdgesAdder {
1731   typedef BT BlockT;
1732   typedef BlockFrequencyInfoImplBase::LoopData LoopData;
1733   typedef GraphTraits<const BlockT *> Successor;
1734
1735   const BlockFrequencyInfoImpl<BT> &BFI;
1736   explicit BlockEdgesAdder(const BlockFrequencyInfoImpl<BT> &BFI)
1737       : BFI(BFI) {}
1738   void operator()(IrreducibleGraph &G, IrreducibleGraph::IrrNode &Irr,
1739                   const LoopData *OuterLoop) {
1740     const BlockT *BB = BFI.RPOT[Irr.Node.Index];
1741     for (auto I = Successor::child_begin(BB), E = Successor::child_end(BB);
1742          I != E; ++I)
1743       G.addEdge(Irr, BFI.getNode(*I), OuterLoop);
1744   }
1745 };
1746 }
1747 template <class BT>
1748 void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1749     LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1750   DEBUG(dbgs() << "analyze-irreducible-in-";
1751         if (OuterLoop) dbgs() << "loop: " << getLoopName(*OuterLoop) << "\n";
1752         else dbgs() << "function\n");
1753
1754   using namespace bfi_detail;
1755   // Ideally, addBlockEdges() would be declared here as a lambda, but that
1756   // crashes GCC 4.7.
1757   BlockEdgesAdder<BT> addBlockEdges(*this);
1758   IrreducibleGraph G(*this, OuterLoop, addBlockEdges);
1759
1760   for (auto &L : analyzeIrreducible(G, OuterLoop, Insert))
1761     computeMassInLoop(L);
1762
1763   if (!OuterLoop)
1764     return;
1765   updateLoopWithIrreducible(*OuterLoop);
1766 }
1767
1768 template <class BT>
1769 bool
1770 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1771                                                       const BlockNode &Node) {
1772   DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1773   // Calculate probability for successors.
1774   Distribution Dist;
1775   if (auto *Loop = Working[Node.Index].getPackagedLoop()) {
1776     assert(Loop != OuterLoop && "Cannot propagate mass in a packaged loop");
1777     if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
1778       // Irreducible backedge.
1779       return false;
1780   } else {
1781     const BlockT *BB = getBlock(Node);
1782     for (auto SI = Successor::child_begin(BB), SE = Successor::child_end(BB);
1783          SI != SE; ++SI)
1784       // Do not dereference SI, or getEdgeWeight() is linear in the number of
1785       // successors.
1786       if (!addToDist(Dist, OuterLoop, Node, getNode(*SI),
1787                      BPI->getEdgeWeight(BB, SI)))
1788         // Irreducible backedge.
1789         return false;
1790   }
1791
1792   // Distribute mass to successors, saving exit and backedge data in the
1793   // loop header.
1794   distributeMass(Node, OuterLoop, Dist);
1795   return true;
1796 }
1797
1798 template <class BT>
1799 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
1800   if (!F)
1801     return OS;
1802   OS << "block-frequency-info: " << F->getName() << "\n";
1803   for (const BlockT &BB : *F)
1804     OS << " - " << bfi_detail::getBlockName(&BB)
1805        << ": float = " << getFloatingBlockFreq(&BB)
1806        << ", int = " << getBlockFreq(&BB).getFrequency() << "\n";
1807
1808   // Add an extra newline for readability.
1809   OS << "\n";
1810   return OS;
1811 }
1812 }
1813
1814 #undef DEBUG_TYPE
1815
1816 #endif