bea9f79aebf2d95ab231de478ec9063d2b9d94de
[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 Data about a loop.
941   ///
942   /// Contains the data necessary to represent represent a loop as a
943   /// pseudo-node once it's packaged.
944   struct LoopData {
945     typedef SmallVector<std::pair<BlockNode, BlockMass>, 4> ExitMap;
946     typedef SmallVector<BlockNode, 4> MemberList;
947     BlockNode Header;       ///< Header.
948     ExitMap Exits;          ///< Successor edges (and weights).
949     MemberList Members;     ///< Members of the loop.
950     BlockMass BackedgeMass; ///< Mass returned to loop header.
951     BlockMass Mass;
952     Float Scale;
953
954     LoopData(const BlockNode &Header) : Header(Header) {}
955   };
956
957   /// \brief Index of loop information.
958   struct WorkingData {
959     BlockNode ContainingLoop; ///< The block whose loop this block is inside.
960     uint32_t LoopIndex;       ///< Index into PackagedLoops.
961     bool IsPackaged;          ///< Has ContainingLoop been packaged up?
962     bool IsAPackage;          ///< Has this block's loop been packaged up?
963     BlockMass Mass;           ///< Mass distribution from the entry block.
964
965     WorkingData()
966         : LoopIndex(UINT32_MAX), IsPackaged(false), IsAPackage(false) {}
967
968     bool hasLoopHeader() const { return ContainingLoop.isValid(); }
969     bool isLoopHeader() const { return LoopIndex != UINT32_MAX; }
970   };
971
972   /// \brief Unscaled probability weight.
973   ///
974   /// Probability weight for an edge in the graph (including the
975   /// successor/target node).
976   ///
977   /// All edges in the original function are 32-bit.  However, exit edges from
978   /// loop packages are taken from 64-bit exit masses, so we need 64-bits of
979   /// space in general.
980   ///
981   /// In addition to the raw weight amount, Weight stores the type of the edge
982   /// in the current context (i.e., the context of the loop being processed).
983   /// Is this a local edge within the loop, an exit from the loop, or a
984   /// backedge to the loop header?
985   struct Weight {
986     enum DistType { Local, Exit, Backedge };
987     DistType Type;
988     BlockNode TargetNode;
989     uint64_t Amount;
990     Weight() : Type(Local), Amount(0) {}
991   };
992
993   /// \brief Distribution of unscaled probability weight.
994   ///
995   /// Distribution of unscaled probability weight to a set of successors.
996   ///
997   /// This class collates the successor edge weights for later processing.
998   ///
999   /// \a DidOverflow indicates whether \a Total did overflow while adding to
1000   /// the distribution.  It should never overflow twice.  There's no flag for
1001   /// whether \a ForwardTotal overflows, since when \a Total exceeds 32-bits
1002   /// they both get re-computed during \a normalize().
1003   struct Distribution {
1004     typedef SmallVector<Weight, 4> WeightList;
1005     WeightList Weights;    ///< Individual successor weights.
1006     uint64_t Total;        ///< Sum of all weights.
1007     bool DidOverflow;      ///< Whether \a Total did overflow.
1008     uint32_t ForwardTotal; ///< Total excluding backedges.
1009
1010     Distribution() : Total(0), DidOverflow(false), ForwardTotal(0) {}
1011     void addLocal(const BlockNode &Node, uint64_t Amount) {
1012       add(Node, Amount, Weight::Local);
1013     }
1014     void addExit(const BlockNode &Node, uint64_t Amount) {
1015       add(Node, Amount, Weight::Exit);
1016     }
1017     void addBackedge(const BlockNode &Node, uint64_t Amount) {
1018       add(Node, Amount, Weight::Backedge);
1019     }
1020
1021     /// \brief Normalize the distribution.
1022     ///
1023     /// Combines multiple edges to the same \a Weight::TargetNode and scales
1024     /// down so that \a Total fits into 32-bits.
1025     ///
1026     /// This is linear in the size of \a Weights.  For the vast majority of
1027     /// cases, adjacent edge weights are combined by sorting WeightList and
1028     /// combining adjacent weights.  However, for very large edge lists an
1029     /// auxiliary hash table is used.
1030     void normalize();
1031
1032   private:
1033     void add(const BlockNode &Node, uint64_t Amount, Weight::DistType Type);
1034   };
1035
1036   /// \brief Data about each block.  This is used downstream.
1037   std::vector<FrequencyData> Freqs;
1038
1039   /// \brief Loop data: see initializeLoops().
1040   std::vector<WorkingData> Working;
1041
1042   /// \brief Indexed information about packaged loops.
1043   std::vector<LoopData> PackagedLoops;
1044
1045   /// \brief Add all edges out of a packaged loop to the distribution.
1046   ///
1047   /// Adds all edges from LocalLoopHead to Dist.  Calls addToDist() to add each
1048   /// successor edge.
1049   void addLoopSuccessorsToDist(const BlockNode &LoopHead,
1050                                const BlockNode &LocalLoopHead,
1051                                Distribution &Dist);
1052
1053   /// \brief Add an edge to the distribution.
1054   ///
1055   /// Adds an edge to Succ to Dist.  If \c LoopHead.isValid(), then whether the
1056   /// edge is forward/exit/backedge is in the context of LoopHead.  Otherwise,
1057   /// every edge should be a forward edge (since all the loops are packaged
1058   /// up).
1059   void addToDist(Distribution &Dist, const BlockNode &LoopHead,
1060                  const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight);
1061
1062   LoopData &getLoopPackage(const BlockNode &Head) {
1063     assert(Head.Index < Working.size());
1064     size_t Index = Working[Head.Index].LoopIndex;
1065     assert(Index < PackagedLoops.size());
1066     return PackagedLoops[Index];
1067   }
1068
1069   /// \brief Distribute mass according to a distribution.
1070   ///
1071   /// Distributes the mass in Source according to Dist.  If LoopHead.isValid(),
1072   /// backedges and exits are stored in its entry in PackagedLoops.
1073   ///
1074   /// Mass is distributed in parallel from two copies of the source mass.
1075   ///
1076   /// The first mass (forward) represents the distribution of mass through the
1077   /// local DAG.  This distribution should lose mass at loop exits and ignore
1078   /// backedges.
1079   ///
1080   /// The second mass (general) represents the behavior of the loop in the
1081   /// global context.  In a given distribution from the head, how much mass
1082   /// exits, and to where?  How much mass returns to the loop head?
1083   ///
1084   /// The forward mass should be split up between local successors and exits,
1085   /// but only actually distributed to the local successors.  The general mass
1086   /// should be split up between all three types of successors, but distributed
1087   /// only to exits and backedges.
1088   void distributeMass(const BlockNode &Source, const BlockNode &LoopHead,
1089                       Distribution &Dist);
1090
1091   /// \brief Compute the loop scale for a loop.
1092   void computeLoopScale(const BlockNode &LoopHead);
1093
1094   /// \brief Package up a loop.
1095   void packageLoop(const BlockNode &LoopHead);
1096
1097   /// \brief Finalize frequency metrics.
1098   ///
1099   /// Unwraps loop packages, calculates final frequencies, and cleans up
1100   /// no-longer-needed data structures.
1101   void finalizeMetrics();
1102
1103   /// \brief Clear all memory.
1104   void clear();
1105
1106   virtual std::string getBlockName(const BlockNode &Node) const;
1107
1108   virtual raw_ostream &print(raw_ostream &OS) const { return OS; }
1109   void dump() const { print(dbgs()); }
1110
1111   Float getFloatingBlockFreq(const BlockNode &Node) const;
1112
1113   BlockFrequency getBlockFreq(const BlockNode &Node) const;
1114
1115   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockNode &Node) const;
1116   raw_ostream &printBlockFreq(raw_ostream &OS,
1117                               const BlockFrequency &Freq) const;
1118
1119   uint64_t getEntryFreq() const {
1120     assert(!Freqs.empty());
1121     return Freqs[0].Integer;
1122   }
1123   /// \brief Virtual destructor.
1124   ///
1125   /// Need a virtual destructor to mask the compiler warning about
1126   /// getBlockName().
1127   virtual ~BlockFrequencyInfoImplBase() {}
1128 };
1129
1130 namespace bfi_detail {
1131 template <class BlockT> struct TypeMap {};
1132 template <> struct TypeMap<BasicBlock> {
1133   typedef BasicBlock BlockT;
1134   typedef Function FunctionT;
1135   typedef BranchProbabilityInfo BranchProbabilityInfoT;
1136   typedef Loop LoopT;
1137   typedef LoopInfo LoopInfoT;
1138 };
1139 template <> struct TypeMap<MachineBasicBlock> {
1140   typedef MachineBasicBlock BlockT;
1141   typedef MachineFunction FunctionT;
1142   typedef MachineBranchProbabilityInfo BranchProbabilityInfoT;
1143   typedef MachineLoop LoopT;
1144   typedef MachineLoopInfo LoopInfoT;
1145 };
1146
1147 /// \brief Get the name of a MachineBasicBlock.
1148 ///
1149 /// Get the name of a MachineBasicBlock.  It's templated so that including from
1150 /// CodeGen is unnecessary (that would be a layering issue).
1151 ///
1152 /// This is used mainly for debug output.  The name is similar to
1153 /// MachineBasicBlock::getFullName(), but skips the name of the function.
1154 template <class BlockT> std::string getBlockName(const BlockT *BB) {
1155   assert(BB && "Unexpected nullptr");
1156   auto MachineName = "BB" + Twine(BB->getNumber());
1157   if (BB->getBasicBlock())
1158     return (MachineName + "[" + BB->getName() + "]").str();
1159   return MachineName.str();
1160 }
1161 /// \brief Get the name of a BasicBlock.
1162 template <> inline std::string getBlockName(const BasicBlock *BB) {
1163   assert(BB && "Unexpected nullptr");
1164   return BB->getName().str();
1165 }
1166 }
1167
1168 /// \brief Shared implementation for block frequency analysis.
1169 ///
1170 /// This is a shared implementation of BlockFrequencyInfo and
1171 /// MachineBlockFrequencyInfo, and calculates the relative frequencies of
1172 /// blocks.
1173 ///
1174 /// This algorithm leverages BlockMass and UnsignedFloat to maintain precision,
1175 /// separates mass distribution from loop scaling, and dithers to eliminate
1176 /// probability mass loss.
1177 ///
1178 /// The implementation is split between BlockFrequencyInfoImpl, which knows the
1179 /// type of graph being modelled (BasicBlock vs. MachineBasicBlock), and
1180 /// BlockFrequencyInfoImplBase, which doesn't.  The base class uses \a
1181 /// BlockNode, a wrapper around a uint32_t.  BlockNode is numbered from 0 in
1182 /// reverse-post order.  This gives two advantages:  it's easy to compare the
1183 /// relative ordering of two nodes, and maps keyed on BlockT can be represented
1184 /// by vectors.
1185 ///
1186 /// This algorithm is O(V+E), unless there is irreducible control flow, in
1187 /// which case it's O(V*E) in the worst case.
1188 ///
1189 /// These are the main stages:
1190 ///
1191 ///  0. Reverse post-order traversal (\a initializeRPOT()).
1192 ///
1193 ///     Run a single post-order traversal and save it (in reverse) in RPOT.
1194 ///     All other stages make use of this ordering.  Save a lookup from BlockT
1195 ///     to BlockNode (the index into RPOT) in Nodes.
1196 ///
1197 ///  1. Loop indexing (\a initializeLoops()).
1198 ///
1199 ///     Translate LoopInfo/MachineLoopInfo into a form suitable for the rest of
1200 ///     the algorithm.  In particular, store the immediate members of each loop
1201 ///     in reverse post-order.
1202 ///
1203 ///  2. Calculate mass and scale in loops (\a computeMassInLoops()).
1204 ///
1205 ///     For each loop (bottom-up), distribute mass through the DAG resulting
1206 ///     from ignoring backedges and treating sub-loops as a single pseudo-node.
1207 ///     Track the backedge mass distributed to the loop header, and use it to
1208 ///     calculate the loop scale (number of loop iterations).
1209 ///
1210 ///     Visiting loops bottom-up is a post-order traversal of loop headers.
1211 ///     For each loop, immediate members that represent sub-loops will already
1212 ///     have been visited and packaged into a pseudo-node.
1213 ///
1214 ///     Distributing mass in a loop is a reverse-post-order traversal through
1215 ///     the loop.  Start by assigning full mass to the Loop header.  For each
1216 ///     node in the loop:
1217 ///
1218 ///         - Fetch and categorize the weight distribution for its successors.
1219 ///           If this is a packaged-subloop, the weight distribution is stored
1220 ///           in \a LoopData::Exits.  Otherwise, fetch it from
1221 ///           BranchProbabilityInfo.
1222 ///
1223 ///         - Each successor is categorized as \a Weight::Local, a normal
1224 ///           forward edge within the current loop, \a Weight::Backedge, a
1225 ///           backedge to the loop header, or \a Weight::Exit, any successor
1226 ///           outside the loop.  The weight, the successor, and its category
1227 ///           are stored in \a Distribution.  There can be multiple edges to
1228 ///           each successor.
1229 ///
1230 ///         - Normalize the distribution:  scale weights down so that their sum
1231 ///           is 32-bits, and coalesce multiple edges to the same node.
1232 ///
1233 ///         - Distribute the mass accordingly, dithering to minimize mass loss,
1234 ///           as described in \a distributeMass().  Mass is distributed in
1235 ///           parallel in two ways: forward, and general.  Local successors
1236 ///           take their mass from the forward mass, while exit and backedge
1237 ///           successors take their mass from the general mass.  Additionally,
1238 ///           exit edges use up (ignored) mass from the forward mass, and local
1239 ///           edges use up (ignored) mass from the general distribution.
1240 ///
1241 ///     Finally, calculate the loop scale from the accumulated backedge mass.
1242 ///
1243 ///  3. Distribute mass in the function (\a computeMassInFunction()).
1244 ///
1245 ///     Finally, distribute mass through the DAG resulting from packaging all
1246 ///     loops in the function.  This uses the same algorithm as distributing
1247 ///     mass in a loop, except that there are no exit or backedge edges.
1248 ///
1249 ///  4. Loop unpackaging and cleanup (\a finalizeMetrics()).
1250 ///
1251 ///     Initialize the frequency to a floating point representation of its
1252 ///     mass.
1253 ///
1254 ///     Visit loops top-down (reverse post-order), scaling the loop header's
1255 ///     frequency by its psuedo-node's mass and loop scale.  Keep track of the
1256 ///     minimum and maximum final frequencies.
1257 ///
1258 ///     Using the min and max frequencies as a guide, translate floating point
1259 ///     frequencies to an appropriate range in uint64_t.
1260 ///
1261 /// It has some known flaws.
1262 ///
1263 ///   - Irreducible control flow isn't modelled correctly.  In particular,
1264 ///     LoopInfo and MachineLoopInfo ignore irreducible backedges.  The main
1265 ///     result is that irreducible SCCs will under-scaled.  No mass is lost,
1266 ///     but the computed branch weights for the loop pseudo-node will be
1267 ///     incorrect.
1268 ///
1269 ///     Modelling irreducible control flow exactly involves setting up and
1270 ///     solving a group of infinite geometric series.  Such precision is
1271 ///     unlikely to be worthwhile, since most of our algorithms give up on
1272 ///     irreducible control flow anyway.
1273 ///
1274 ///     Nevertheless, we might find that we need to get closer.  If
1275 ///     LoopInfo/MachineLoopInfo flags loops with irreducible control flow
1276 ///     (and/or the function as a whole), we can find the SCCs, compute an
1277 ///     approximate exit frequency for the SCC as a whole, and scale up
1278 ///     accordingly.
1279 ///
1280 ///   - Loop scale is limited to 4096 per loop (2^12) to avoid exhausting
1281 ///     BlockFrequency's 64-bit integer precision.
1282 template <class BT> class BlockFrequencyInfoImpl : BlockFrequencyInfoImplBase {
1283   typedef typename bfi_detail::TypeMap<BT>::BlockT BlockT;
1284   typedef typename bfi_detail::TypeMap<BT>::FunctionT FunctionT;
1285   typedef typename bfi_detail::TypeMap<BT>::BranchProbabilityInfoT
1286   BranchProbabilityInfoT;
1287   typedef typename bfi_detail::TypeMap<BT>::LoopT LoopT;
1288   typedef typename bfi_detail::TypeMap<BT>::LoopInfoT LoopInfoT;
1289
1290   typedef GraphTraits<const BlockT *> Successor;
1291   typedef GraphTraits<Inverse<const BlockT *>> Predecessor;
1292
1293   const BranchProbabilityInfoT *BPI;
1294   const LoopInfoT *LI;
1295   const FunctionT *F;
1296
1297   // All blocks in reverse postorder.
1298   std::vector<const BlockT *> RPOT;
1299   DenseMap<const BlockT *, BlockNode> Nodes;
1300
1301   typedef typename std::vector<const BlockT *>::const_iterator rpot_iterator;
1302
1303   rpot_iterator rpot_begin() const { return RPOT.begin(); }
1304   rpot_iterator rpot_end() const { return RPOT.end(); }
1305
1306   size_t getIndex(const rpot_iterator &I) const { return I - rpot_begin(); }
1307
1308   BlockNode getNode(const rpot_iterator &I) const {
1309     return BlockNode(getIndex(I));
1310   }
1311   BlockNode getNode(const BlockT *BB) const { return Nodes.lookup(BB); }
1312
1313   const BlockT *getBlock(const BlockNode &Node) const {
1314     assert(Node.Index < RPOT.size());
1315     return RPOT[Node.Index];
1316   }
1317
1318   void initializeRPOT();
1319   void initializeLoops();
1320   void runOnFunction(const FunctionT *F);
1321
1322   void propagateMassToSuccessors(const BlockNode &LoopHead,
1323                                  const BlockNode &Node);
1324   void computeMassInLoops();
1325   void computeMassInLoop(const BlockNode &LoopHead);
1326   void computeMassInFunction();
1327
1328   std::string getBlockName(const BlockNode &Node) const override {
1329     return bfi_detail::getBlockName(getBlock(Node));
1330   }
1331
1332 public:
1333   const FunctionT *getFunction() const { return F; }
1334
1335   void doFunction(const FunctionT *F, const BranchProbabilityInfoT *BPI,
1336                   const LoopInfoT *LI);
1337   BlockFrequencyInfoImpl() : BPI(0), LI(0), F(0) {}
1338
1339   using BlockFrequencyInfoImplBase::getEntryFreq;
1340   BlockFrequency getBlockFreq(const BlockT *BB) const {
1341     return BlockFrequencyInfoImplBase::getBlockFreq(getNode(BB));
1342   }
1343   Float getFloatingBlockFreq(const BlockT *BB) const {
1344     return BlockFrequencyInfoImplBase::getFloatingBlockFreq(getNode(BB));
1345   }
1346
1347   /// \brief Print the frequencies for the current function.
1348   ///
1349   /// Prints the frequencies for the blocks in the current function.
1350   ///
1351   /// Blocks are printed in the natural iteration order of the function, rather
1352   /// than reverse post-order.  This provides two advantages:  writing -analyze
1353   /// tests is easier (since blocks come out in source order), and even
1354   /// unreachable blocks are printed.
1355   ///
1356   /// \a BlockFrequencyInfoImplBase::print() only knows reverse post-order, so
1357   /// we need to override it here.
1358   raw_ostream &print(raw_ostream &OS) const override;
1359   using BlockFrequencyInfoImplBase::dump;
1360
1361   using BlockFrequencyInfoImplBase::printBlockFreq;
1362   raw_ostream &printBlockFreq(raw_ostream &OS, const BlockT *BB) const {
1363     return BlockFrequencyInfoImplBase::printBlockFreq(OS, getNode(BB));
1364   }
1365 };
1366
1367 template <class BT>
1368 void BlockFrequencyInfoImpl<BT>::doFunction(const FunctionT *F,
1369                                             const BranchProbabilityInfoT *BPI,
1370                                             const LoopInfoT *LI) {
1371   // Save the parameters.
1372   this->BPI = BPI;
1373   this->LI = LI;
1374   this->F = F;
1375
1376   // Clean up left-over data structures.
1377   BlockFrequencyInfoImplBase::clear();
1378   RPOT.clear();
1379   Nodes.clear();
1380
1381   // Initialize.
1382   DEBUG(dbgs() << "\nblock-frequency: " << F->getName() << "\n================="
1383                << std::string(F->getName().size(), '=') << "\n");
1384   initializeRPOT();
1385   initializeLoops();
1386
1387   // Visit loops in post-order to find thelocal mass distribution, and then do
1388   // the full function.
1389   computeMassInLoops();
1390   computeMassInFunction();
1391   finalizeMetrics();
1392 }
1393
1394 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1395   const BlockT *Entry = F->begin();
1396   RPOT.reserve(F->size());
1397   std::copy(po_begin(Entry), po_end(Entry), std::back_inserter(RPOT));
1398   std::reverse(RPOT.begin(), RPOT.end());
1399
1400   assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1401          "More nodes in function than Block Frequency Info supports");
1402
1403   DEBUG(dbgs() << "reverse-post-order-traversal\n");
1404   for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
1405     BlockNode Node = getNode(I);
1406     DEBUG(dbgs() << " - " << getIndex(I) << ": " << getBlockName(Node) << "\n");
1407     Nodes[*I] = Node;
1408   }
1409
1410   Working.resize(RPOT.size());
1411   Freqs.resize(RPOT.size());
1412 }
1413
1414 template <class BT> void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1415   DEBUG(dbgs() << "loop-detection\n");
1416   if (LI->empty())
1417     return;
1418
1419   // Visit loops top down and assign them an index.
1420   std::deque<const LoopT *> Q;
1421   Q.insert(Q.end(), LI->begin(), LI->end());
1422   while (!Q.empty()) {
1423     const LoopT *Loop = Q.front();
1424     Q.pop_front();
1425     Q.insert(Q.end(), Loop->begin(), Loop->end());
1426
1427     // Save the order this loop was visited.
1428     BlockNode Header = getNode(Loop->getHeader());
1429     assert(Header.isValid());
1430
1431     Working[Header.Index].LoopIndex = PackagedLoops.size();
1432     PackagedLoops.emplace_back(Header);
1433     DEBUG(dbgs() << " - loop = " << getBlockName(Header) << "\n");
1434   }
1435
1436   // Visit nodes in reverse post-order and add them to their deepest containing
1437   // loop.
1438   for (size_t Index = 0; Index < RPOT.size(); ++Index) {
1439     const LoopT *Loop = LI->getLoopFor(RPOT[Index]);
1440     if (!Loop)
1441       continue;
1442
1443     // If this is a loop header, find its parent loop (if any).
1444     if (Working[Index].isLoopHeader())
1445       if (!(Loop = Loop->getParentLoop()))
1446         continue;
1447
1448     // Add this node to its containing loop's member list.
1449     BlockNode Header = getNode(Loop->getHeader());
1450     assert(Header.isValid());
1451     const auto &HeaderData = Working[Header.Index];
1452     assert(HeaderData.isLoopHeader());
1453
1454     Working[Index].ContainingLoop = Header;
1455     PackagedLoops[HeaderData.LoopIndex].Members.push_back(Index);
1456     DEBUG(dbgs() << " - loop = " << getBlockName(Header)
1457                  << ": member = " << getBlockName(Index) << "\n");
1458   }
1459 }
1460
1461 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1462   // Visit loops with the deepest first, and the top-level loops last.
1463   for (auto L = PackagedLoops.rbegin(), LE = PackagedLoops.rend(); L != LE; ++L)
1464     computeMassInLoop(L->Header);
1465 }
1466
1467 template <class BT>
1468 void BlockFrequencyInfoImpl<BT>::computeMassInLoop(const BlockNode &LoopHead) {
1469   // Compute mass in loop.
1470   DEBUG(dbgs() << "compute-mass-in-loop: " << getBlockName(LoopHead) << "\n");
1471
1472   Working[LoopHead.Index].Mass = BlockMass::getFull();
1473   propagateMassToSuccessors(LoopHead, LoopHead);
1474
1475   for (const BlockNode &M : getLoopPackage(LoopHead).Members)
1476     propagateMassToSuccessors(LoopHead, M);
1477
1478   computeLoopScale(LoopHead);
1479   packageLoop(LoopHead);
1480 }
1481
1482 template <class BT> void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1483   // Compute mass in function.
1484   DEBUG(dbgs() << "compute-mass-in-function\n");
1485   assert(!Working.empty() && "no blocks in function");
1486   assert(!Working[0].isLoopHeader() && "entry block is a loop header");
1487
1488   Working[0].Mass = BlockMass::getFull();
1489   for (rpot_iterator I = rpot_begin(), IE = rpot_end(); I != IE; ++I) {
1490     // Check for nodes that have been packaged.
1491     BlockNode Node = getNode(I);
1492     if (Working[Node.Index].hasLoopHeader())
1493       continue;
1494
1495     propagateMassToSuccessors(BlockNode(), Node);
1496   }
1497 }
1498
1499 template <class BT>
1500 void
1501 BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(const BlockNode &LoopHead,
1502                                                       const BlockNode &Node) {
1503   DEBUG(dbgs() << " - node: " << getBlockName(Node) << "\n");
1504   // Calculate probability for successors.
1505   Distribution Dist;
1506   if (Node != LoopHead && Working[Node.Index].isLoopHeader())
1507     addLoopSuccessorsToDist(LoopHead, Node, Dist);
1508   else {
1509     const BlockT *BB = getBlock(Node);
1510     for (auto SI = Successor::child_begin(BB), SE = Successor::child_end(BB);
1511          SI != SE; ++SI)
1512       // Do not dereference SI, or getEdgeWeight() is linear in the number of
1513       // successors.
1514       addToDist(Dist, LoopHead, Node, getNode(*SI), BPI->getEdgeWeight(BB, SI));
1515   }
1516
1517   // Distribute mass to successors, saving exit and backedge data in the
1518   // loop header.
1519   distributeMass(Node, LoopHead, Dist);
1520 }
1521
1522 template <class BT>
1523 raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
1524   if (!F)
1525     return OS;
1526   OS << "block-frequency-info: " << F->getName() << "\n";
1527   for (const BlockT &BB : *F)
1528     OS << " - " << bfi_detail::getBlockName(&BB)
1529        << ": float = " << getFloatingBlockFreq(&BB)
1530        << ", int = " << getBlockFreq(&BB).getFrequency() << "\n";
1531
1532   // Add an extra newline for readability.
1533   OS << "\n";
1534   return OS;
1535 }
1536 }
1537
1538 #undef DEBUG_TYPE
1539
1540 #endif