LLVM 24.0.0git
BlockFrequencyInfoImpl.cpp
Go to the documentation of this file.
1//===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Loops should be simplified before this analysis.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/MapVector.h"
18#include "llvm/Config/llvm-config.h"
19#include "llvm/IR/Function.h"
23#include "llvm/Support/Debug.h"
27#include <algorithm>
28#include <cassert>
29#include <cstddef>
30#include <cstdint>
31#include <iterator>
32#include <list>
33#include <numeric>
34#include <optional>
35#include <utility>
36#include <vector>
37
38using namespace llvm;
39using namespace llvm::bfi_detail;
40
41#define DEBUG_TYPE "block-freq"
42
43namespace llvm {
45 "check-bfi-unknown-block-queries",
46 cl::init(false), cl::Hidden,
47 cl::desc("Check if block frequency is queried for an unknown block "
48 "for debugging missed BFI updates"));
49
51 "use-iterative-bfi-inference", cl::Hidden,
52 cl::desc("Apply an iterative post-processing to infer correct BFI counts"));
53
55 "iterative-bfi-max-iterations-per-block", cl::init(1000), cl::Hidden,
56 cl::desc("Iterative inference: maximum number of update iterations "
57 "per block"));
58
60 "iterative-bfi-precision", cl::init(1e-12), cl::Hidden,
61 cl::desc("Iterative inference: delta convergence precision; smaller values "
62 "typically lead to better results at the cost of worsen runtime"));
63} // namespace llvm
64
66 if (isFull())
67 return ScaledNumber<uint64_t>(1, 0);
68 return ScaledNumber<uint64_t>(getMass() + 1, -64);
69}
70
71#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
73#endif
74
75static char getHexDigit(int N) {
76 assert(N < 16);
77 if (N < 10)
78 return '0' + N;
79 return 'a' + N - 10;
80}
81
83 for (int Digits = 0; Digits < 16; ++Digits)
84 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
85 return OS;
86}
87
88namespace {
89
97
98/// Dithering mass distributer.
99///
100/// This class splits up a single mass into portions by weight, dithering to
101/// spread out error. No mass is lost. The dithering precision depends on the
102/// precision of the product of \a BlockMass and \a BranchProbability.
103///
104/// The distribution algorithm follows.
105///
106/// 1. Initialize by saving the sum of the weights in \a RemWeight and the
107/// mass to distribute in \a RemMass.
108///
109/// 2. For each portion:
110///
111/// 1. Construct a branch probability, P, as the portion's weight divided
112/// by the current value of \a RemWeight.
113/// 2. Calculate the portion's mass as \a RemMass times P.
114/// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
115/// the current portion's weight and mass.
116struct DitheringDistributer {
117 uint32_t RemWeight;
118 BlockMass RemMass;
119
120 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
121
122 BlockMass takeMass(uint32_t Weight);
123};
124
125} // end anonymous namespace
126
127DitheringDistributer::DitheringDistributer(Distribution &Dist,
128 const BlockMass &Mass) {
129 Dist.normalize();
130 RemWeight = Dist.Total;
131 RemMass = Mass;
132}
133
134BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
135 assert(Weight && "invalid weight");
136 assert(Weight <= RemWeight);
137 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
138
139 // Decrement totals (dither).
140 RemWeight -= Weight;
141 RemMass -= Mass;
142 return Mass;
143}
144
145void Distribution::add(const BlockNode &Node, uint64_t Amount,
146 Weight::DistType Type) {
147 assert(Amount && "invalid weight of 0");
148 uint64_t NewTotal = Total + Amount;
149
150 // Check for overflow. It should be impossible to overflow twice.
151 bool IsOverflow = NewTotal < Total;
152 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
153 DidOverflow |= IsOverflow;
154
155 // Update the total.
156 Total = NewTotal;
157
158 // Save the weight.
159 Weights.push_back(Weight(Type, Node, Amount));
160}
161
162static void combineWeight(Weight &W, const Weight &OtherW) {
163 assert(OtherW.TargetNode.isValid());
164 if (!W.Amount) {
165 W = OtherW;
166 return;
167 }
168 assert(W.Type == OtherW.Type);
169 assert(W.TargetNode == OtherW.TargetNode);
170 assert(OtherW.Amount && "Expected non-zero weight");
171 if (W.Amount > W.Amount + OtherW.Amount)
172 // Saturate on overflow.
173 W.Amount = UINT64_MAX;
174 else
175 W.Amount += OtherW.Amount;
176}
177
178static void combineWeightsBySorting(WeightList &Weights) {
179 // Sort so edges to the same node are adjacent.
180 llvm::sort(Weights, [](const Weight &L, const Weight &R) {
181 return L.TargetNode < R.TargetNode;
182 });
183
184 // Combine adjacent edges.
185 WeightList::iterator O = Weights.begin();
186 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
187 ++O, (I = L)) {
188 *O = *I;
189
190 // Find the adjacent weights to the same node.
191 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
192 combineWeight(*O, *L);
193 }
194
195 // Erase extra entries.
196 Weights.erase(O, Weights.end());
197}
198
199static void combineWeightsByHashing(WeightList &Weights) {
201 Combined.reserve(Weights.size());
202 for (const Weight &W : Weights)
203 combineWeight(Combined[W.TargetNode.Index], W);
204
205 // Check whether anything changed.
206 if (Weights.size() == Combined.size())
207 return;
208
209 // Fill in the new weights.
210 Weights.clear();
211 for (const auto &I : Combined)
212 Weights.push_back(I.second);
213}
214
215static void combineWeights(WeightList &Weights) {
216 // Use a hash table for many successors to keep this linear.
217 if (Weights.size() > 128) {
219 return;
220 }
221
223}
224
226 assert(Shift >= 0);
227 assert(Shift < 64);
228 if (!Shift)
229 return N;
230 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
231}
232
234 // Early exit for termination nodes.
235 if (Weights.empty())
236 return;
237
238 // Only bother if there are multiple successors.
239 if (Weights.size() > 1)
241
242 // Early exit when combined into a single successor.
243 if (Weights.size() == 1) {
244 Total = 1;
245 Weights.front().Amount = 1;
246 return;
247 }
248
249 // Determine how much to shift right so that the total fits into 32-bits.
250 //
251 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
252 // for each weight can cause a 32-bit overflow.
253 int Shift = 0;
254 if (DidOverflow)
255 Shift = 33;
256 else if (Total > UINT32_MAX)
257 Shift = 33 - llvm::countl_zero(Total);
258
259 // Early exit if nothing needs to be scaled.
260 if (!Shift) {
261 // If we didn't overflow then combineWeights() shouldn't have changed the
262 // sum of the weights, but let's double-check.
263 assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
264 [](uint64_t Sum, const Weight &W) {
265 return Sum + W.Amount;
266 }) &&
267 "Expected total to be correct");
268 return;
269 }
270
271 // Recompute the total through accumulation (rather than shifting it) so that
272 // it's accurate after shifting and any changes combineWeights() made above.
273 Total = 0;
274
275 // Sum the weights to each node and shift right if necessary.
276 for (Weight &W : Weights) {
277 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
278 // can round here without concern about overflow.
279 assert(W.TargetNode.isValid());
280 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
281 assert(W.Amount <= UINT32_MAX);
282
283 // Update the total.
284 Total += W.Amount;
285 }
286 assert(Total <= UINT32_MAX);
287}
288
290 // Swap with a default-constructed std::vector, since std::vector<>::clear()
291 // does not actually clear heap storage.
292 std::vector<FrequencyData>().swap(Freqs);
293 IsIrrLoopHeader.clear();
294 std::vector<WorkingData>().swap(Working);
295 Loops.clear();
297}
298
299/// Clear all memory not needed downstream.
300///
301/// Releases all memory not used downstream. In particular, saves Freqs.
303 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
304 SparseBitVector<> SavedIsIrrLoopHeader(std::move(BFI.IsIrrLoopHeader));
305 BFI.clear();
306 BFI.Freqs = std::move(SavedFreqs);
307 BFI.IsIrrLoopHeader = std::move(SavedIsIrrLoopHeader);
308}
309
311 const LoopData *OuterLoop,
312 const BlockNode &Pred,
313 const BlockNode &Succ,
314 uint64_t Weight) {
315 if (!Weight)
316 Weight = 1;
317
318 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
319 return OuterLoop && OuterLoop->isHeader(Node);
320 };
321
322 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
323
324#ifndef NDEBUG
325 auto debugSuccessor = [&](const char *Type) {
326 dbgs() << " =>"
327 << " [" << Type << "] weight = " << Weight;
328 if (!isLoopHeader(Resolved))
329 dbgs() << ", succ = " << getBlockName(Succ);
330 dbgs() << ", pred = " << getBlockName(Pred);
331 if (Resolved != Succ)
332 dbgs() << ", resolved = " << getBlockName(Resolved);
333 dbgs() << "\n";
334 };
335 (void)debugSuccessor;
336#endif
337
338 if (isLoopHeader(Resolved)) {
339 LLVM_DEBUG(debugSuccessor("backedge"));
340 Dist.addBackedge(Resolved, Weight);
341 return;
342 }
343
344 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
345 LLVM_DEBUG(debugSuccessor(" exit "));
346 Dist.addExit(Resolved, Weight);
347 return;
348 }
349
350 // Every irreducible SCC is packaged before mass distribution and an
351 // irreducible package is solved rather than swept, so the only retreating
352 // edge left is the one to OuterLoop's header, handled above.
353 assert(Resolved >= Pred && "unhandled irreducible control flow");
354
355 LLVM_DEBUG(debugSuccessor(" local "));
356 Dist.addLocal(Resolved, Weight);
357}
358
360 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
361 // Copy the exit map into Dist.
362 for (const auto &I : Loop.Exits)
363 addToDist(Dist, OuterLoop, Loop.getHeader(), I.first, I.second.getMass());
364}
365
366/// Compute the loop scale for a loop.
368 // Compute loop scale.
369 LLVM_DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
370
371 // Infinite loops need special handling. If we give the back edge an infinite
372 // mass, they may saturate all the other scales in the function down to 1,
373 // making all the other region temperatures look exactly the same. Choose an
374 // arbitrary scale to avoid these issues.
375 //
376 // FIXME: An alternate way would be to select a symbolic scale which is later
377 // replaced to be the maximum of all computed scales plus 1. This would
378 // appropriately describe the loop as having a large scale, without skewing
379 // the final frequency computation.
380 const Scaled64 InfiniteLoopScale(1, 12);
381
382 // LoopScale == 1 / ExitMass
383 // ExitMass == HeadMass - BackedgeMass
384 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
385
386 // Block scale stores the inverse of the scale. If this is an infinite loop,
387 // its exit mass will be zero. In this case, use an arbitrary scale for the
388 // loop scale.
389 Loop.Scale =
390 ExitMass.isEmpty() ? InfiniteLoopScale : ExitMass.toScaled().inverse();
391
392 LLVM_DEBUG(dbgs() << " - exit-mass = " << ExitMass << " ("
393 << BlockMass::getFull() << " - " << Loop.BackedgeMass
394 << ")\n"
395 << " - scale = " << Loop.Scale << "\n");
396}
397
398/// Package up a loop.
400 LLVM_DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
401
402 // Clear the subloop exits to prevent quadratic memory usage.
403 for (const BlockNode &M : Loop.Nodes) {
404 if (auto *Loop = Working[M.Index].getPackagedLoop())
405 Loop->Exits.clear();
406 LLVM_DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
407 }
408 Loop.IsPackaged = true;
409}
410
411#ifndef NDEBUG
413 const DitheringDistributer &D, const BlockNode &T,
414 const BlockMass &M, const char *Desc) {
415 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
416 if (Desc)
417 dbgs() << " [" << Desc << "]";
418 if (T.isValid())
419 dbgs() << " to " << BFI.getBlockName(T);
420 dbgs() << "\n";
421}
422#endif
423
425 LoopData *OuterLoop,
426 Distribution &Dist) {
427 BlockMass Mass = Working[Source.Index].getMass();
428 LLVM_DEBUG(dbgs() << " => mass: " << Mass << "\n");
429
430 // Distribute mass to successors as laid out in Dist.
431 DitheringDistributer D(Dist, Mass);
432
433 for (const Weight &W : Dist.Weights) {
434 // Check for a local edge (non-backedge and non-exit).
435 BlockMass Taken = D.takeMass(W.Amount);
436 if (W.Type == Weight::Local) {
437 Working[W.TargetNode.Index].getMass() += Taken;
438 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
439 continue;
440 }
441
442 // Backedges and exits only make sense if we're processing a loop.
443 assert(OuterLoop && "backedge or exit outside of loop");
444
445 // Check for a backedge.
446 if (W.Type == Weight::Backedge) {
447 OuterLoop->BackedgeMass += Taken;
448 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "back"));
449 continue;
450 }
451
452 // This must be an exit.
453 assert(W.Type == Weight::Exit);
454 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
455 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "exit"));
456 }
457}
458
460 auto Max = Scaled64::getZero();
461 for (const FrequencyData &F : BFI.Freqs)
462 Max = std::max(Max, F.Scaled);
463
464 // Scale the Factor to a size that creates integers. If possible scale
465 // integers so that Max == UINT64_MAX so that they can be best differentiated.
466 // It is possible that the range between min and max cannot be accurately
467 // represented in a 64bit integer without either loosing precision for small
468 // values (so small unequal numbers all map to 1) or saturaturing big numbers
469 // loosing precision for big numbers (so unequal big numbers may map to
470 // UINT64_MAX). We choose to loose precision for small numbers.
471 const unsigned MaxBits = sizeof(Scaled64::DigitsType) * CHAR_BIT;
472 // Users often add up multiple BlockFrequency values or multiply them with
473 // things like instruction costs. Leave some room to avoid saturating
474 // operations reaching UIN64_MAX too early.
475 const unsigned Slack = 10;
476 Scaled64 ScalingFactor = Scaled64(1, MaxBits - Slack) / Max;
477
478 // Translate the floats to integers.
479 LLVM_DEBUG({
480 auto Min = Scaled64::getLargest();
481 for (const FrequencyData &F : BFI.Freqs)
482 Min = std::min(Min, F.Scaled);
483 dbgs() << "float-to-int: min = " << Min << ", max = " << Max
484 << ", factor = " << ScalingFactor << "\n";
485 });
486 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
487 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
488 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
489 LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
490 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
491 << ", int = " << BFI.Freqs[Index].Integer << "\n");
492 }
493}
494
495/// Unwrap a loop package.
496///
497/// Visits all the members of a loop, adjusting their BlockData according to
498/// the loop's pseudo-node.
499static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
500 LLVM_DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
501 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
502 << "\n");
503 Loop.Scale *= Loop.Mass.toScaled();
504 Loop.IsPackaged = false;
505 LLVM_DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
506
507 // Propagate the head scale through the loop. Since members are visited in
508 // RPO, the head scale will be updated by the loop scale first, and then the
509 // final head scale will be used for updated the rest of the members.
510 for (const BlockNode &N : Loop.Nodes) {
511 const auto &Working = BFI.Working[N.Index];
512 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
513 : BFI.Freqs[N.Index].Scaled;
514 Scaled64 New = Loop.Scale * F;
515 LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => "
516 << New << "\n");
517 F = New;
518 }
519}
520
522 // Set initial frequencies from loop-local masses.
523 for (size_t Index = 0; Index < Working.size(); ++Index)
524 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
525
526 for (LoopData &Loop : Loops)
527 unwrapLoop(*this, Loop);
528}
529
531 // Convert to integers.
533
534 // Clean up data structures.
535 cleanup(*this);
536
537 // Print out the final stats.
538 LLVM_DEBUG(dump());
539}
540
543 if (!Node.isValid()) {
544#ifndef NDEBUG
548 OS << "*** Detected BFI query for unknown block " << getBlockName(Node);
550 }
551#endif
552 return BlockFrequency(0);
553 }
554 return BlockFrequency(Freqs[Node.Index].Integer);
555}
556
557std::optional<uint64_t>
562
563std::optional<uint64_t>
565 BlockFrequency Freq) const {
566 auto EntryCount = F.getEntryCount();
567 if (!EntryCount)
568 return std::nullopt;
569 // Use 128 bit APInt to do the arithmetic to avoid overflow.
570 APInt BlockCount(128, *EntryCount);
571 APInt BlockFreq(128, Freq.getFrequency());
572 APInt EntryFreq(128, getEntryFreq().getFrequency());
573 BlockCount *= BlockFreq;
574 // Rounded division of BlockCount by EntryFreq. Since EntryFreq is unsigned
575 // lshr by 1 gives EntryFreq/2.
576 BlockCount = (BlockCount + EntryFreq.lshr(1)).udiv(EntryFreq);
577 return BlockCount.getLimitedValue();
578}
579
580bool
582 if (!Node.isValid())
583 return false;
584 return IsIrrLoopHeader.test(Node.Index);
585}
586
587Scaled64
589 if (!Node.isValid())
590 return Scaled64::getZero();
591 return Freqs[Node.Index].Scaled;
592}
593
595 BlockFrequency Freq) {
596 assert(Node.isValid() && "Expected valid node");
597 assert(Node.Index < Freqs.size() && "Expected legal index");
598 Freqs[Node.Index].Integer = Freq.getFrequency();
599}
600
601std::string
603 return {};
604}
605
606std::string
608 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
609}
610
612 Start = OuterLoop.getHeader();
613 Nodes.reserve(OuterLoop.Nodes.size());
614 for (auto N : OuterLoop.Nodes)
615 addNode(N);
616 indexNodes();
617}
618
620 Start = 0;
621 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
622 if (!BFI.Working[Index].isPackaged())
623 addNode(Index);
624 indexNodes();
625}
626
628 for (auto &I : Nodes)
629 Lookup[I.Node.Index] = &I;
630}
631
633 const BFIBase::LoopData *OuterLoop) {
634 if (OuterLoop && OuterLoop->isHeader(Succ))
635 return;
636 auto L = Lookup.find(Succ.Index);
637 if (L == Lookup.end())
638 return;
639 IrrNode &SuccIrr = *L->second;
640 Irr.Succs.push_back(&SuccIrr);
641}
642
643namespace llvm {
644
645template <> struct GraphTraits<IrreducibleGraph> {
647 using NodeRef = const GraphT::IrrNode *;
648 using ChildIteratorType = GraphT::IrrNode::iterator;
649
650 static NodeRef getEntryNode(const GraphT &G) { return G.StartIrr; }
651 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
652 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
653};
654
655} // end namespace llvm
656
657/// Package \c SCC into a loop represented by its lowest-RPO member.
658static void
660 const IrreducibleGraph &G, LoopData *OuterLoop,
661 std::list<LoopData>::iterator Insert,
663 const BitVector &IsEntry, const BitVector &Extra) {
664 LLVM_DEBUG(dbgs() << " - found-scc\n");
665
666 // One representative, not a header set: solving the SCC makes the entries'
667 // relative frequencies fall out of the solve rather than out of an assumed
668 // split. Take the lowest RPO node so the choice is deterministic.
669 LoopData::NodeList Members;
670 Members.reserve(SCC.size());
671 for (const auto *I : SCC) {
672 Members.push_back(I->Node);
673 // The package no longer distinguishes headers; the marking stays because
674 // PGOInstrumentation places counters on isIrrLoopHeader().
675 bool Header = IsEntry.test(G.getIndex(I)) || Extra.test(G.getIndex(I));
676 if (Header)
677 BFI.IsIrrLoopHeader.set(I->Node.Index);
678 LLVM_DEBUG(dbgs() << (Header ? " => header = " : " => member = ")
679 << BFI.getBlockName(I->Node) << "\n");
680 }
681 llvm::sort(Members);
682
683 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, std::move(Members));
684
685 // Update loop hierarchy.
686 for (const auto &N : Loop->Nodes)
687 if (BFI.Working[N.Index].isLoopHeader())
688 BFI.Working[N.Index].Loop->Parent = &*Loop;
689 else
690 BFI.Working[N.Index].Loop = &*Loop;
691}
692
693iterator_range<std::list<LoopData>::iterator>
695 const IrreducibleGraph &G, LoopData *OuterLoop,
696 std::list<LoopData>::iterator Insert) {
697 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
698 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
699
700 // Number every node's SCC, as the sweeps below compare an edge's two ends.
701 // Only multi-node SCCs become loops, so keep just their members.
702 SmallVector<unsigned> SccId(G.Nodes.size(), ~0u);
704 unsigned Id = 0;
705 for (auto I = scc_begin(G); !I.isAtEnd(); ++I, ++Id) {
706 for (const auto *N : *I)
707 SccId[G.getIndex(N)] = Id;
708 if (I->size() >= 2)
709 SCCs.emplace_back(I->begin(), I->end());
710 }
711
712 // A node is an entry if an edge from another SCC reaches it, and an extra
713 // header if a backedge within its SCC targets it. Backedges from entries
714 // can have inverted ordering, so they do not make a header. Mass no longer
715 // depends on this split; it only decides isIrrLoopHeader().
716 BitVector IsEntry(G.Nodes.size());
717 BitVector Extra(G.Nodes.size());
718 for (const auto &U : G.Nodes)
719 for (const auto *V : U.Succs)
720 if (SccId[G.getIndex(&U)] != SccId[G.getIndex(V)])
721 IsEntry.set(G.getIndex(V));
722 for (const auto &U : G.Nodes) {
723 if (IsEntry.test(G.getIndex(&U)))
724 continue;
725 for (const auto *V : U.Succs)
726 if (SccId[G.getIndex(V)] == SccId[G.getIndex(&U)] && !(U.Node < V->Node))
727 Extra.set(G.getIndex(V));
728 }
729
730 for (const auto &SCC : SCCs)
731 createIrreducibleLoop(*this, G, OuterLoop, Insert, SCC, IsEntry, Extra);
732
733 if (OuterLoop)
734 return make_range(std::next(Prev), Insert);
735 return make_range(Loops.begin(), Insert);
736}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
@ Scaled
static void combineWeightsBySorting(WeightList &Weights)
static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI)
static void cleanup(BlockFrequencyInfoImplBase &BFI)
Clear all memory not needed downstream.
static void combineWeightsByHashing(WeightList &Weights)
static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop)
Unwrap a loop package.
static void combineWeight(Weight &W, const Weight &OtherW)
static void debugAssign(const BlockFrequencyInfoImplBase &BFI, const DitheringDistributer &D, const BlockNode &T, const BlockMass &M, const char *Desc)
static void combineWeights(WeightList &Weights)
static char getHexDigit(int N)
static void createIrreducibleLoop(BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G, LoopData *OuterLoop, std::list< LoopData >::iterator Insert, ArrayRef< const IrreducibleGraph::IrrNode * > SCC, const BitVector &IsEntry, const BitVector &Extra)
Package SCC into a loop represented by its lowest-RPO member.
static uint64_t shiftRightAndRound(uint64_t N, int Shift)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:683
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file implements a map that provides insertion order iteration.
#define T
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
const char * Msg
This file defines the SmallString class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
Base class for BlockFrequencyInfoImpl.
std::vector< WorkingData > Working
Loop data: see initializeLoops().
std::optional< uint64_t > getProfileCountFromFreq(const Function &F, BlockFrequency Freq) const
std::list< LoopData > Loops
Indexed information about loops.
void addToDist(Distribution &Dist, const LoopData *OuterLoop, const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight)
Add an edge to the distribution.
std::optional< uint64_t > getBlockProfileCount(const Function &F, const BlockNode &Node) const
std::string getLoopName(const LoopData &Loop) const
bool TopContainsIrreducible
Has an irreducible SCC outside every loop.
bool isIrrLoopHeader(const BlockNode &Node)
void computeLoopScale(LoopData &Loop)
Compute the loop scale for a loop.
void packageLoop(LoopData &Loop)
Package up a loop.
virtual std::string getBlockName(const BlockNode &Node) const
void finalizeMetrics()
Finalize frequency metrics.
void setBlockFreq(const BlockNode &Node, BlockFrequency Freq)
BlockFrequency getBlockFreq(const BlockNode &Node) const
iterator_range< std::list< LoopData >::iterator > analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop, std::list< LoopData >::iterator Insert)
Analyze irreducible SCCs.
Scaled64 getFloatingBlockFreq(const BlockNode &Node) const
void distributeMass(const BlockNode &Source, LoopData *OuterLoop, Distribution &Dist)
Distribute mass according to a distribution.
SparseBitVector IsIrrLoopHeader
Whether each block is an irreducible loop header.
void addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist)
Add all edges out of a packaged loop to the distribution.
std::vector< FrequencyData > Freqs
Data about each block. This is used downstream.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
BlockT * getHeader() const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
void reserve(size_type NumEntries)
Grow the MapVector so that it can contain at least NumEntries items before resizing again.
Definition MapVector.h:62
size_type size() const
Definition MapVector.h:58
Simple representation of a scaled number.
ScaledNumber inverse() const
static ScaledNumber getZero()
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void set(unsigned Idx)
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI raw_ostream & print(raw_ostream &OS) const
LLVM_ABI ScaledNumber< uint64_t > toScaled() const
Convert to scaled number.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
#define UINT64_MAX
Definition DataTypes.h:77
std::string getBlockName(const BlockT *BB)
Get the name of a MachineBasicBlock.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
Op::Description Desc
LLVM_ABI llvm::cl::opt< unsigned > IterativeBFIMaxIterationsPerBlock
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI llvm::cl::opt< bool > UseIterativeBFIInference
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI llvm::cl::opt< bool > CheckBFIUnknownBlockQueries
LLVM_ABI llvm::cl::opt< double > IterativeBFIPrecision
#define N
Distribution of unscaled probability weight.
void addBackedge(const BlockNode &Node, uint64_t Amount)
WeightList Weights
Individual successor weights.
LLVM_ABI void normalize()
Normalize the distribution.
void addExit(const BlockNode &Node, uint64_t Amount)
void addLocal(const BlockNode &Node, uint64_t Amount)
ExitMap Exits
Successor edges (and weights).
BlockMass BackedgeMass
Mass that circulates, not exits.
NodeList Nodes
Header and the members of the loop.
static ChildIteratorType child_begin(NodeRef N)
static ChildIteratorType child_end(NodeRef N)
static NodeRef getEntryNode(const GraphT &G)
Graph of irreducible control flow.
LLVM_ABI void addEdge(IrrNode &Irr, const BlockNode &Succ, const BFIBase::LoopData *OuterLoop)
SmallDenseMap< uint32_t, IrrNode *, 4 > Lookup
LLVM_ABI void addNodesInLoop(const BFIBase::LoopData &OuterLoop)