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