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