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