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