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