blockfreq: Rewrite BlockFrequencyInfoImpl
[oota-llvm.git] / lib / Analysis / BlockFrequencyInfoImpl.cpp
1 //===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
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 // Loops should be simplified before this analysis.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "block-freq"
15 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include <deque>
19
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 //
24 // PositiveFloat implementation.
25 //
26 //===----------------------------------------------------------------------===//
27 const int PositiveFloatBase::MaxExponent;
28 const int PositiveFloatBase::MinExponent;
29
30 static void appendDigit(std::string &Str, unsigned D) {
31   assert(D < 10);
32   Str += '0' + D % 10;
33 }
34
35 static void appendNumber(std::string &Str, uint64_t N) {
36   while (N) {
37     appendDigit(Str, N % 10);
38     N /= 10;
39   }
40 }
41
42 static bool doesRoundUp(char Digit) {
43   switch (Digit) {
44   case '5':
45   case '6':
46   case '7':
47   case '8':
48   case '9':
49     return true;
50   default:
51     return false;
52   }
53 }
54
55 static std::string toStringAPFloat(uint64_t D, int E, unsigned Precision) {
56   assert(E >= PositiveFloatBase::MinExponent);
57   assert(E <= PositiveFloatBase::MaxExponent);
58
59   // Find a new E, but don't let it increase past MaxExponent.
60   int LeadingZeros = PositiveFloatBase::countLeadingZeros64(D);
61   int NewE = std::min(PositiveFloatBase::MaxExponent, E + 63 - LeadingZeros);
62   int Shift = 63 - (NewE - E);
63   assert(Shift <= LeadingZeros);
64   assert(Shift == LeadingZeros || NewE == PositiveFloatBase::MaxExponent);
65   D <<= Shift;
66   E = NewE;
67
68   // Check for a denormal.
69   unsigned AdjustedE = E + 16383;
70   if (!(D >> 63)) {
71     assert(E == PositiveFloatBase::MaxExponent);
72     AdjustedE = 0;
73   }
74
75   // Build the float and print it.
76   uint64_t RawBits[2] = {D, AdjustedE};
77   APFloat Float(APFloat::x87DoubleExtended, APInt(80, RawBits));
78   SmallVector<char, 24> Chars;
79   Float.toString(Chars, Precision, 0);
80   return std::string(Chars.begin(), Chars.end());
81 }
82
83 static std::string stripTrailingZeros(std::string Float) {
84   size_t NonZero = Float.find_last_not_of('0');
85   assert(NonZero != std::string::npos && "no . in floating point string");
86
87   if (Float[NonZero] == '.')
88     ++NonZero;
89
90   return Float.substr(0, NonZero + 1);
91 }
92
93 std::string PositiveFloatBase::toString(uint64_t D, int16_t E, int Width,
94                                         unsigned Precision) {
95   if (!D)
96     return "0.0";
97
98   // Canonicalize exponent and digits.
99   uint64_t Above0 = 0;
100   uint64_t Below0 = 0;
101   uint64_t Extra = 0;
102   int ExtraShift = 0;
103   if (E == 0) {
104     Above0 = D;
105   } else if (E > 0) {
106     if (int Shift = std::min(int16_t(countLeadingZeros64(D)), E)) {
107       D <<= Shift;
108       E -= Shift;
109
110       if (!E)
111         Above0 = D;
112     }
113   } else if (E > -64) {
114     Above0 = D >> -E;
115     Below0 = D << (64 + E);
116   } else if (E > -120) {
117     Below0 = D >> (-E - 64);
118     Extra = D << (128 + E);
119     ExtraShift = -64 - E;
120   }
121
122   // Fall back on APFloat for very small and very large numbers.
123   if (!Above0 && !Below0)
124     return toStringAPFloat(D, E, Precision);
125
126   // Append the digits before the decimal.
127   std::string Str;
128   size_t DigitsOut = 0;
129   if (Above0) {
130     appendNumber(Str, Above0);
131     DigitsOut = Str.size();
132   } else
133     appendDigit(Str, 0);
134   std::reverse(Str.begin(), Str.end());
135
136   // Return early if there's nothing after the decimal.
137   if (!Below0)
138     return Str + ".0";
139
140   // Append the decimal and beyond.
141   Str += '.';
142   uint64_t Error = UINT64_C(1) << (64 - Width);
143
144   // We need to shift Below0 to the right to make space for calculating
145   // digits.  Save the precision we're losing in Extra.
146   Extra = (Below0 & 0xf) << 56 | (Extra >> 8);
147   Below0 >>= 4;
148   size_t SinceDot = 0;
149   size_t AfterDot = Str.size();
150   do {
151     if (ExtraShift) {
152       --ExtraShift;
153       Error *= 5;
154     } else
155       Error *= 10;
156
157     Below0 *= 10;
158     Extra *= 10;
159     Below0 += (Extra >> 60);
160     Extra = Extra & (UINT64_MAX >> 4);
161     appendDigit(Str, Below0 >> 60);
162     Below0 = Below0 & (UINT64_MAX >> 4);
163     if (DigitsOut || Str.back() != '0')
164       ++DigitsOut;
165     ++SinceDot;
166   } while (Error && (Below0 << 4 | Extra >> 60) >= Error / 2 &&
167            (!Precision || DigitsOut <= Precision || SinceDot < 2));
168
169   // Return early for maximum precision.
170   if (!Precision || DigitsOut <= Precision)
171     return stripTrailingZeros(Str);
172
173   // Find where to truncate.
174   size_t Truncate =
175       std::max(Str.size() - (DigitsOut - Precision), AfterDot + 1);
176
177   // Check if there's anything to truncate.
178   if (Truncate >= Str.size())
179     return stripTrailingZeros(Str);
180
181   bool Carry = doesRoundUp(Str[Truncate]);
182   if (!Carry)
183     return stripTrailingZeros(Str.substr(0, Truncate));
184
185   // Round with the first truncated digit.
186   for (std::string::reverse_iterator I(Str.begin() + Truncate), E = Str.rend();
187        I != E; ++I) {
188     if (*I == '.')
189       continue;
190     if (*I == '9') {
191       *I = '0';
192       continue;
193     }
194
195     ++*I;
196     Carry = false;
197     break;
198   }
199
200   // Add "1" in front if we still need to carry.
201   return stripTrailingZeros(std::string(Carry, '1') + Str.substr(0, Truncate));
202 }
203
204 raw_ostream &PositiveFloatBase::print(raw_ostream &OS, uint64_t D, int16_t E,
205                                       int Width, unsigned Precision) {
206   return OS << toString(D, E, Width, Precision);
207 }
208
209 void PositiveFloatBase::dump(uint64_t D, int16_t E, int Width) {
210   print(dbgs(), D, E, Width, 0) << "[" << Width << ":" << D << "*2^" << E
211                                 << "]";
212 }
213
214 static std::pair<uint64_t, int16_t>
215 getRoundedFloat(uint64_t N, bool ShouldRound, int64_t Shift) {
216   if (ShouldRound)
217     if (!++N)
218       // Rounding caused an overflow.
219       return std::make_pair(UINT64_C(1), Shift + 64);
220   return std::make_pair(N, Shift);
221 }
222
223 std::pair<uint64_t, int16_t> PositiveFloatBase::divide64(uint64_t Dividend,
224                                                          uint64_t Divisor) {
225   // Input should be sanitized.
226   assert(Divisor);
227   assert(Dividend);
228
229   // Minimize size of divisor.
230   int16_t Shift = 0;
231   if (int Zeros = countTrailingZeros(Divisor)) {
232     Shift -= Zeros;
233     Divisor >>= Zeros;
234   }
235
236   // Check for powers of two.
237   if (Divisor == 1)
238     return std::make_pair(Dividend, Shift);
239
240   // Maximize size of dividend.
241   if (int Zeros = countLeadingZeros64(Dividend)) {
242     Shift -= Zeros;
243     Dividend <<= Zeros;
244   }
245
246   // Start with the result of a divide.
247   uint64_t Quotient = Dividend / Divisor;
248   Dividend %= Divisor;
249
250   // Continue building the quotient with long division.
251   //
252   // TODO: continue with largers digits.
253   while (!(Quotient >> 63) && Dividend) {
254     // Shift Dividend, and check for overflow.
255     bool IsOverflow = Dividend >> 63;
256     Dividend <<= 1;
257     --Shift;
258
259     // Divide.
260     bool DoesDivide = IsOverflow || Divisor <= Dividend;
261     Quotient = (Quotient << 1) | DoesDivide;
262     Dividend -= DoesDivide ? Divisor : 0;
263   }
264
265   // Round.
266   if (Dividend >= getHalf(Divisor))
267     if (!++Quotient)
268       // Rounding caused an overflow in Quotient.
269       return std::make_pair(UINT64_C(1), Shift + 64);
270
271   return getRoundedFloat(Quotient, Dividend >= getHalf(Divisor), Shift);
272 }
273
274 static void addWithCarry(uint64_t &Upper, uint64_t &Lower, uint64_t N) {
275   uint64_t NewLower = Lower + (N << 32);
276   Upper += (N >> 32) + (NewLower < Lower);
277   Lower = NewLower;
278 }
279
280 std::pair<uint64_t, int16_t> PositiveFloatBase::multiply64(uint64_t L,
281                                                            uint64_t R) {
282   // Separate into two 32-bit digits (U.L).
283   uint64_t UL = L >> 32, LL = L & UINT32_MAX, UR = R >> 32, LR = R & UINT32_MAX;
284
285   // Compute cross products.
286   uint64_t P1 = UL * UR, P2 = UL * LR, P3 = LL * UR, P4 = LL * LR;
287
288   // Sum into two 64-bit digits.
289   uint64_t Upper = P1, Lower = P4;
290   addWithCarry(Upper, Lower, P2);
291   addWithCarry(Upper, Lower, P3);
292
293   // Check for the lower 32 bits.
294   if (!Upper)
295     return std::make_pair(Lower, 0);
296
297   // Shift as little as possible to maximize precision.
298   unsigned LeadingZeros = countLeadingZeros64(Upper);
299   int16_t Shift = 64 - LeadingZeros;
300   if (LeadingZeros)
301     Upper = Upper << LeadingZeros | Lower >> Shift;
302   bool ShouldRound = Shift && (Lower & UINT64_C(1) << (Shift - 1));
303   return getRoundedFloat(Upper, ShouldRound, Shift);
304 }
305
306 //===----------------------------------------------------------------------===//
307 //
308 // BlockMass implementation.
309 //
310 //===----------------------------------------------------------------------===//
311 BlockMass &BlockMass::operator*=(const BranchProbability &P) {
312   uint32_t N = P.getNumerator(), D = P.getDenominator();
313   assert(D || "divide by 0");
314   assert(N <= D || "fraction greater than 1");
315
316   // Fast path for multiplying by 1.0.
317   if (!Mass || N == D)
318     return *this;
319
320   // Get as much precision as we can.
321   int Shift = countLeadingZeros(Mass);
322   uint64_t ShiftedQuotient = (Mass << Shift) / D;
323   uint64_t Product = ShiftedQuotient * N >> Shift;
324
325   // Now check for what's lost.
326   uint64_t Left = ShiftedQuotient * (D - N) >> Shift;
327   uint64_t Lost = Mass - Product - Left;
328
329   // TODO: prove this assertion.
330   assert(Lost <= UINT32_MAX);
331
332   // Take the product plus a portion of the spoils.
333   Mass = Product + Lost * N / D;
334   return *this;
335 }
336
337 PositiveFloat<uint64_t> BlockMass::toFloat() const {
338   if (isFull())
339     return PositiveFloat<uint64_t>(1, 0);
340   return PositiveFloat<uint64_t>(getMass() + 1, -64);
341 }
342
343 void BlockMass::dump() const { print(dbgs()); }
344
345 static char getHexDigit(int N) {
346   assert(N < 16);
347   if (N < 10)
348     return '0' + N;
349   return 'a' + N - 10;
350 }
351 raw_ostream &BlockMass::print(raw_ostream &OS) const {
352   for (int Digits = 0; Digits < 16; ++Digits)
353     OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
354   return OS;
355 }
356
357 //===----------------------------------------------------------------------===//
358 //
359 // BlockFrequencyInfoImpl implementation.
360 //
361 //===----------------------------------------------------------------------===//
362 namespace {
363
364 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
365 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
366 typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
367 typedef BlockFrequencyInfoImplBase::Float Float;
368 typedef BlockFrequencyInfoImplBase::PackagedLoopData PackagedLoopData;
369 typedef BlockFrequencyInfoImplBase::Weight Weight;
370 typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
371
372 /// \brief Stack entry describing a loop.
373 struct LoopStackEntry {
374   BlockNode LoopHead;
375   BlockNode LatestBackedge;
376 };
377
378 /// \brief Stack describing currently open loops.
379 struct LoopStack {
380   std::vector<LoopStackEntry> OpenLoops;
381
382   void push(const BlockNode &LoopHead, const BlockNode &LatestBackedge) {
383     assert(LoopHead.isValid());
384     assert(LatestBackedge.isValid());
385     OpenLoops.push_back({LoopHead, LatestBackedge});
386   }
387   void pop(const BlockNode &FinishedNode) {
388     while (!empty() && top().LatestBackedge <= FinishedNode)
389       OpenLoops.pop_back();
390   }
391   bool empty() const { return OpenLoops.empty(); }
392   const LoopStackEntry &top() const {
393     assert(!OpenLoops.empty());
394     return OpenLoops.back();
395   }
396   void adjustAfterFinishing(const BlockNode &Current,
397                             const BlockNode &LatestBackedge) {
398     pop(Current);
399     if (LatestBackedge.isValid() && LatestBackedge > Current)
400       push(Current, LatestBackedge);
401   }
402 };
403
404 /// \brief Dithering mass distributer.
405 ///
406 /// This class splits up a single mass into portions by weight, dithering to
407 /// spread out error.  No mass is lost.  The dithering precision depends on the
408 /// precision of the product of \a BlockMass and \a BranchProbability.
409 ///
410 /// The distribution algorithm follows.
411 ///
412 ///  1. Initialize by saving the sum of the weights in \a RemWeight and the
413 ///     mass to distribute in \a RemMass.
414 ///
415 ///  2. For each portion:
416 ///
417 ///      1. Construct a branch probability, P, as the portion's weight divided
418 ///         by the current value of \a RemWeight.
419 ///      2. Calculate the portion's mass as \a RemMass times P.
420 ///      3. Update \a RemWeight and \a RemMass at each portion by subtracting
421 ///         the current portion's weight and mass.
422 ///
423 /// Mass is distributed in two ways: full distribution and forward
424 /// distribution.  The latter ignores backedges, and uses the parallel fields
425 /// \a RemForwardWeight and \a RemForwardMass.
426 struct DitheringDistributer {
427   uint32_t RemWeight;
428   uint32_t RemForwardWeight;
429
430   BlockMass RemMass;
431   BlockMass RemForwardMass;
432
433   DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
434
435   BlockMass takeLocalMass(uint32_t Weight) {
436     (void)takeMass(Weight);
437     return takeForwardMass(Weight);
438   }
439   BlockMass takeExitMass(uint32_t Weight) {
440     (void)takeForwardMass(Weight);
441     return takeMass(Weight);
442   }
443   BlockMass takeBackedgeMass(uint32_t Weight) { return takeMass(Weight); }
444
445 private:
446   BlockMass takeForwardMass(uint32_t Weight);
447   BlockMass takeMass(uint32_t Weight);
448 };
449 }
450
451 DitheringDistributer::DitheringDistributer(Distribution &Dist,
452                                            const BlockMass &Mass) {
453   Dist.normalize();
454   RemWeight = Dist.Total;
455   RemForwardWeight = Dist.ForwardTotal;
456   RemMass = Mass;
457   RemForwardMass = Dist.ForwardTotal ? Mass : BlockMass();
458 }
459
460 BlockMass DitheringDistributer::takeForwardMass(uint32_t Weight) {
461   // Compute the amount of mass to take.
462   assert(Weight && "invalid weight");
463   assert(Weight <= RemForwardWeight);
464   BlockMass Mass = RemForwardMass * BranchProbability(Weight, RemForwardWeight);
465
466   // Decrement totals (dither).
467   RemForwardWeight -= Weight;
468   RemForwardMass -= Mass;
469   return Mass;
470 }
471 BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
472   assert(Weight && "invalid weight");
473   assert(Weight <= RemWeight);
474   BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
475
476   // Decrement totals (dither).
477   RemWeight -= Weight;
478   RemMass -= Mass;
479   return Mass;
480 }
481
482 void Distribution::add(const BlockNode &Node, uint64_t Amount,
483                        Weight::DistType Type) {
484   assert(Amount && "invalid weight of 0");
485   uint64_t NewTotal = Total + Amount;
486
487   // Check for overflow.  It should be impossible to overflow twice.
488   bool IsOverflow = NewTotal < Total;
489   assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
490   DidOverflow |= IsOverflow;
491
492   // Update the total.
493   Total = NewTotal;
494
495   // Save the weight.
496   Weight W;
497   W.TargetNode = Node;
498   W.Amount = Amount;
499   W.Type = Type;
500   Weights.push_back(W);
501
502   if (Type == Weight::Backedge)
503     return;
504
505   // Update forward total.  Don't worry about overflow here, since then Total
506   // will exceed 32-bits and they'll both be recomputed in normalize().
507   ForwardTotal += Amount;
508 }
509
510 static void combineWeight(Weight &W, const Weight &OtherW) {
511   assert(OtherW.TargetNode.isValid());
512   if (!W.Amount) {
513     W = OtherW;
514     return;
515   }
516   assert(W.Type == OtherW.Type);
517   assert(W.TargetNode == OtherW.TargetNode);
518   assert(W.Amount < W.Amount + OtherW.Amount);
519   W.Amount += OtherW.Amount;
520 }
521 static void combineWeightsBySorting(WeightList &Weights) {
522   // Sort so edges to the same node are adjacent.
523   std::sort(Weights.begin(), Weights.end(),
524             [](const Weight &L,
525                const Weight &R) { return L.TargetNode < R.TargetNode; });
526
527   // Combine adjacent edges.
528   WeightList::iterator O = Weights.begin();
529   for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
530        ++O, (I = L)) {
531     *O = *I;
532
533     // Find the adjacent weights to the same node.
534     for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
535       combineWeight(*O, *L);
536   }
537
538   // Erase extra entries.
539   Weights.erase(O, Weights.end());
540   return;
541 }
542 static void combineWeightsByHashing(WeightList &Weights) {
543   // Collect weights into a DenseMap.
544   typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
545   HashTable Combined(NextPowerOf2(2 * Weights.size()));
546   for (const Weight &W : Weights)
547     combineWeight(Combined[W.TargetNode.Index], W);
548
549   // Check whether anything changed.
550   if (Weights.size() == Combined.size())
551     return;
552
553   // Fill in the new weights.
554   Weights.clear();
555   Weights.reserve(Combined.size());
556   for (const auto &I : Combined)
557     Weights.push_back(I.second);
558 }
559 static void combineWeights(WeightList &Weights) {
560   // Use a hash table for many successors to keep this linear.
561   if (Weights.size() > 128) {
562     combineWeightsByHashing(Weights);
563     return;
564   }
565
566   combineWeightsBySorting(Weights);
567 }
568 static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
569   assert(Shift >= 0);
570   assert(Shift < 64);
571   if (!Shift)
572     return N;
573   return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
574 }
575 void Distribution::normalize() {
576   // Early exit for termination nodes.
577   if (Weights.empty())
578     return;
579
580   // Only bother if there are multiple successors.
581   if (Weights.size() > 1)
582     combineWeights(Weights);
583
584   // Early exit when combined into a single successor.
585   if (Weights.size() == 1) {
586     Total = 1;
587     ForwardTotal = Weights.front().Type != Weight::Backedge;
588     Weights.front().Amount = 1;
589     return;
590   }
591
592   // Determine how much to shift right so that the total fits into 32-bits.
593   //
594   // If we shift at all, shift by 1 extra.  Otherwise, the lower limit of 1
595   // for each weight can cause a 32-bit overflow.
596   int Shift = 0;
597   if (DidOverflow)
598     Shift = 33;
599   else if (Total > UINT32_MAX)
600     Shift = 33 - countLeadingZeros(Total);
601
602   // Early exit if nothing needs to be scaled.
603   if (!Shift)
604     return;
605
606   // Recompute the total through accumulation (rather than shifting it) so that
607   // it's accurate after shifting.  ForwardTotal is dirty here anyway.
608   Total = 0;
609   ForwardTotal = 0;
610
611   // Sum the weights to each node and shift right if necessary.
612   for (Weight &W : Weights) {
613     // Scale down below UINT32_MAX.  Since Shift is larger than necessary, we
614     // can round here without concern about overflow.
615     assert(W.TargetNode.isValid());
616     W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
617     assert(W.Amount <= UINT32_MAX);
618
619     // Update the total.
620     Total += W.Amount;
621     if (W.Type == Weight::Backedge)
622       continue;
623
624     // Update the forward total.
625     ForwardTotal += W.Amount;
626   }
627   assert(Total <= UINT32_MAX);
628 }
629
630 void BlockFrequencyInfoImplBase::clear() {
631   *this = BlockFrequencyInfoImplBase();
632 }
633
634 /// \brief Clear all memory not needed downstream.
635 ///
636 /// Releases all memory not used downstream.  In particular, saves Freqs.
637 static void cleanup(BlockFrequencyInfoImplBase &BFI) {
638   std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
639   BFI.clear();
640   BFI.Freqs = std::move(SavedFreqs);
641 }
642
643 /// \brief Get a possibly packaged node.
644 ///
645 /// Get the node currently representing Node, which could be a containing
646 /// loop.
647 ///
648 /// This function should only be called when distributing mass.  As long as
649 /// there are no irreducilbe edges to Node, then it will have complexity O(1)
650 /// in this context.
651 ///
652 /// In general, the complexity is O(L), where L is the number of loop headers
653 /// Node has been packaged into.  Since this method is called in the context
654 /// of distributing mass, L will be the number of loop headers an early exit
655 /// edge jumps out of.
656 static BlockNode getPackagedNode(const BlockFrequencyInfoImplBase &BFI,
657                                  const BlockNode &Node) {
658   assert(Node.isValid());
659   if (!BFI.Working[Node.Index].IsPackaged)
660     return Node;
661   if (!BFI.Working[Node.Index].ContainingLoop.isValid())
662     return Node;
663   return getPackagedNode(BFI, BFI.Working[Node.Index].ContainingLoop);
664 }
665
666 /// \brief Get the appropriate mass for a possible pseudo-node loop package.
667 ///
668 /// Get appropriate mass for Node.  If Node is a loop-header (whose loop has
669 /// been packaged), returns the mass of its pseudo-node.  If it's a node inside
670 /// a packaged loop, it returns the loop's pseudo-node.
671 static BlockMass &getPackageMass(BlockFrequencyInfoImplBase &BFI,
672                                  const BlockNode &Node) {
673   assert(Node.isValid());
674   assert(!BFI.Working[Node.Index].IsPackaged);
675   if (!BFI.Working[Node.Index].IsAPackage)
676     return BFI.Working[Node.Index].Mass;
677
678   return BFI.getLoopPackage(Node).Mass;
679 }
680
681 void BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
682                                            const BlockNode &LoopHead,
683                                            const BlockNode &Pred,
684                                            const BlockNode &Succ,
685                                            uint64_t Weight) {
686   if (!Weight)
687     Weight = 1;
688
689 #ifndef NDEBUG
690   auto debugSuccessor = [&](const char *Type, const BlockNode &Resolved) {
691     dbgs() << "  =>"
692            << " [" << Type << "] weight = " << Weight;
693     if (Succ != LoopHead)
694       dbgs() << ", succ = " << getBlockName(Succ);
695     if (Resolved != Succ)
696       dbgs() << ", resolved = " << getBlockName(Resolved);
697     dbgs() << "\n";
698   };
699   (void)debugSuccessor;
700 #endif
701
702   if (Succ == LoopHead) {
703     DEBUG(debugSuccessor("backedge", Succ));
704     Dist.addBackedge(LoopHead, Weight);
705     return;
706   }
707   BlockNode Resolved = getPackagedNode(*this, Succ);
708   assert(Resolved != LoopHead);
709
710   if (Working[Resolved.Index].ContainingLoop != LoopHead) {
711     DEBUG(debugSuccessor("  exit  ", Resolved));
712     Dist.addExit(Resolved, Weight);
713     return;
714   }
715
716   if (!LoopHead.isValid() && Resolved < Pred) {
717     // Irreducible backedge.  Skip this edge in the distribution.
718     DEBUG(debugSuccessor("skipped ", Resolved));
719     return;
720   }
721
722   DEBUG(debugSuccessor(" local  ", Resolved));
723   Dist.addLocal(Resolved, Weight);
724 }
725
726 void BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
727     const BlockNode &LoopHead, const BlockNode &LocalLoopHead,
728     Distribution &Dist) {
729   PackagedLoopData &LoopPackage = getLoopPackage(LocalLoopHead);
730   const PackagedLoopData::ExitMap &Exits = LoopPackage.Exits;
731
732   // Copy the exit map into Dist.
733   for (const auto &I : Exits)
734     addToDist(Dist, LoopHead, LocalLoopHead, I.first, I.second.getMass());
735
736   // We don't need this map any more.  Clear it to prevent quadratic memory
737   // usage in deeply nested loops with irreducible control flow.
738   LoopPackage.Exits.clear();
739 }
740
741 /// \brief Get the maximum allowed loop scale.
742 ///
743 /// Gives the maximum number of estimated iterations allowed for a loop.
744 /// Downstream users have trouble with very large numbers (even within
745 /// 64-bits).  Perhaps they can be changed to use PositiveFloat.
746 ///
747 /// TODO: change downstream users so that this can be increased or removed.
748 static Float getMaxLoopScale() { return Float(1, 12); }
749
750 /// \brief Compute the loop scale for a loop.
751 void BlockFrequencyInfoImplBase::computeLoopScale(const BlockNode &LoopHead) {
752   // Compute loop scale.
753   DEBUG(dbgs() << "compute-loop-scale: " << getBlockName(LoopHead) << "\n");
754
755   // LoopScale == 1 / ExitMass
756   // ExitMass == HeadMass - BackedgeMass
757   PackagedLoopData &LoopPackage = getLoopPackage(LoopHead);
758   BlockMass ExitMass = BlockMass::getFull() - LoopPackage.BackedgeMass;
759
760   // Block scale stores the inverse of the scale.
761   LoopPackage.Scale = ExitMass.toFloat().inverse();
762
763   DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
764                << " - " << LoopPackage.BackedgeMass << ")\n"
765                << " - scale = " << LoopPackage.Scale << "\n");
766
767   if (LoopPackage.Scale > getMaxLoopScale()) {
768     LoopPackage.Scale = getMaxLoopScale();
769     DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
770   }
771 }
772
773 /// \brief Package up a loop.
774 void BlockFrequencyInfoImplBase::packageLoop(const BlockNode &LoopHead) {
775   DEBUG(dbgs() << "packaging-loop: " << getBlockName(LoopHead) << "\n");
776   Working[LoopHead.Index].IsAPackage = true;
777   for (const BlockNode &M : getLoopPackage(LoopHead).Members) {
778     DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
779     Working[M.Index].IsPackaged = true;
780   }
781 }
782
783 void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
784                                                 const BlockNode &LoopHead,
785                                                 Distribution &Dist) {
786   BlockMass Mass = getPackageMass(*this, Source);
787   DEBUG(dbgs() << "  => mass:  " << Mass
788                << " (    general     |    forward     )\n");
789
790   // Distribute mass to successors as laid out in Dist.
791   DitheringDistributer D(Dist, Mass);
792
793 #ifndef NDEBUG
794   auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
795                          const char *Desc) {
796     dbgs() << "  => assign " << M << " (" << D.RemMass << "|"
797            << D.RemForwardMass << ")";
798     if (Desc)
799       dbgs() << " [" << Desc << "]";
800     if (T.isValid())
801       dbgs() << " to " << getBlockName(T);
802     dbgs() << "\n";
803   };
804   (void)debugAssign;
805 #endif
806
807   PackagedLoopData *LoopPackage = 0;
808   if (LoopHead.isValid())
809     LoopPackage = &getLoopPackage(LoopHead);
810   for (const Weight &W : Dist.Weights) {
811     // Check for a local edge (forward and non-exit).
812     if (W.Type == Weight::Local) {
813       BlockMass Local = D.takeLocalMass(W.Amount);
814       getPackageMass(*this, W.TargetNode) += Local;
815       DEBUG(debugAssign(W.TargetNode, Local, nullptr));
816       continue;
817     }
818
819     // Backedges and exits only make sense if we're processing a loop.
820     assert(LoopPackage && "backedge or exit outside of loop");
821
822     // Check for a backedge.
823     if (W.Type == Weight::Backedge) {
824       BlockMass Back = D.takeBackedgeMass(W.Amount);
825       LoopPackage->BackedgeMass += Back;
826       DEBUG(debugAssign(BlockNode(), Back, "back"));
827       continue;
828     }
829
830     // This must be an exit.
831     assert(W.Type == Weight::Exit);
832     BlockMass Exit = D.takeExitMass(W.Amount);
833     LoopPackage->Exits.push_back(std::make_pair(W.TargetNode, Exit));
834     DEBUG(debugAssign(W.TargetNode, Exit, "exit"));
835   }
836 }
837
838 static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
839                                      const Float &Min, const Float &Max) {
840   // Scale the Factor to a size that creates integers.  Ideally, integers would
841   // be scaled so that Max == UINT64_MAX so that they can be best
842   // differentiated.  However, the register allocator currently deals poorly
843   // with large numbers.  Instead, push Min up a little from 1 to give some
844   // room to differentiate small, unequal numbers.
845   //
846   // TODO: fix issues downstream so that ScalingFactor can be Float(1,64)/Max.
847   Float ScalingFactor = Min.inverse();
848   if ((Max / Min).lg() < 60)
849     ScalingFactor <<= 3;
850
851   // Translate the floats to integers.
852   DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
853                << ", factor = " << ScalingFactor << "\n");
854   for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
855     Float Scaled = BFI.Freqs[Index].Floating * ScalingFactor;
856     BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
857     DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
858                  << BFI.Freqs[Index].Floating << ", scaled = " << Scaled
859                  << ", int = " << BFI.Freqs[Index].Integer << "\n");
860   }
861 }
862
863 static void scaleBlockData(BlockFrequencyInfoImplBase &BFI,
864                            const BlockNode &Node,
865                            const PackagedLoopData &Loop) {
866   Float F = Loop.Mass.toFloat() * Loop.Scale;
867
868   Float &Current = BFI.Freqs[Node.Index].Floating;
869   Float Updated = Current * F;
870
871   DEBUG(dbgs() << " - " << BFI.getBlockName(Node) << ": " << Current << " => "
872                << Updated << "\n");
873
874   Current = Updated;
875 }
876
877 /// \brief Unwrap a loop package.
878 ///
879 /// Visits all the members of a loop, adjusting their BlockData according to
880 /// the loop's pseudo-node.
881 static void unwrapLoopPackage(BlockFrequencyInfoImplBase &BFI,
882                               const BlockNode &Head) {
883   assert(Head.isValid());
884
885   PackagedLoopData &LoopPackage = BFI.getLoopPackage(Head);
886   DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getBlockName(Head)
887                << ": mass = " << LoopPackage.Mass
888                << ", scale = " << LoopPackage.Scale << "\n");
889   scaleBlockData(BFI, Head, LoopPackage);
890
891   // Propagate the head scale through the loop.  Since members are visited in
892   // RPO, the head scale will be updated by the loop scale first, and then the
893   // final head scale will be used for updated the rest of the members.
894   for (const BlockNode &M : LoopPackage.Members) {
895     const FrequencyData &HeadData = BFI.Freqs[Head.Index];
896     FrequencyData &Freqs = BFI.Freqs[M.Index];
897     Float NewFreq = Freqs.Floating * HeadData.Floating;
898     DEBUG(dbgs() << " - " << BFI.getBlockName(M) << ": " << Freqs.Floating
899                  << " => " << NewFreq << "\n");
900     Freqs.Floating = NewFreq;
901   }
902 }
903
904 void BlockFrequencyInfoImplBase::finalizeMetrics() {
905   // Set initial frequencies from loop-local masses.
906   for (size_t Index = 0; Index < Working.size(); ++Index)
907     Freqs[Index].Floating = Working[Index].Mass.toFloat();
908
909   // Unwrap loop packages in reverse post-order, tracking min and max
910   // frequencies.
911   auto Min = Float::getLargest();
912   auto Max = Float::getZero();
913   for (size_t Index = 0; Index < Working.size(); ++Index) {
914     if (Working[Index].isLoopHeader())
915       unwrapLoopPackage(*this, BlockNode(Index));
916
917     // Update max scale.
918     Min = std::min(Min, Freqs[Index].Floating);
919     Max = std::max(Max, Freqs[Index].Floating);
920   }
921
922   // Convert to integers.
923   convertFloatingToInteger(*this, Min, Max);
924
925   // Clean up data structures.
926   cleanup(*this);
927
928   // Print out the final stats.
929   DEBUG(dump());
930 }
931
932 BlockFrequency
933 BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
934   if (!Node.isValid())
935     return 0;
936   return Freqs[Node.Index].Integer;
937 }
938 Float
939 BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
940   if (!Node.isValid())
941     return Float::getZero();
942   return Freqs[Node.Index].Floating;
943 }
944
945 std::string
946 BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
947   return std::string();
948 }
949
950 raw_ostream &
951 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
952                                            const BlockNode &Node) const {
953   return OS << getFloatingBlockFreq(Node);
954 }
955
956 raw_ostream &
957 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
958                                            const BlockFrequency &Freq) const {
959   Float Block(Freq.getFrequency(), 0);
960   Float Entry(getEntryFreq(), 0);
961
962   return OS << Block / Entry;
963 }