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