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