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/SCCIterator.h"
16 #include "llvm/Support/raw_ostream.h"
19 using namespace llvm::bfi_detail;
21 #define DEBUG_TYPE "block-freq"
23 ScaledNumber<uint64_t> BlockMass::toScaled() const {
25 return ScaledNumber<uint64_t>(1, 0);
26 return ScaledNumber<uint64_t>(getMass() + 1, -64);
29 void BlockMass::dump() const { print(dbgs()); }
31 static char getHexDigit(int N) {
37 raw_ostream &BlockMass::print(raw_ostream &OS) const {
38 for (int Digits = 0; Digits < 16; ++Digits)
39 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
45 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
46 typedef BlockFrequencyInfoImplBase::Distribution Distribution;
47 typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
48 typedef BlockFrequencyInfoImplBase::Scaled64 Scaled64;
49 typedef BlockFrequencyInfoImplBase::LoopData LoopData;
50 typedef BlockFrequencyInfoImplBase::Weight Weight;
51 typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
53 /// \brief Dithering mass distributer.
55 /// This class splits up a single mass into portions by weight, dithering to
56 /// spread out error. No mass is lost. The dithering precision depends on the
57 /// precision of the product of \a BlockMass and \a BranchProbability.
59 /// The distribution algorithm follows.
61 /// 1. Initialize by saving the sum of the weights in \a RemWeight and the
62 /// mass to distribute in \a RemMass.
64 /// 2. For each portion:
66 /// 1. Construct a branch probability, P, as the portion's weight divided
67 /// by the current value of \a RemWeight.
68 /// 2. Calculate the portion's mass as \a RemMass times P.
69 /// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
70 /// the current portion's weight and mass.
71 struct DitheringDistributer {
75 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
77 BlockMass takeMass(uint32_t Weight);
82 DitheringDistributer::DitheringDistributer(Distribution &Dist,
83 const BlockMass &Mass) {
85 RemWeight = Dist.Total;
89 BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
90 assert(Weight && "invalid weight");
91 assert(Weight <= RemWeight);
92 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
94 // Decrement totals (dither).
100 void Distribution::add(const BlockNode &Node, uint64_t Amount,
101 Weight::DistType Type) {
102 assert(Amount && "invalid weight of 0");
103 uint64_t NewTotal = Total + Amount;
105 // Check for overflow. It should be impossible to overflow twice.
106 bool IsOverflow = NewTotal < Total;
107 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
108 DidOverflow |= IsOverflow;
114 Weights.push_back(Weight(Type, Node, Amount));
117 static void combineWeight(Weight &W, const Weight &OtherW) {
118 assert(OtherW.TargetNode.isValid());
123 assert(W.Type == OtherW.Type);
124 assert(W.TargetNode == OtherW.TargetNode);
125 assert(W.Amount < W.Amount + OtherW.Amount && "Unexpected overflow");
126 W.Amount += OtherW.Amount;
128 static void combineWeightsBySorting(WeightList &Weights) {
129 // Sort so edges to the same node are adjacent.
130 std::sort(Weights.begin(), Weights.end(),
132 const Weight &R) { return L.TargetNode < R.TargetNode; });
134 // Combine adjacent edges.
135 WeightList::iterator O = Weights.begin();
136 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
140 // Find the adjacent weights to the same node.
141 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
142 combineWeight(*O, *L);
145 // Erase extra entries.
146 Weights.erase(O, Weights.end());
149 static void combineWeightsByHashing(WeightList &Weights) {
150 // Collect weights into a DenseMap.
151 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
152 HashTable Combined(NextPowerOf2(2 * Weights.size()));
153 for (const Weight &W : Weights)
154 combineWeight(Combined[W.TargetNode.Index], W);
156 // Check whether anything changed.
157 if (Weights.size() == Combined.size())
160 // Fill in the new weights.
162 Weights.reserve(Combined.size());
163 for (const auto &I : Combined)
164 Weights.push_back(I.second);
166 static void combineWeights(WeightList &Weights) {
167 // Use a hash table for many successors to keep this linear.
168 if (Weights.size() > 128) {
169 combineWeightsByHashing(Weights);
173 combineWeightsBySorting(Weights);
175 static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
180 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
182 void Distribution::normalize() {
183 // Early exit for termination nodes.
187 // Only bother if there are multiple successors.
188 if (Weights.size() > 1)
189 combineWeights(Weights);
191 // Early exit when combined into a single successor.
192 if (Weights.size() == 1) {
194 Weights.front().Amount = 1;
198 // Determine how much to shift right so that the total fits into 32-bits.
200 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
201 // for each weight can cause a 32-bit overflow.
205 else if (Total > UINT32_MAX)
206 Shift = 33 - countLeadingZeros(Total);
208 // Early exit if nothing needs to be scaled.
212 // Recompute the total through accumulation (rather than shifting it) so that
213 // it's accurate after shifting.
216 // Sum the weights to each node and shift right if necessary.
217 for (Weight &W : Weights) {
218 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
219 // can round here without concern about overflow.
220 assert(W.TargetNode.isValid());
221 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
222 assert(W.Amount <= UINT32_MAX);
227 assert(Total <= UINT32_MAX);
230 void BlockFrequencyInfoImplBase::clear() {
231 // Swap with a default-constructed std::vector, since std::vector<>::clear()
232 // does not actually clear heap storage.
233 std::vector<FrequencyData>().swap(Freqs);
234 std::vector<WorkingData>().swap(Working);
238 /// \brief Clear all memory not needed downstream.
240 /// Releases all memory not used downstream. In particular, saves Freqs.
241 static void cleanup(BlockFrequencyInfoImplBase &BFI) {
242 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
244 BFI.Freqs = std::move(SavedFreqs);
247 bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
248 const LoopData *OuterLoop,
249 const BlockNode &Pred,
250 const BlockNode &Succ,
255 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
256 return OuterLoop && OuterLoop->isHeader(Node);
259 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
262 auto debugSuccessor = [&](const char *Type) {
264 << " [" << Type << "] weight = " << Weight;
265 if (!isLoopHeader(Resolved))
266 dbgs() << ", succ = " << getBlockName(Succ);
267 if (Resolved != Succ)
268 dbgs() << ", resolved = " << getBlockName(Resolved);
271 (void)debugSuccessor;
274 if (isLoopHeader(Resolved)) {
275 DEBUG(debugSuccessor("backedge"));
276 Dist.addBackedge(OuterLoop->getHeader(), Weight);
280 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
281 DEBUG(debugSuccessor(" exit "));
282 Dist.addExit(Resolved, Weight);
286 if (Resolved < Pred) {
287 if (!isLoopHeader(Pred)) {
288 // If OuterLoop is an irreducible loop, we can't actually handle this.
289 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
290 "unhandled irreducible control flow");
292 // Irreducible backedge. Abort.
293 DEBUG(debugSuccessor("abort!!!"));
297 // If "Pred" is a loop header, then this isn't really a backedge; rather,
298 // OuterLoop must be irreducible. These false backedges can come only from
299 // secondary loop headers.
300 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
301 "unhandled irreducible control flow");
304 DEBUG(debugSuccessor(" local "));
305 Dist.addLocal(Resolved, Weight);
309 bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
310 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
311 // Copy the exit map into Dist.
312 for (const auto &I : Loop.Exits)
313 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
315 // Irreducible backedge.
321 /// \brief Get the maximum allowed loop scale.
323 /// Gives the maximum number of estimated iterations allowed for a loop. Very
324 /// large numbers cause problems downstream (even within 64-bits).
325 static Scaled64 getMaxLoopScale() { return Scaled64(1, 12); }
327 /// \brief Compute the loop scale for a loop.
328 void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
329 // Compute loop scale.
330 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
332 // LoopScale == 1 / ExitMass
333 // ExitMass == HeadMass - BackedgeMass
334 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
336 // Block scale stores the inverse of the scale.
337 Loop.Scale = ExitMass.toScaled().inverse();
339 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
340 << " - " << Loop.BackedgeMass << ")\n"
341 << " - scale = " << Loop.Scale << "\n");
343 if (Loop.Scale > getMaxLoopScale()) {
344 Loop.Scale = getMaxLoopScale();
345 DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
349 /// \brief Package up a loop.
350 void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
351 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
353 // Clear the subloop exits to prevent quadratic memory usage.
354 for (const BlockNode &M : Loop.Nodes) {
355 if (auto *Loop = Working[M.Index].getPackagedLoop())
357 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
359 Loop.IsPackaged = true;
362 void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
364 Distribution &Dist) {
365 BlockMass Mass = Working[Source.Index].getMass();
366 DEBUG(dbgs() << " => mass: " << Mass << "\n");
368 // Distribute mass to successors as laid out in Dist.
369 DitheringDistributer D(Dist, Mass);
372 auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
374 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
376 dbgs() << " [" << Desc << "]";
378 dbgs() << " to " << getBlockName(T);
384 for (const Weight &W : Dist.Weights) {
385 // Check for a local edge (non-backedge and non-exit).
386 BlockMass Taken = D.takeMass(W.Amount);
387 if (W.Type == Weight::Local) {
388 Working[W.TargetNode.Index].getMass() += Taken;
389 DEBUG(debugAssign(W.TargetNode, Taken, nullptr));
393 // Backedges and exits only make sense if we're processing a loop.
394 assert(OuterLoop && "backedge or exit outside of loop");
396 // Check for a backedge.
397 if (W.Type == Weight::Backedge) {
398 OuterLoop->BackedgeMass += Taken;
399 DEBUG(debugAssign(BlockNode(), Taken, "back"));
403 // This must be an exit.
404 assert(W.Type == Weight::Exit);
405 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
406 DEBUG(debugAssign(W.TargetNode, Taken, "exit"));
410 static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
411 const Scaled64 &Min, const Scaled64 &Max) {
412 // Scale the Factor to a size that creates integers. Ideally, integers would
413 // be scaled so that Max == UINT64_MAX so that they can be best
414 // differentiated. However, the register allocator currently deals poorly
415 // with large numbers. Instead, push Min up a little from 1 to give some
416 // room to differentiate small, unequal numbers.
418 // TODO: fix issues downstream so that ScalingFactor can be
419 // Scaled64(1,64)/Max.
420 Scaled64 ScalingFactor = Min.inverse();
421 if ((Max / Min).lg() < 60)
424 // Translate the floats to integers.
425 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
426 << ", factor = " << ScalingFactor << "\n");
427 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
428 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
429 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
430 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
431 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
432 << ", int = " << BFI.Freqs[Index].Integer << "\n");
436 /// \brief Unwrap a loop package.
438 /// Visits all the members of a loop, adjusting their BlockData according to
439 /// the loop's pseudo-node.
440 static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
441 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
442 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
444 Loop.Scale *= Loop.Mass.toScaled();
445 Loop.IsPackaged = false;
446 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
448 // Propagate the head scale through the loop. Since members are visited in
449 // RPO, the head scale will be updated by the loop scale first, and then the
450 // final head scale will be used for updated the rest of the members.
451 for (const BlockNode &N : Loop.Nodes) {
452 const auto &Working = BFI.Working[N.Index];
453 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
454 : BFI.Freqs[N.Index].Scaled;
455 Scaled64 New = Loop.Scale * F;
456 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
462 void BlockFrequencyInfoImplBase::unwrapLoops() {
463 // Set initial frequencies from loop-local masses.
464 for (size_t Index = 0; Index < Working.size(); ++Index)
465 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
467 for (LoopData &Loop : Loops)
468 unwrapLoop(*this, Loop);
471 void BlockFrequencyInfoImplBase::finalizeMetrics() {
472 // Unwrap loop packages in reverse post-order, tracking min and max
474 auto Min = Scaled64::getLargest();
475 auto Max = Scaled64::getZero();
476 for (size_t Index = 0; Index < Working.size(); ++Index) {
477 // Update min/max scale.
478 Min = std::min(Min, Freqs[Index].Scaled);
479 Max = std::max(Max, Freqs[Index].Scaled);
482 // Convert to integers.
483 convertFloatingToInteger(*this, Min, Max);
485 // Clean up data structures.
488 // Print out the final stats.
493 BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
496 return Freqs[Node.Index].Integer;
499 BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
501 return Scaled64::getZero();
502 return Freqs[Node.Index].Scaled;
506 BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
507 return std::string();
510 BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
511 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
515 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
516 const BlockNode &Node) const {
517 return OS << getFloatingBlockFreq(Node);
521 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
522 const BlockFrequency &Freq) const {
523 Scaled64 Block(Freq.getFrequency(), 0);
524 Scaled64 Entry(getEntryFreq(), 0);
526 return OS << Block / Entry;
529 void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
530 Start = OuterLoop.getHeader();
531 Nodes.reserve(OuterLoop.Nodes.size());
532 for (auto N : OuterLoop.Nodes)
536 void IrreducibleGraph::addNodesInFunction() {
538 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
539 if (!BFI.Working[Index].isPackaged())
543 void IrreducibleGraph::indexNodes() {
544 for (auto &I : Nodes)
545 Lookup[I.Node.Index] = &I;
547 void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
548 const BFIBase::LoopData *OuterLoop) {
549 if (OuterLoop && OuterLoop->isHeader(Succ))
551 auto L = Lookup.find(Succ.Index);
552 if (L == Lookup.end())
554 IrrNode &SuccIrr = *L->second;
555 Irr.Edges.push_back(&SuccIrr);
556 SuccIrr.Edges.push_front(&Irr);
561 template <> struct GraphTraits<IrreducibleGraph> {
562 typedef bfi_detail::IrreducibleGraph GraphT;
564 typedef const GraphT::IrrNode NodeType;
565 typedef GraphT::IrrNode::iterator ChildIteratorType;
567 static const NodeType *getEntryNode(const GraphT &G) {
570 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
571 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
575 /// \brief Find extra irreducible headers.
577 /// Find entry blocks and other blocks with backedges, which exist when \c G
578 /// contains irreducible sub-SCCs.
579 static void findIrreducibleHeaders(
580 const BlockFrequencyInfoImplBase &BFI,
581 const IrreducibleGraph &G,
582 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
583 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
584 // Map from nodes in the SCC to whether it's an entry block.
585 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
587 // InSCC also acts the set of nodes in the graph. Seed it.
588 for (const auto *I : SCC)
591 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
592 auto &Irr = *I->first;
593 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
597 // This is an entry block.
599 Headers.push_back(Irr.Node);
600 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
604 assert(Headers.size() >= 2 &&
605 "Expected irreducible CFG; -loop-info is likely invalid");
606 if (Headers.size() == InSCC.size()) {
607 // Every block is a header.
608 std::sort(Headers.begin(), Headers.end());
612 // Look for extra headers from irreducible sub-SCCs.
613 for (const auto &I : InSCC) {
614 // Entry blocks are already headers.
618 auto &Irr = *I.first;
619 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
620 // Skip forward edges.
621 if (P->Node < Irr.Node)
624 // Skip predecessors from entry blocks. These can have inverted
629 // Store the extra header.
630 Headers.push_back(Irr.Node);
631 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
634 if (Headers.back() == Irr.Node)
635 // Added this as a header.
638 // This is not a header.
639 Others.push_back(Irr.Node);
640 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
642 std::sort(Headers.begin(), Headers.end());
643 std::sort(Others.begin(), Others.end());
646 static void createIrreducibleLoop(
647 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
648 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
649 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
650 // Translate the SCC into RPO.
651 DEBUG(dbgs() << " - found-scc\n");
653 LoopData::NodeList Headers;
654 LoopData::NodeList Others;
655 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
657 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
658 Headers.end(), Others.begin(), Others.end());
660 // Update loop hierarchy.
661 for (const auto &N : Loop->Nodes)
662 if (BFI.Working[N.Index].isLoopHeader())
663 BFI.Working[N.Index].Loop->Parent = &*Loop;
665 BFI.Working[N.Index].Loop = &*Loop;
668 iterator_range<std::list<LoopData>::iterator>
669 BlockFrequencyInfoImplBase::analyzeIrreducible(
670 const IrreducibleGraph &G, LoopData *OuterLoop,
671 std::list<LoopData>::iterator Insert) {
672 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
673 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
675 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
679 // Translate the SCC into RPO.
680 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
684 return make_range(std::next(Prev), Insert);
685 return make_range(Loops.begin(), Insert);
689 BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
690 OuterLoop.Exits.clear();
691 OuterLoop.BackedgeMass = BlockMass::getEmpty();
692 auto O = OuterLoop.Nodes.begin() + 1;
693 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
694 if (!Working[I->Index].isPackaged())
696 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());