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
13#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/SCCIterator.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/Config/llvm-config.h"
19#include "llvm/IR/Function.h"
20#include "llvm/Support/BlockFrequency.h"
21#include "llvm/Support/BranchProbability.h"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/MathExtras.h"
25#include "llvm/Support/ScaledNumber.h"
26#include "llvm/Support/raw_ostream.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 {
44cl::opt<bool> CheckBFIUnknownBlockQueries(
45 "check-bfi-unknown-block-queries",
46 cl::init(Val: false), cl::Hidden,
47 cl::desc("Check if block frequency is queried for an unknown block "
48 "for debugging missed BFI updates"));
49
50cl::opt<bool> UseIterativeBFIInference(
51 "use-iterative-bfi-inference", cl::Hidden,
52 cl::desc("Apply an iterative post-processing to infer correct BFI counts"));
53
54cl::opt<unsigned> IterativeBFIMaxIterationsPerBlock(
55 "iterative-bfi-max-iterations-per-block", cl::init(Val: 1000), cl::Hidden,
56 cl::desc("Iterative inference: maximum number of update iterations "
57 "per block"));
58
59cl::opt<double> IterativeBFIPrecision(
60 "iterative-bfi-precision", cl::init(Val: 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
65ScaledNumber<uint64_t> BlockMass::toScaled() const {
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)
72LLVM_DUMP_METHOD void BlockMass::dump() const { print(dbgs()); }
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
82raw_ostream &BlockMass::print(raw_ostream &OS) const {
83 for (int Digits = 0; Digits < 16; ++Digits)
84 OS << getHexDigit(N: Mass >> (60 - Digits * 4) & 0xf);
85 return OS;
86}
87
88namespace {
89
90using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
91using Distribution = BlockFrequencyInfoImplBase::Distribution;
92using WeightList = BlockFrequencyInfoImplBase::Distribution::WeightList;
93using Scaled64 = BlockFrequencyInfoImplBase::Scaled64;
94using LoopData = BlockFrequencyInfoImplBase::LoopData;
95using Weight = BlockFrequencyInfoImplBase::Weight;
96using FrequencyData = BlockFrequencyInfoImplBase::FrequencyData;
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(Elt: 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(C&: Weights, Comp: [](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(W&: *O, OtherW: *L);
193 }
194
195 // Erase extra entries.
196 Weights.erase(CS: O, CE: Weights.end());
197}
198
199static void combineWeightsByHashing(WeightList &Weights) {
200 // Collect weights into a DenseMap.
201 using HashTable = DenseMap<BlockNode::IndexType, Weight>;
202
203 HashTable Combined(NextPowerOf2(A: 2 * Weights.size()));
204 for (const Weight &W : Weights)
205 combineWeight(W&: Combined[W.TargetNode.Index], OtherW: W);
206
207 // Check whether anything changed.
208 if (Weights.size() == Combined.size())
209 return;
210
211 // Fill in the new weights.
212 Weights.clear();
213 Weights.reserve(N: Combined.size());
214 for (const auto &I : Combined)
215 Weights.push_back(Elt: I.second);
216}
217
218static void combineWeights(WeightList &Weights) {
219 // Use a hash table for many successors to keep this linear.
220 if (Weights.size() > 128) {
221 combineWeightsByHashing(Weights);
222 return;
223 }
224
225 combineWeightsBySorting(Weights);
226}
227
228static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
229 assert(Shift >= 0);
230 assert(Shift < 64);
231 if (!Shift)
232 return N;
233 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
234}
235
236void Distribution::normalize() {
237 // Early exit for termination nodes.
238 if (Weights.empty())
239 return;
240
241 // Only bother if there are multiple successors.
242 if (Weights.size() > 1)
243 combineWeights(Weights);
244
245 // Early exit when combined into a single successor.
246 if (Weights.size() == 1) {
247 Total = 1;
248 Weights.front().Amount = 1;
249 return;
250 }
251
252 // Determine how much to shift right so that the total fits into 32-bits.
253 //
254 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
255 // for each weight can cause a 32-bit overflow.
256 int Shift = 0;
257 if (DidOverflow)
258 Shift = 33;
259 else if (Total > UINT32_MAX)
260 Shift = 33 - llvm::countl_zero(Val: Total);
261
262 // Early exit if nothing needs to be scaled.
263 if (!Shift) {
264 // If we didn't overflow then combineWeights() shouldn't have changed the
265 // sum of the weights, but let's double-check.
266 assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
267 [](uint64_t Sum, const Weight &W) {
268 return Sum + W.Amount;
269 }) &&
270 "Expected total to be correct");
271 return;
272 }
273
274 // Recompute the total through accumulation (rather than shifting it) so that
275 // it's accurate after shifting and any changes combineWeights() made above.
276 Total = 0;
277
278 // Sum the weights to each node and shift right if necessary.
279 for (Weight &W : Weights) {
280 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
281 // can round here without concern about overflow.
282 assert(W.TargetNode.isValid());
283 W.Amount = std::max(UINT64_C(1), b: shiftRightAndRound(N: W.Amount, Shift));
284 assert(W.Amount <= UINT32_MAX);
285
286 // Update the total.
287 Total += W.Amount;
288 }
289 assert(Total <= UINT32_MAX);
290}
291
292void BlockFrequencyInfoImplBase::clear() {
293 // Swap with a default-constructed std::vector, since std::vector<>::clear()
294 // does not actually clear heap storage.
295 std::vector<FrequencyData>().swap(x&: Freqs);
296 IsIrrLoopHeader.clear();
297 std::vector<WorkingData>().swap(x&: Working);
298 Loops.clear();
299 TopContainsIrreducible = false;
300}
301
302/// Clear all memory not needed downstream.
303///
304/// Releases all memory not used downstream. In particular, saves Freqs.
305static void cleanup(BlockFrequencyInfoImplBase &BFI) {
306 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
307 SparseBitVector<> SavedIsIrrLoopHeader(std::move(BFI.IsIrrLoopHeader));
308 BFI.clear();
309 BFI.Freqs = std::move(SavedFreqs);
310 BFI.IsIrrLoopHeader = std::move(SavedIsIrrLoopHeader);
311}
312
313void BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
314 const LoopData *OuterLoop,
315 const BlockNode &Pred,
316 const BlockNode &Succ,
317 uint64_t Weight) {
318 if (!Weight)
319 Weight = 1;
320
321 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
322 return OuterLoop && OuterLoop->isHeader(Node);
323 };
324
325 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
326
327#ifndef NDEBUG
328 auto debugSuccessor = [&](const char *Type) {
329 dbgs() << " =>"
330 << " [" << Type << "] weight = " << Weight;
331 if (!isLoopHeader(Resolved))
332 dbgs() << ", succ = " << getBlockName(Succ);
333 dbgs() << ", pred = " << getBlockName(Pred);
334 if (Resolved != Succ)
335 dbgs() << ", resolved = " << getBlockName(Resolved);
336 dbgs() << "\n";
337 };
338 (void)debugSuccessor;
339#endif
340
341 if (isLoopHeader(Resolved)) {
342 LLVM_DEBUG(debugSuccessor("backedge"));
343 Dist.addBackedge(Node: Resolved, Amount: Weight);
344 return;
345 }
346
347 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
348 LLVM_DEBUG(debugSuccessor(" exit "));
349 Dist.addExit(Node: Resolved, Amount: Weight);
350 return;
351 }
352
353 // Every irreducible SCC is packaged before mass distribution and an
354 // irreducible package is solved rather than swept, so the only retreating
355 // edge left is the one to OuterLoop's header, handled above.
356 assert(Resolved >= Pred && "unhandled irreducible control flow");
357
358 LLVM_DEBUG(debugSuccessor(" local "));
359 Dist.addLocal(Node: Resolved, Amount: Weight);
360}
361
362void BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
363 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
364 // Copy the exit map into Dist.
365 for (const auto &I : Loop.Exits)
366 addToDist(Dist, OuterLoop, Pred: Loop.getHeader(), Succ: I.first, Weight: I.second.getMass());
367}
368
369/// Compute the loop scale for a loop.
370void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
371 // Compute loop scale.
372 LLVM_DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
373
374 // Infinite loops need special handling. If we give the back edge an infinite
375 // mass, they may saturate all the other scales in the function down to 1,
376 // making all the other region temperatures look exactly the same. Choose an
377 // arbitrary scale to avoid these issues.
378 //
379 // FIXME: An alternate way would be to select a symbolic scale which is later
380 // replaced to be the maximum of all computed scales plus 1. This would
381 // appropriately describe the loop as having a large scale, without skewing
382 // the final frequency computation.
383 const Scaled64 InfiniteLoopScale(1, 12);
384
385 // LoopScale == 1 / ExitMass
386 // ExitMass == HeadMass - BackedgeMass
387 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
388
389 // Block scale stores the inverse of the scale. If this is an infinite loop,
390 // its exit mass will be zero. In this case, use an arbitrary scale for the
391 // loop scale.
392 Loop.Scale =
393 ExitMass.isEmpty() ? InfiniteLoopScale : ExitMass.toScaled().inverse();
394
395 LLVM_DEBUG(dbgs() << " - exit-mass = " << ExitMass << " ("
396 << BlockMass::getFull() << " - " << Loop.BackedgeMass
397 << ")\n"
398 << " - scale = " << Loop.Scale << "\n");
399}
400
401/// Package up a loop.
402void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
403 LLVM_DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
404
405 // Clear the subloop exits to prevent quadratic memory usage.
406 for (const BlockNode &M : Loop.Nodes) {
407 if (auto *Loop = Working[M.Index].getPackagedLoop())
408 Loop->Exits.clear();
409 LLVM_DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
410 }
411 Loop.IsPackaged = true;
412}
413
414#ifndef NDEBUG
415static void debugAssign(const BlockFrequencyInfoImplBase &BFI,
416 const DitheringDistributer &D, const BlockNode &T,
417 const BlockMass &M, const char *Desc) {
418 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
419 if (Desc)
420 dbgs() << " [" << Desc << "]";
421 if (T.isValid())
422 dbgs() << " to " << BFI.getBlockName(T);
423 dbgs() << "\n";
424}
425#endif
426
427void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
428 LoopData *OuterLoop,
429 Distribution &Dist) {
430 BlockMass Mass = Working[Source.Index].getMass();
431 LLVM_DEBUG(dbgs() << " => mass: " << Mass << "\n");
432
433 // Distribute mass to successors as laid out in Dist.
434 DitheringDistributer D(Dist, Mass);
435
436 for (const Weight &W : Dist.Weights) {
437 // Check for a local edge (non-backedge and non-exit).
438 BlockMass Taken = D.takeMass(Weight: W.Amount);
439 if (W.Type == Weight::Local) {
440 Working[W.TargetNode.Index].getMass() += Taken;
441 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
442 continue;
443 }
444
445 // Backedges and exits only make sense if we're processing a loop.
446 assert(OuterLoop && "backedge or exit outside of loop");
447
448 // Check for a backedge.
449 if (W.Type == Weight::Backedge) {
450 OuterLoop->BackedgeMass += Taken;
451 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "back"));
452 continue;
453 }
454
455 // This must be an exit.
456 assert(W.Type == Weight::Exit);
457 OuterLoop->Exits.push_back(Elt: std::make_pair(x: W.TargetNode, y&: Taken));
458 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "exit"));
459 }
460}
461
462static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI) {
463 auto Max = Scaled64::getZero();
464 for (const FrequencyData &F : BFI.Freqs)
465 Max = std::max(a: Max, b: F.Scaled);
466
467 // Scale the Factor to a size that creates integers. If possible scale
468 // integers so that Max == UINT64_MAX so that they can be best differentiated.
469 // It is possible that the range between min and max cannot be accurately
470 // represented in a 64bit integer without either loosing precision for small
471 // values (so small unequal numbers all map to 1) or saturaturing big numbers
472 // loosing precision for big numbers (so unequal big numbers may map to
473 // UINT64_MAX). We choose to loose precision for small numbers.
474 const unsigned MaxBits = sizeof(Scaled64::DigitsType) * CHAR_BIT;
475 // Users often add up multiple BlockFrequency values or multiply them with
476 // things like instruction costs. Leave some room to avoid saturating
477 // operations reaching UIN64_MAX too early.
478 const unsigned Slack = 10;
479 Scaled64 ScalingFactor = Scaled64(1, MaxBits - Slack) / Max;
480
481 // Translate the floats to integers.
482 LLVM_DEBUG({
483 auto Min = Scaled64::getLargest();
484 for (const FrequencyData &F : BFI.Freqs)
485 Min = std::min(Min, F.Scaled);
486 dbgs() << "float-to-int: min = " << Min << ", max = " << Max
487 << ", factor = " << ScalingFactor << "\n";
488 });
489 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
490 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
491 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), b: Scaled.toInt<uint64_t>());
492 LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
493 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
494 << ", int = " << BFI.Freqs[Index].Integer << "\n");
495 }
496}
497
498/// Unwrap a loop package.
499///
500/// Visits all the members of a loop, adjusting their BlockData according to
501/// the loop's pseudo-node.
502static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
503 LLVM_DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
504 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
505 << "\n");
506 Loop.Scale *= Loop.Mass.toScaled();
507 Loop.IsPackaged = false;
508 LLVM_DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
509
510 // Propagate the head scale through the loop. Since members are visited in
511 // RPO, the head scale will be updated by the loop scale first, and then the
512 // final head scale will be used for updated the rest of the members.
513 for (const BlockNode &N : Loop.Nodes) {
514 const auto &Working = BFI.Working[N.Index];
515 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
516 : BFI.Freqs[N.Index].Scaled;
517 Scaled64 New = Loop.Scale * F;
518 LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => "
519 << New << "\n");
520 F = New;
521 }
522}
523
524void BlockFrequencyInfoImplBase::unwrapLoops() {
525 // Set initial frequencies from loop-local masses.
526 for (size_t Index = 0; Index < Working.size(); ++Index)
527 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
528
529 for (LoopData &Loop : Loops)
530 unwrapLoop(BFI&: *this, Loop);
531}
532
533void BlockFrequencyInfoImplBase::finalizeMetrics() {
534 // Convert to integers.
535 convertFloatingToInteger(BFI&: *this);
536
537 // Clean up data structures.
538 cleanup(BFI&: *this);
539
540 // Print out the final stats.
541 LLVM_DEBUG(dump());
542}
543
544BlockFrequency
545BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
546 if (!Node.isValid()) {
547#ifndef NDEBUG
548 if (CheckBFIUnknownBlockQueries) {
549 SmallString<256> Msg;
550 raw_svector_ostream OS(Msg);
551 OS << "*** Detected BFI query for unknown block " << getBlockName(Node);
552 report_fatal_error(OS.str());
553 }
554#endif
555 return BlockFrequency(0);
556 }
557 return BlockFrequency(Freqs[Node.Index].Integer);
558}
559
560std::optional<uint64_t>
561BlockFrequencyInfoImplBase::getBlockProfileCount(const Function &F,
562 const BlockNode &Node) const {
563 return getProfileCountFromFreq(F, Freq: getBlockFreq(Node));
564}
565
566std::optional<uint64_t>
567BlockFrequencyInfoImplBase::getProfileCountFromFreq(const Function &F,
568 BlockFrequency Freq) const {
569 auto EntryCount = F.getEntryCount();
570 if (!EntryCount)
571 return std::nullopt;
572 // Use 128 bit APInt to do the arithmetic to avoid overflow.
573 APInt BlockCount(128, *EntryCount);
574 APInt BlockFreq(128, Freq.getFrequency());
575 APInt EntryFreq(128, getEntryFreq().getFrequency());
576 BlockCount *= BlockFreq;
577 // Rounded division of BlockCount by EntryFreq. Since EntryFreq is unsigned
578 // lshr by 1 gives EntryFreq/2.
579 BlockCount = (BlockCount + EntryFreq.lshr(shiftAmt: 1)).udiv(RHS: EntryFreq);
580 return BlockCount.getLimitedValue();
581}
582
583bool
584BlockFrequencyInfoImplBase::isIrrLoopHeader(const BlockNode &Node) {
585 if (!Node.isValid())
586 return false;
587 return IsIrrLoopHeader.test(Idx: Node.Index);
588}
589
590Scaled64
591BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
592 if (!Node.isValid())
593 return Scaled64::getZero();
594 return Freqs[Node.Index].Scaled;
595}
596
597void BlockFrequencyInfoImplBase::setBlockFreq(const BlockNode &Node,
598 BlockFrequency Freq) {
599 assert(Node.isValid() && "Expected valid node");
600 assert(Node.Index < Freqs.size() && "Expected legal index");
601 Freqs[Node.Index].Integer = Freq.getFrequency();
602}
603
604std::string
605BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
606 return {};
607}
608
609std::string
610BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
611 return getBlockName(Node: Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
612}
613
614void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
615 Start = OuterLoop.getHeader();
616 Nodes.reserve(n: OuterLoop.Nodes.size());
617 for (auto N : OuterLoop.Nodes)
618 addNode(Node: N);
619 indexNodes();
620}
621
622void IrreducibleGraph::addNodesInFunction() {
623 Start = 0;
624 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
625 if (!BFI.Working[Index].isPackaged())
626 addNode(Node: Index);
627 indexNodes();
628}
629
630void IrreducibleGraph::indexNodes() {
631 for (auto &I : Nodes)
632 Lookup[I.Node.Index] = &I;
633}
634
635void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
636 const BFIBase::LoopData *OuterLoop) {
637 if (OuterLoop && OuterLoop->isHeader(Node: Succ))
638 return;
639 auto L = Lookup.find(Val: Succ.Index);
640 if (L == Lookup.end())
641 return;
642 IrrNode &SuccIrr = *L->second;
643 Irr.Succs.push_back(Elt: &SuccIrr);
644}
645
646namespace llvm {
647
648template <> struct GraphTraits<IrreducibleGraph> {
649 using GraphT = bfi_detail::IrreducibleGraph;
650 using NodeRef = const GraphT::IrrNode *;
651 using ChildIteratorType = GraphT::IrrNode::iterator;
652
653 static NodeRef getEntryNode(const GraphT &G) { return G.StartIrr; }
654 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
655 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
656};
657
658} // end namespace llvm
659
660/// Package \c SCC into a loop represented by its lowest-RPO member.
661static void
662createIrreducibleLoop(BlockFrequencyInfoImplBase &BFI,
663 const IrreducibleGraph &G, LoopData *OuterLoop,
664 std::list<LoopData>::iterator Insert,
665 ArrayRef<const IrreducibleGraph::IrrNode *> SCC,
666 const BitVector &IsEntry, const BitVector &Extra) {
667 LLVM_DEBUG(dbgs() << " - found-scc\n");
668
669 // One representative, not a header set: solving the SCC makes the entries'
670 // relative frequencies fall out of the solve rather than out of an assumed
671 // split. Take the lowest RPO node so the choice is deterministic.
672 LoopData::NodeList Members;
673 Members.reserve(N: SCC.size());
674 for (const auto *I : SCC) {
675 Members.push_back(Elt: I->Node);
676 // The package no longer distinguishes headers; the marking stays because
677 // PGOInstrumentation places counters on isIrrLoopHeader().
678 bool Header = IsEntry.test(Idx: G.getIndex(N: I)) || Extra.test(Idx: G.getIndex(N: I));
679 if (Header)
680 BFI.IsIrrLoopHeader.set(I->Node.Index);
681 LLVM_DEBUG(dbgs() << (Header ? " => header = " : " => member = ")
682 << BFI.getBlockName(I->Node) << "\n");
683 }
684 llvm::sort(C&: Members);
685
686 auto Loop = BFI.Loops.emplace(position: Insert, args&: OuterLoop, args: std::move(Members));
687
688 // Update loop hierarchy.
689 for (const auto &N : Loop->Nodes)
690 if (BFI.Working[N.Index].isLoopHeader())
691 BFI.Working[N.Index].Loop->Parent = &*Loop;
692 else
693 BFI.Working[N.Index].Loop = &*Loop;
694}
695
696iterator_range<std::list<LoopData>::iterator>
697BlockFrequencyInfoImplBase::analyzeIrreducible(
698 const IrreducibleGraph &G, LoopData *OuterLoop,
699 std::list<LoopData>::iterator Insert) {
700 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
701 auto Prev = OuterLoop ? std::prev(x: Insert) : Loops.end();
702
703 // Number every node's SCC, as the sweeps below compare an edge's two ends.
704 // Only multi-node SCCs become loops, so keep just their members.
705 SmallVector<unsigned> SccId(G.Nodes.size(), ~0u);
706 SmallVector<SmallVector<const IrreducibleGraph::IrrNode *>> SCCs;
707 unsigned Id = 0;
708 for (auto I = scc_begin(G); !I.isAtEnd(); ++I, ++Id) {
709 for (const auto *N : *I)
710 SccId[G.getIndex(N)] = Id;
711 if (I->size() >= 2)
712 SCCs.emplace_back(Args: I->begin(), Args: I->end());
713 }
714
715 // A node is an entry if an edge from another SCC reaches it, and an extra
716 // header if a backedge within its SCC targets it. Backedges from entries
717 // can have inverted ordering, so they do not make a header. Mass no longer
718 // depends on this split; it only decides isIrrLoopHeader().
719 BitVector IsEntry(G.Nodes.size());
720 BitVector Extra(G.Nodes.size());
721 for (const auto &U : G.Nodes)
722 for (const auto *V : U.Succs)
723 if (SccId[G.getIndex(N: &U)] != SccId[G.getIndex(N: V)])
724 IsEntry.set(G.getIndex(N: V));
725 for (const auto &U : G.Nodes) {
726 if (IsEntry.test(Idx: G.getIndex(N: &U)))
727 continue;
728 for (const auto *V : U.Succs)
729 if (SccId[G.getIndex(N: V)] == SccId[G.getIndex(N: &U)] && !(U.Node < V->Node))
730 Extra.set(G.getIndex(N: V));
731 }
732
733 for (const auto &SCC : SCCs)
734 createIrreducibleLoop(BFI&: *this, G, OuterLoop, Insert, SCC, IsEntry, Extra);
735
736 if (OuterLoop)
737 return make_range(x: std::next(x: Prev), y: Insert);
738 return make_range(x: Loops.begin(), y: Insert);
739}
740