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