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