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