1 //===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Loops should be simplified before this analysis.
12 //===----------------------------------------------------------------------===//
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"
21 using namespace llvm::bfi_detail;
23 #define DEBUG_TYPE "block-freq"
25 //===----------------------------------------------------------------------===//
27 // ScaledNumber implementation.
29 //===----------------------------------------------------------------------===//
30 static void appendDigit(std::string &Str, unsigned D) {
35 static void appendNumber(std::string &Str, uint64_t N) {
37 appendDigit(Str, N % 10);
42 static bool doesRoundUp(char Digit) {
55 static std::string toStringAPFloat(uint64_t D, int E, unsigned Precision) {
56 assert(E >= ScaledNumbers::MinScale);
57 assert(E <= ScaledNumbers::MaxScale);
59 // Find a new E, but don't let it increase past MaxScale.
60 int LeadingZeros = ScaledNumberBase::countLeadingZeros64(D);
61 int NewE = std::min(ScaledNumbers::MaxScale, E + 63 - LeadingZeros);
62 int Shift = 63 - (NewE - E);
63 assert(Shift <= LeadingZeros);
64 assert(Shift == LeadingZeros || NewE == ScaledNumbers::MaxScale);
68 // Check for a denormal.
69 unsigned AdjustedE = E + 16383;
71 assert(E == ScaledNumbers::MaxScale);
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());
83 static std::string stripTrailingZeros(const std::string &Float) {
84 size_t NonZero = Float.find_last_not_of('0');
85 assert(NonZero != std::string::npos && "no . in floating point string");
87 if (Float[NonZero] == '.')
90 return Float.substr(0, NonZero + 1);
93 std::string ScaledNumberBase::toString(uint64_t D, int16_t E, int Width,
98 // Canonicalize exponent and digits.
106 if (int Shift = std::min(int16_t(countLeadingZeros64(D)), E)) {
113 } else if (E > -64) {
115 Below0 = D << (64 + E);
116 } else if (E > -120) {
117 Below0 = D >> (-E - 64);
118 Extra = D << (128 + E);
119 ExtraShift = -64 - E;
122 // Fall back on APFloat for very small and very large numbers.
123 if (!Above0 && !Below0)
124 return toStringAPFloat(D, E, Precision);
126 // Append the digits before the decimal.
128 size_t DigitsOut = 0;
130 appendNumber(Str, Above0);
131 DigitsOut = Str.size();
134 std::reverse(Str.begin(), Str.end());
136 // Return early if there's nothing after the decimal.
140 // Append the decimal and beyond.
142 uint64_t Error = UINT64_C(1) << (64 - Width);
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);
149 size_t AfterDot = Str.size();
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')
166 } while (Error && (Below0 << 4 | Extra >> 60) >= Error / 2 &&
167 (!Precision || DigitsOut <= Precision || SinceDot < 2));
169 // Return early for maximum precision.
170 if (!Precision || DigitsOut <= Precision)
171 return stripTrailingZeros(Str);
173 // Find where to truncate.
175 std::max(Str.size() - (DigitsOut - Precision), AfterDot + 1);
177 // Check if there's anything to truncate.
178 if (Truncate >= Str.size())
179 return stripTrailingZeros(Str);
181 bool Carry = doesRoundUp(Str[Truncate]);
183 return stripTrailingZeros(Str.substr(0, Truncate));
185 // Round with the first truncated digit.
186 for (std::string::reverse_iterator I(Str.begin() + Truncate), E = Str.rend();
200 // Add "1" in front if we still need to carry.
201 return stripTrailingZeros(std::string(Carry, '1') + Str.substr(0, Truncate));
204 raw_ostream &ScaledNumberBase::print(raw_ostream &OS, uint64_t D, int16_t E,
205 int Width, unsigned Precision) {
206 return OS << toString(D, E, Width, Precision);
209 void ScaledNumberBase::dump(uint64_t D, int16_t E, int Width) {
210 print(dbgs(), D, E, Width, 0) << "[" << Width << ":" << D << "*2^" << E
214 //===----------------------------------------------------------------------===//
216 // BlockMass implementation.
218 //===----------------------------------------------------------------------===//
219 ScaledNumber<uint64_t> BlockMass::toFloat() const {
221 return ScaledNumber<uint64_t>(1, 0);
222 return ScaledNumber<uint64_t>(getMass() + 1, -64);
225 void BlockMass::dump() const { print(dbgs()); }
227 static char getHexDigit(int N) {
233 raw_ostream &BlockMass::print(raw_ostream &OS) const {
234 for (int Digits = 0; Digits < 16; ++Digits)
235 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
239 //===----------------------------------------------------------------------===//
241 // BlockFrequencyInfoImpl implementation.
243 //===----------------------------------------------------------------------===//
246 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
247 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
248 typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
249 typedef BlockFrequencyInfoImplBase::Float Float;
250 typedef BlockFrequencyInfoImplBase::LoopData LoopData;
251 typedef BlockFrequencyInfoImplBase::Weight Weight;
252 typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
254 /// \brief Dithering mass distributer.
256 /// This class splits up a single mass into portions by weight, dithering to
257 /// spread out error. No mass is lost. The dithering precision depends on the
258 /// precision of the product of \a BlockMass and \a BranchProbability.
260 /// The distribution algorithm follows.
262 /// 1. Initialize by saving the sum of the weights in \a RemWeight and the
263 /// mass to distribute in \a RemMass.
265 /// 2. For each portion:
267 /// 1. Construct a branch probability, P, as the portion's weight divided
268 /// by the current value of \a RemWeight.
269 /// 2. Calculate the portion's mass as \a RemMass times P.
270 /// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
271 /// the current portion's weight and mass.
272 struct DitheringDistributer {
276 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
278 BlockMass takeMass(uint32_t Weight);
282 DitheringDistributer::DitheringDistributer(Distribution &Dist,
283 const BlockMass &Mass) {
285 RemWeight = Dist.Total;
289 BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
290 assert(Weight && "invalid weight");
291 assert(Weight <= RemWeight);
292 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
294 // Decrement totals (dither).
300 void Distribution::add(const BlockNode &Node, uint64_t Amount,
301 Weight::DistType Type) {
302 assert(Amount && "invalid weight of 0");
303 uint64_t NewTotal = Total + Amount;
305 // Check for overflow. It should be impossible to overflow twice.
306 bool IsOverflow = NewTotal < Total;
307 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
308 DidOverflow |= IsOverflow;
318 Weights.push_back(W);
321 static void combineWeight(Weight &W, const Weight &OtherW) {
322 assert(OtherW.TargetNode.isValid());
327 assert(W.Type == OtherW.Type);
328 assert(W.TargetNode == OtherW.TargetNode);
329 assert(W.Amount < W.Amount + OtherW.Amount && "Unexpected overflow");
330 W.Amount += OtherW.Amount;
332 static void combineWeightsBySorting(WeightList &Weights) {
333 // Sort so edges to the same node are adjacent.
334 std::sort(Weights.begin(), Weights.end(),
336 const Weight &R) { return L.TargetNode < R.TargetNode; });
338 // Combine adjacent edges.
339 WeightList::iterator O = Weights.begin();
340 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
344 // Find the adjacent weights to the same node.
345 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
346 combineWeight(*O, *L);
349 // Erase extra entries.
350 Weights.erase(O, Weights.end());
353 static void combineWeightsByHashing(WeightList &Weights) {
354 // Collect weights into a DenseMap.
355 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
356 HashTable Combined(NextPowerOf2(2 * Weights.size()));
357 for (const Weight &W : Weights)
358 combineWeight(Combined[W.TargetNode.Index], W);
360 // Check whether anything changed.
361 if (Weights.size() == Combined.size())
364 // Fill in the new weights.
366 Weights.reserve(Combined.size());
367 for (const auto &I : Combined)
368 Weights.push_back(I.second);
370 static void combineWeights(WeightList &Weights) {
371 // Use a hash table for many successors to keep this linear.
372 if (Weights.size() > 128) {
373 combineWeightsByHashing(Weights);
377 combineWeightsBySorting(Weights);
379 static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
384 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
386 void Distribution::normalize() {
387 // Early exit for termination nodes.
391 // Only bother if there are multiple successors.
392 if (Weights.size() > 1)
393 combineWeights(Weights);
395 // Early exit when combined into a single successor.
396 if (Weights.size() == 1) {
398 Weights.front().Amount = 1;
402 // Determine how much to shift right so that the total fits into 32-bits.
404 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
405 // for each weight can cause a 32-bit overflow.
409 else if (Total > UINT32_MAX)
410 Shift = 33 - countLeadingZeros(Total);
412 // Early exit if nothing needs to be scaled.
416 // Recompute the total through accumulation (rather than shifting it) so that
417 // it's accurate after shifting.
420 // Sum the weights to each node and shift right if necessary.
421 for (Weight &W : Weights) {
422 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
423 // can round here without concern about overflow.
424 assert(W.TargetNode.isValid());
425 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
426 assert(W.Amount <= UINT32_MAX);
431 assert(Total <= UINT32_MAX);
434 void BlockFrequencyInfoImplBase::clear() {
435 // Swap with a default-constructed std::vector, since std::vector<>::clear()
436 // does not actually clear heap storage.
437 std::vector<FrequencyData>().swap(Freqs);
438 std::vector<WorkingData>().swap(Working);
442 /// \brief Clear all memory not needed downstream.
444 /// Releases all memory not used downstream. In particular, saves Freqs.
445 static void cleanup(BlockFrequencyInfoImplBase &BFI) {
446 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
448 BFI.Freqs = std::move(SavedFreqs);
451 bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
452 const LoopData *OuterLoop,
453 const BlockNode &Pred,
454 const BlockNode &Succ,
459 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
460 return OuterLoop && OuterLoop->isHeader(Node);
463 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
466 auto debugSuccessor = [&](const char *Type) {
468 << " [" << Type << "] weight = " << Weight;
469 if (!isLoopHeader(Resolved))
470 dbgs() << ", succ = " << getBlockName(Succ);
471 if (Resolved != Succ)
472 dbgs() << ", resolved = " << getBlockName(Resolved);
475 (void)debugSuccessor;
478 if (isLoopHeader(Resolved)) {
479 DEBUG(debugSuccessor("backedge"));
480 Dist.addBackedge(OuterLoop->getHeader(), Weight);
484 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
485 DEBUG(debugSuccessor(" exit "));
486 Dist.addExit(Resolved, Weight);
490 if (Resolved < Pred) {
491 if (!isLoopHeader(Pred)) {
492 // If OuterLoop is an irreducible loop, we can't actually handle this.
493 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
494 "unhandled irreducible control flow");
496 // Irreducible backedge. Abort.
497 DEBUG(debugSuccessor("abort!!!"));
501 // If "Pred" is a loop header, then this isn't really a backedge; rather,
502 // OuterLoop must be irreducible. These false backedges can come only from
503 // secondary loop headers.
504 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
505 "unhandled irreducible control flow");
508 DEBUG(debugSuccessor(" local "));
509 Dist.addLocal(Resolved, Weight);
513 bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
514 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
515 // Copy the exit map into Dist.
516 for (const auto &I : Loop.Exits)
517 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
519 // Irreducible backedge.
525 /// \brief Get the maximum allowed loop scale.
527 /// Gives the maximum number of estimated iterations allowed for a loop. Very
528 /// large numbers cause problems downstream (even within 64-bits).
529 static Float getMaxLoopScale() { return Float(1, 12); }
531 /// \brief Compute the loop scale for a loop.
532 void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
533 // Compute loop scale.
534 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
536 // LoopScale == 1 / ExitMass
537 // ExitMass == HeadMass - BackedgeMass
538 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
540 // Block scale stores the inverse of the scale.
541 Loop.Scale = ExitMass.toFloat().inverse();
543 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
544 << " - " << Loop.BackedgeMass << ")\n"
545 << " - scale = " << Loop.Scale << "\n");
547 if (Loop.Scale > getMaxLoopScale()) {
548 Loop.Scale = getMaxLoopScale();
549 DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
553 /// \brief Package up a loop.
554 void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
555 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
557 // Clear the subloop exits to prevent quadratic memory usage.
558 for (const BlockNode &M : Loop.Nodes) {
559 if (auto *Loop = Working[M.Index].getPackagedLoop())
561 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
563 Loop.IsPackaged = true;
566 void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
568 Distribution &Dist) {
569 BlockMass Mass = Working[Source.Index].getMass();
570 DEBUG(dbgs() << " => mass: " << Mass << "\n");
572 // Distribute mass to successors as laid out in Dist.
573 DitheringDistributer D(Dist, Mass);
576 auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
578 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
580 dbgs() << " [" << Desc << "]";
582 dbgs() << " to " << getBlockName(T);
588 for (const Weight &W : Dist.Weights) {
589 // Check for a local edge (non-backedge and non-exit).
590 BlockMass Taken = D.takeMass(W.Amount);
591 if (W.Type == Weight::Local) {
592 Working[W.TargetNode.Index].getMass() += Taken;
593 DEBUG(debugAssign(W.TargetNode, Taken, nullptr));
597 // Backedges and exits only make sense if we're processing a loop.
598 assert(OuterLoop && "backedge or exit outside of loop");
600 // Check for a backedge.
601 if (W.Type == Weight::Backedge) {
602 OuterLoop->BackedgeMass += Taken;
603 DEBUG(debugAssign(BlockNode(), Taken, "back"));
607 // This must be an exit.
608 assert(W.Type == Weight::Exit);
609 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
610 DEBUG(debugAssign(W.TargetNode, Taken, "exit"));
614 static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
615 const Float &Min, const Float &Max) {
616 // Scale the Factor to a size that creates integers. Ideally, integers would
617 // be scaled so that Max == UINT64_MAX so that they can be best
618 // differentiated. However, the register allocator currently deals poorly
619 // with large numbers. Instead, push Min up a little from 1 to give some
620 // room to differentiate small, unequal numbers.
622 // TODO: fix issues downstream so that ScalingFactor can be Float(1,64)/Max.
623 Float ScalingFactor = Min.inverse();
624 if ((Max / Min).lg() < 60)
627 // Translate the floats to integers.
628 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
629 << ", factor = " << ScalingFactor << "\n");
630 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
631 Float Scaled = BFI.Freqs[Index].Floating * ScalingFactor;
632 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
633 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
634 << BFI.Freqs[Index].Floating << ", scaled = " << Scaled
635 << ", int = " << BFI.Freqs[Index].Integer << "\n");
639 /// \brief Unwrap a loop package.
641 /// Visits all the members of a loop, adjusting their BlockData according to
642 /// the loop's pseudo-node.
643 static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
644 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
645 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
647 Loop.Scale *= Loop.Mass.toFloat();
648 Loop.IsPackaged = false;
649 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
651 // Propagate the head scale through the loop. Since members are visited in
652 // RPO, the head scale will be updated by the loop scale first, and then the
653 // final head scale will be used for updated the rest of the members.
654 for (const BlockNode &N : Loop.Nodes) {
655 const auto &Working = BFI.Working[N.Index];
656 Float &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
657 : BFI.Freqs[N.Index].Floating;
658 Float New = Loop.Scale * F;
659 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
665 void BlockFrequencyInfoImplBase::unwrapLoops() {
666 // Set initial frequencies from loop-local masses.
667 for (size_t Index = 0; Index < Working.size(); ++Index)
668 Freqs[Index].Floating = Working[Index].Mass.toFloat();
670 for (LoopData &Loop : Loops)
671 unwrapLoop(*this, Loop);
674 void BlockFrequencyInfoImplBase::finalizeMetrics() {
675 // Unwrap loop packages in reverse post-order, tracking min and max
677 auto Min = Float::getLargest();
678 auto Max = Float::getZero();
679 for (size_t Index = 0; Index < Working.size(); ++Index) {
680 // Update min/max scale.
681 Min = std::min(Min, Freqs[Index].Floating);
682 Max = std::max(Max, Freqs[Index].Floating);
685 // Convert to integers.
686 convertFloatingToInteger(*this, Min, Max);
688 // Clean up data structures.
691 // Print out the final stats.
696 BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
699 return Freqs[Node.Index].Integer;
702 BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
704 return Float::getZero();
705 return Freqs[Node.Index].Floating;
709 BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
710 return std::string();
713 BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
714 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
718 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
719 const BlockNode &Node) const {
720 return OS << getFloatingBlockFreq(Node);
724 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
725 const BlockFrequency &Freq) const {
726 Float Block(Freq.getFrequency(), 0);
727 Float Entry(getEntryFreq(), 0);
729 return OS << Block / Entry;
732 void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
733 Start = OuterLoop.getHeader();
734 Nodes.reserve(OuterLoop.Nodes.size());
735 for (auto N : OuterLoop.Nodes)
739 void IrreducibleGraph::addNodesInFunction() {
741 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
742 if (!BFI.Working[Index].isPackaged())
746 void IrreducibleGraph::indexNodes() {
747 for (auto &I : Nodes)
748 Lookup[I.Node.Index] = &I;
750 void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
751 const BFIBase::LoopData *OuterLoop) {
752 if (OuterLoop && OuterLoop->isHeader(Succ))
754 auto L = Lookup.find(Succ.Index);
755 if (L == Lookup.end())
757 IrrNode &SuccIrr = *L->second;
758 Irr.Edges.push_back(&SuccIrr);
759 SuccIrr.Edges.push_front(&Irr);
764 template <> struct GraphTraits<IrreducibleGraph> {
765 typedef bfi_detail::IrreducibleGraph GraphT;
767 typedef const GraphT::IrrNode NodeType;
768 typedef GraphT::IrrNode::iterator ChildIteratorType;
770 static const NodeType *getEntryNode(const GraphT &G) {
773 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
774 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
778 /// \brief Find extra irreducible headers.
780 /// Find entry blocks and other blocks with backedges, which exist when \c G
781 /// contains irreducible sub-SCCs.
782 static void findIrreducibleHeaders(
783 const BlockFrequencyInfoImplBase &BFI,
784 const IrreducibleGraph &G,
785 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
786 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
787 // Map from nodes in the SCC to whether it's an entry block.
788 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
790 // InSCC also acts the set of nodes in the graph. Seed it.
791 for (const auto *I : SCC)
794 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
795 auto &Irr = *I->first;
796 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
800 // This is an entry block.
802 Headers.push_back(Irr.Node);
803 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
807 assert(Headers.size() >= 2 && "Should be irreducible");
808 if (Headers.size() == InSCC.size()) {
809 // Every block is a header.
810 std::sort(Headers.begin(), Headers.end());
814 // Look for extra headers from irreducible sub-SCCs.
815 for (const auto &I : InSCC) {
816 // Entry blocks are already headers.
820 auto &Irr = *I.first;
821 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
822 // Skip forward edges.
823 if (P->Node < Irr.Node)
826 // Skip predecessors from entry blocks. These can have inverted
831 // Store the extra header.
832 Headers.push_back(Irr.Node);
833 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
836 if (Headers.back() == Irr.Node)
837 // Added this as a header.
840 // This is not a header.
841 Others.push_back(Irr.Node);
842 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
844 std::sort(Headers.begin(), Headers.end());
845 std::sort(Others.begin(), Others.end());
848 static void createIrreducibleLoop(
849 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
850 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
851 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
852 // Translate the SCC into RPO.
853 DEBUG(dbgs() << " - found-scc\n");
855 LoopData::NodeList Headers;
856 LoopData::NodeList Others;
857 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
859 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
860 Headers.end(), Others.begin(), Others.end());
862 // Update loop hierarchy.
863 for (const auto &N : Loop->Nodes)
864 if (BFI.Working[N.Index].isLoopHeader())
865 BFI.Working[N.Index].Loop->Parent = &*Loop;
867 BFI.Working[N.Index].Loop = &*Loop;
870 iterator_range<std::list<LoopData>::iterator>
871 BlockFrequencyInfoImplBase::analyzeIrreducible(
872 const IrreducibleGraph &G, LoopData *OuterLoop,
873 std::list<LoopData>::iterator Insert) {
874 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
875 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
877 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
881 // Translate the SCC into RPO.
882 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
886 return make_range(std::next(Prev), Insert);
887 return make_range(Loops.begin(), Insert);
891 BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
892 OuterLoop.Exits.clear();
893 OuterLoop.BackedgeMass = BlockMass::getEmpty();
894 auto O = OuterLoop.Nodes.begin() + 1;
895 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
896 if (!Working[I->Index].isPackaged())
898 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());