blob: e4fda2472b3acd08fa55dd3e1c03ac87d1dd177d [file] [log] [blame]
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +00001//===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Loops should be simplified before this analysis.
10//
11//===----------------------------------------------------------------------===//
12
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000013#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000014#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/GraphTraits.h"
17#include "llvm/ADT/None.h"
Duncan P. N. Exon Smith87c40fd2014-05-06 01:57:42 +000018#include "llvm/ADT/SCCIterator.h"
Nico Weber432a3882018-04-30 14:59:11 +000019#include "llvm/Config/llvm-config.h"
Xinliang David Lib12b3532016-06-22 17:12:12 +000020#include "llvm/IR/Function.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000021#include "llvm/Support/BlockFrequency.h"
22#include "llvm/Support/BranchProbability.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ScaledNumber.h"
26#include "llvm/Support/MathExtras.h"
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000027#include "llvm/Support/raw_ostream.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000028#include <algorithm>
29#include <cassert>
30#include <cstddef>
31#include <cstdint>
32#include <iterator>
33#include <list>
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +000034#include <numeric>
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000035#include <utility>
36#include <vector>
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000037
38using namespace llvm;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +000039using namespace llvm::bfi_detail;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000040
Chandler Carruth1b9dde02014-04-22 02:02:50 +000041#define DEBUG_TYPE "block-freq"
42
Hiroshi Yamauchi803dd6f2020-02-03 12:22:03 -080043cl::opt<bool> CheckBFIUnknownBlockQueries(
44 "check-bfi-unknown-block-queries",
45 cl::init(false), cl::Hidden,
46 cl::desc("Check if block frequency is queried for an unknown block "
47 "for debugging missed BFI updates"));
48
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +000049ScaledNumber<uint64_t> BlockMass::toScaled() const {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000050 if (isFull())
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000051 return ScaledNumber<uint64_t>(1, 0);
52 return ScaledNumber<uint64_t>(getMass() + 1, -64);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000053}
54
Aaron Ballman615eb472017-10-15 14:32:27 +000055#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +000056LLVM_DUMP_METHOD void BlockMass::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +000057#endif
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000058
59static char getHexDigit(int N) {
60 assert(N < 16);
61 if (N < 10)
62 return '0' + N;
63 return 'a' + N - 10;
64}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000065
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000066raw_ostream &BlockMass::print(raw_ostream &OS) const {
67 for (int Digits = 0; Digits < 16; ++Digits)
68 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
69 return OS;
70}
71
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000072namespace {
73
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000074using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
75using Distribution = BlockFrequencyInfoImplBase::Distribution;
76using WeightList = BlockFrequencyInfoImplBase::Distribution::WeightList;
77using Scaled64 = BlockFrequencyInfoImplBase::Scaled64;
78using LoopData = BlockFrequencyInfoImplBase::LoopData;
79using Weight = BlockFrequencyInfoImplBase::Weight;
80using FrequencyData = BlockFrequencyInfoImplBase::FrequencyData;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000081
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000082/// Dithering mass distributer.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000083///
84/// This class splits up a single mass into portions by weight, dithering to
85/// spread out error. No mass is lost. The dithering precision depends on the
86/// precision of the product of \a BlockMass and \a BranchProbability.
87///
88/// The distribution algorithm follows.
89///
90/// 1. Initialize by saving the sum of the weights in \a RemWeight and the
91/// mass to distribute in \a RemMass.
92///
93/// 2. For each portion:
94///
95/// 1. Construct a branch probability, P, as the portion's weight divided
96/// by the current value of \a RemWeight.
97/// 2. Calculate the portion's mass as \a RemMass times P.
98/// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
99/// the current portion's weight and mass.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000100struct DitheringDistributer {
101 uint32_t RemWeight;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000102 BlockMass RemMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000103
104 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
105
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000106 BlockMass takeMass(uint32_t Weight);
107};
Duncan P. N. Exon Smithb5650e52014-07-11 23:56:50 +0000108
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000109} // end anonymous namespace
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000110
111DitheringDistributer::DitheringDistributer(Distribution &Dist,
112 const BlockMass &Mass) {
113 Dist.normalize();
114 RemWeight = Dist.Total;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000115 RemMass = Mass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000116}
117
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000118BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
119 assert(Weight && "invalid weight");
120 assert(Weight <= RemWeight);
121 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
122
123 // Decrement totals (dither).
124 RemWeight -= Weight;
125 RemMass -= Mass;
126 return Mass;
127}
128
129void Distribution::add(const BlockNode &Node, uint64_t Amount,
130 Weight::DistType Type) {
131 assert(Amount && "invalid weight of 0");
132 uint64_t NewTotal = Total + Amount;
133
134 // Check for overflow. It should be impossible to overflow twice.
135 bool IsOverflow = NewTotal < Total;
136 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
137 DidOverflow |= IsOverflow;
138
139 // Update the total.
140 Total = NewTotal;
141
142 // Save the weight.
Duncan P. N. Exon Smith60755102014-07-12 00:26:00 +0000143 Weights.push_back(Weight(Type, Node, Amount));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000144}
145
146static void combineWeight(Weight &W, const Weight &OtherW) {
147 assert(OtherW.TargetNode.isValid());
148 if (!W.Amount) {
149 W = OtherW;
150 return;
151 }
152 assert(W.Type == OtherW.Type);
153 assert(W.TargetNode == OtherW.TargetNode);
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000154 assert(OtherW.Amount && "Expected non-zero weight");
155 if (W.Amount > W.Amount + OtherW.Amount)
156 // Saturate on overflow.
157 W.Amount = UINT64_MAX;
158 else
159 W.Amount += OtherW.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000160}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000161
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000162static void combineWeightsBySorting(WeightList &Weights) {
163 // Sort so edges to the same node are adjacent.
Fangrui Song0cac7262018-09-27 02:13:45 +0000164 llvm::sort(Weights, [](const Weight &L, const Weight &R) {
165 return L.TargetNode < R.TargetNode;
166 });
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000167
168 // Combine adjacent edges.
169 WeightList::iterator O = Weights.begin();
170 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
171 ++O, (I = L)) {
172 *O = *I;
173
174 // Find the adjacent weights to the same node.
175 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
176 combineWeight(*O, *L);
177 }
178
179 // Erase extra entries.
180 Weights.erase(O, Weights.end());
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000181}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000182
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000183static void combineWeightsByHashing(WeightList &Weights) {
184 // Collect weights into a DenseMap.
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000185 using HashTable = DenseMap<BlockNode::IndexType, Weight>;
186
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000187 HashTable Combined(NextPowerOf2(2 * Weights.size()));
188 for (const Weight &W : Weights)
189 combineWeight(Combined[W.TargetNode.Index], W);
190
191 // Check whether anything changed.
192 if (Weights.size() == Combined.size())
193 return;
194
195 // Fill in the new weights.
196 Weights.clear();
197 Weights.reserve(Combined.size());
198 for (const auto &I : Combined)
199 Weights.push_back(I.second);
200}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000201
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000202static void combineWeights(WeightList &Weights) {
203 // Use a hash table for many successors to keep this linear.
204 if (Weights.size() > 128) {
205 combineWeightsByHashing(Weights);
206 return;
207 }
208
209 combineWeightsBySorting(Weights);
210}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000211
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000212static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
213 assert(Shift >= 0);
214 assert(Shift < 64);
215 if (!Shift)
216 return N;
217 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
218}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000219
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000220void Distribution::normalize() {
221 // Early exit for termination nodes.
222 if (Weights.empty())
223 return;
224
225 // Only bother if there are multiple successors.
226 if (Weights.size() > 1)
227 combineWeights(Weights);
228
229 // Early exit when combined into a single successor.
230 if (Weights.size() == 1) {
231 Total = 1;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000232 Weights.front().Amount = 1;
233 return;
234 }
235
236 // Determine how much to shift right so that the total fits into 32-bits.
237 //
238 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
239 // for each weight can cause a 32-bit overflow.
240 int Shift = 0;
241 if (DidOverflow)
242 Shift = 33;
243 else if (Total > UINT32_MAX)
244 Shift = 33 - countLeadingZeros(Total);
245
246 // Early exit if nothing needs to be scaled.
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000247 if (!Shift) {
248 // If we didn't overflow then combineWeights() shouldn't have changed the
249 // sum of the weights, but let's double-check.
250 assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
251 [](uint64_t Sum, const Weight &W) {
252 return Sum + W.Amount;
253 }) &&
254 "Expected total to be correct");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000255 return;
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000256 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000257
258 // Recompute the total through accumulation (rather than shifting it) so that
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000259 // it's accurate after shifting and any changes combineWeights() made above.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000260 Total = 0;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000261
262 // Sum the weights to each node and shift right if necessary.
263 for (Weight &W : Weights) {
264 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
265 // can round here without concern about overflow.
266 assert(W.TargetNode.isValid());
267 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
268 assert(W.Amount <= UINT32_MAX);
269
270 // Update the total.
271 Total += W.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000272 }
273 assert(Total <= UINT32_MAX);
274}
275
276void BlockFrequencyInfoImplBase::clear() {
Duncan P. N. Exon Smithdc2d66e2014-04-22 03:31:34 +0000277 // Swap with a default-constructed std::vector, since std::vector<>::clear()
278 // does not actually clear heap storage.
279 std::vector<FrequencyData>().swap(Freqs);
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000280 IsIrrLoopHeader.clear();
Duncan P. N. Exon Smithdc2d66e2014-04-22 03:31:34 +0000281 std::vector<WorkingData>().swap(Working);
Duncan P. N. Exon Smithfc7dc932014-04-25 04:30:06 +0000282 Loops.clear();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000283}
284
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000285/// Clear all memory not needed downstream.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000286///
287/// Releases all memory not used downstream. In particular, saves Freqs.
288static void cleanup(BlockFrequencyInfoImplBase &BFI) {
289 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000290 SparseBitVector<> SavedIsIrrLoopHeader(std::move(BFI.IsIrrLoopHeader));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000291 BFI.clear();
292 BFI.Freqs = std::move(SavedFreqs);
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000293 BFI.IsIrrLoopHeader = std::move(SavedIsIrrLoopHeader);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000294}
295
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000296bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000297 const LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000298 const BlockNode &Pred,
299 const BlockNode &Succ,
300 uint64_t Weight) {
301 if (!Weight)
302 Weight = 1;
303
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000304 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
305 return OuterLoop && OuterLoop->isHeader(Node);
306 };
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000307
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000308 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
309
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000310#ifndef NDEBUG
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000311 auto debugSuccessor = [&](const char *Type) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000312 dbgs() << " =>"
313 << " [" << Type << "] weight = " << Weight;
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000314 if (!isLoopHeader(Resolved))
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000315 dbgs() << ", succ = " << getBlockName(Succ);
316 if (Resolved != Succ)
317 dbgs() << ", resolved = " << getBlockName(Resolved);
318 dbgs() << "\n";
319 };
320 (void)debugSuccessor;
321#endif
322
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000323 if (isLoopHeader(Resolved)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000324 LLVM_DEBUG(debugSuccessor("backedge"));
Diego Novillo9a779622015-06-16 19:10:58 +0000325 Dist.addBackedge(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000326 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000327 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000328
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000329 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000330 LLVM_DEBUG(debugSuccessor(" exit "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000331 Dist.addExit(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000332 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000333 }
334
Duncan P. N. Exon Smithb3380ea2014-04-22 03:31:53 +0000335 if (Resolved < Pred) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000336 if (!isLoopHeader(Pred)) {
337 // If OuterLoop is an irreducible loop, we can't actually handle this.
338 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
339 "unhandled irreducible control flow");
340
341 // Irreducible backedge. Abort.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000342 LLVM_DEBUG(debugSuccessor("abort!!!"));
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000343 return false;
344 }
345
346 // If "Pred" is a loop header, then this isn't really a backedge; rather,
347 // OuterLoop must be irreducible. These false backedges can come only from
348 // secondary loop headers.
349 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
350 "unhandled irreducible control flow");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000351 }
352
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000353 LLVM_DEBUG(debugSuccessor(" local "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000354 Dist.addLocal(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000355 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000356}
357
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000358bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000359 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000360 // Copy the exit map into Dist.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000361 for (const auto &I : Loop.Exits)
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000362 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
363 I.second.getMass()))
364 // Irreducible backedge.
365 return false;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000366
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000367 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000368}
369
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000370/// Compute the loop scale for a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000371void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000372 // Compute loop scale.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000373 LLVM_DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000374
Diego Novilloa354f482015-04-01 17:42:27 +0000375 // Infinite loops need special handling. If we give the back edge an infinite
376 // mass, they may saturate all the other scales in the function down to 1,
377 // making all the other region temperatures look exactly the same. Choose an
378 // arbitrary scale to avoid these issues.
379 //
380 // FIXME: An alternate way would be to select a symbolic scale which is later
381 // replaced to be the maximum of all computed scales plus 1. This would
382 // appropriately describe the loop as having a large scale, without skewing
383 // the final frequency computation.
Sanjay Patel0fb98802016-05-09 16:07:45 +0000384 const Scaled64 InfiniteLoopScale(1, 12);
Diego Novilloa354f482015-04-01 17:42:27 +0000385
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000386 // LoopScale == 1 / ExitMass
387 // ExitMass == HeadMass - BackedgeMass
Diego Novillo9a779622015-06-16 19:10:58 +0000388 BlockMass TotalBackedgeMass;
389 for (auto &Mass : Loop.BackedgeMass)
390 TotalBackedgeMass += Mass;
391 BlockMass ExitMass = BlockMass::getFull() - TotalBackedgeMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000392
Diego Novilloa354f482015-04-01 17:42:27 +0000393 // Block scale stores the inverse of the scale. If this is an infinite loop,
394 // its exit mass will be zero. In this case, use an arbitrary scale for the
395 // loop scale.
396 Loop.Scale =
Sanjay Patel0fb98802016-05-09 16:07:45 +0000397 ExitMass.isEmpty() ? InfiniteLoopScale : ExitMass.toScaled().inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000398
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000399 LLVM_DEBUG(dbgs() << " - exit-mass = " << ExitMass << " ("
400 << BlockMass::getFull() << " - " << TotalBackedgeMass
401 << ")\n"
402 << " - scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000403}
404
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000405/// Package up a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000406void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000407 LLVM_DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000408
409 // Clear the subloop exits to prevent quadratic memory usage.
410 for (const BlockNode &M : Loop.Nodes) {
411 if (auto *Loop = Working[M.Index].getPackagedLoop())
412 Loop->Exits.clear();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000413 LLVM_DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000414 }
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000415 Loop.IsPackaged = true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000416}
417
Diego Novillo9a779622015-06-16 19:10:58 +0000418#ifndef NDEBUG
419static void debugAssign(const BlockFrequencyInfoImplBase &BFI,
420 const DitheringDistributer &D, const BlockNode &T,
421 const BlockMass &M, const char *Desc) {
422 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
423 if (Desc)
424 dbgs() << " [" << Desc << "]";
425 if (T.isValid())
426 dbgs() << " to " << BFI.getBlockName(T);
427 dbgs() << "\n";
428}
429#endif
430
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000431void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000432 LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000433 Distribution &Dist) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000434 BlockMass Mass = Working[Source.Index].getMass();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000435 LLVM_DEBUG(dbgs() << " => mass: " << Mass << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000436
437 // Distribute mass to successors as laid out in Dist.
438 DitheringDistributer D(Dist, Mass);
439
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000440 for (const Weight &W : Dist.Weights) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000441 // Check for a local edge (non-backedge and non-exit).
442 BlockMass Taken = D.takeMass(W.Amount);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000443 if (W.Type == Weight::Local) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000444 Working[W.TargetNode.Index].getMass() += Taken;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000445 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000446 continue;
447 }
448
449 // Backedges and exits only make sense if we're processing a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000450 assert(OuterLoop && "backedge or exit outside of loop");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000451
452 // Check for a backedge.
453 if (W.Type == Weight::Backedge) {
Diego Novillo8c49a572015-06-17 16:28:22 +0000454 OuterLoop->BackedgeMass[OuterLoop->getHeaderIndex(W.TargetNode)] += Taken;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000455 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "back"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000456 continue;
457 }
458
459 // This must be an exit.
460 assert(W.Type == Weight::Exit);
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000461 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000462 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "exit"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000463 }
464}
465
466static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000467 const Scaled64 &Min, const Scaled64 &Max) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000468 // Scale the Factor to a size that creates integers. Ideally, integers would
469 // be scaled so that Max == UINT64_MAX so that they can be best
Diego Novilloa354f482015-04-01 17:42:27 +0000470 // differentiated. However, in the presence of large frequency values, small
471 // frequencies are scaled down to 1, making it impossible to differentiate
472 // small, unequal numbers. When the spread between Min and Max frequencies
473 // fits well within MaxBits, we make the scale be at least 8.
474 const unsigned MaxBits = 64;
475 const unsigned SpreadBits = (Max / Min).lg();
476 Scaled64 ScalingFactor;
477 if (SpreadBits <= MaxBits - 3) {
478 // If the values are small enough, make the scaling factor at least 8 to
479 // allow distinguishing small values.
480 ScalingFactor = Min.inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000481 ScalingFactor <<= 3;
Diego Novilloa354f482015-04-01 17:42:27 +0000482 } else {
483 // If the values need more than MaxBits to be represented, saturate small
484 // frequency values down to 1 by using a scaling factor that benefits large
485 // frequency values.
486 ScalingFactor = Scaled64(1, MaxBits) / Max;
487 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000488
489 // Translate the floats to integers.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000490 LLVM_DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
491 << ", factor = " << ScalingFactor << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000492 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000493 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000494 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000495 LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
496 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
497 << ", int = " << BFI.Freqs[Index].Integer << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000498 }
499}
500
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000501/// Unwrap a loop package.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000502///
503/// Visits all the members of a loop, adjusting their BlockData according to
504/// the loop's pseudo-node.
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000505static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000506 LLVM_DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
507 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
508 << "\n");
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000509 Loop.Scale *= Loop.Mass.toScaled();
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000510 Loop.IsPackaged = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000511 LLVM_DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000512
513 // Propagate the head scale through the loop. Since members are visited in
514 // RPO, the head scale will be updated by the loop scale first, and then the
515 // final head scale will be used for updated the rest of the members.
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000516 for (const BlockNode &N : Loop.Nodes) {
517 const auto &Working = BFI.Working[N.Index];
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000518 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
519 : BFI.Freqs[N.Index].Scaled;
520 Scaled64 New = Loop.Scale * F;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000521 LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => "
522 << New << "\n");
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000523 F = New;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000524 }
525}
526
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000527void BlockFrequencyInfoImplBase::unwrapLoops() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000528 // Set initial frequencies from loop-local masses.
529 for (size_t Index = 0; Index < Working.size(); ++Index)
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000530 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000531
Duncan P. N. Exon Smithda0b21c2014-04-25 04:38:23 +0000532 for (LoopData &Loop : Loops)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000533 unwrapLoop(*this, Loop);
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000534}
535
536void BlockFrequencyInfoImplBase::finalizeMetrics() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000537 // Unwrap loop packages in reverse post-order, tracking min and max
538 // frequencies.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000539 auto Min = Scaled64::getLargest();
540 auto Max = Scaled64::getZero();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000541 for (size_t Index = 0; Index < Working.size(); ++Index) {
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000542 // Update min/max scale.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000543 Min = std::min(Min, Freqs[Index].Scaled);
544 Max = std::max(Max, Freqs[Index].Scaled);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000545 }
546
547 // Convert to integers.
548 convertFloatingToInteger(*this, Min, Max);
549
550 // Clean up data structures.
551 cleanup(*this);
552
553 // Print out the final stats.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000554 LLVM_DEBUG(dump());
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000555}
556
557BlockFrequency
558BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
Hiroshi Yamauchi803dd6f2020-02-03 12:22:03 -0800559 if (!Node.isValid()) {
560#ifndef NDEBUG
561 if (CheckBFIUnknownBlockQueries) {
562 SmallString<256> Msg;
563 raw_svector_ostream OS(Msg);
564 OS << "*** Detected BFI query for unknown block " << getBlockName(Node);
565 report_fatal_error(OS.str());
566 }
567#endif
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000568 return 0;
Hiroshi Yamauchi803dd6f2020-02-03 12:22:03 -0800569 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000570 return Freqs[Node.Index].Integer;
571}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000572
Xinliang David Lib12b3532016-06-22 17:12:12 +0000573Optional<uint64_t>
574BlockFrequencyInfoImplBase::getBlockProfileCount(const Function &F,
Xinliang David Li499c80b2019-04-24 19:51:16 +0000575 const BlockNode &Node,
576 bool AllowSynthetic) const {
577 return getProfileCountFromFreq(F, getBlockFreq(Node).getFrequency(),
578 AllowSynthetic);
Sean Silvaf8015752016-08-02 02:15:45 +0000579}
580
581Optional<uint64_t>
582BlockFrequencyInfoImplBase::getProfileCountFromFreq(const Function &F,
Xinliang David Li499c80b2019-04-24 19:51:16 +0000583 uint64_t Freq,
584 bool AllowSynthetic) const {
585 auto EntryCount = F.getEntryCount(AllowSynthetic);
Xinliang David Lib12b3532016-06-22 17:12:12 +0000586 if (!EntryCount)
587 return None;
588 // Use 128 bit APInt to do the arithmetic to avoid overflow.
Easwaran Ramane5b8de22018-01-17 22:24:23 +0000589 APInt BlockCount(128, EntryCount.getCount());
Sean Silvaf8015752016-08-02 02:15:45 +0000590 APInt BlockFreq(128, Freq);
Xinliang David Lib12b3532016-06-22 17:12:12 +0000591 APInt EntryFreq(128, getEntryFreq());
592 BlockCount *= BlockFreq;
Easwaran Ramanaca738b2018-08-16 00:26:59 +0000593 // Rounded division of BlockCount by EntryFreq. Since EntryFreq is unsigned
594 // lshr by 1 gives EntryFreq/2.
595 BlockCount = (BlockCount + EntryFreq.lshr(1)).udiv(EntryFreq);
Xinliang David Lib12b3532016-06-22 17:12:12 +0000596 return BlockCount.getLimitedValue();
597}
598
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000599bool
600BlockFrequencyInfoImplBase::isIrrLoopHeader(const BlockNode &Node) {
601 if (!Node.isValid())
602 return false;
603 return IsIrrLoopHeader.test(Node.Index);
604}
605
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000606Scaled64
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000607BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
608 if (!Node.isValid())
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000609 return Scaled64::getZero();
610 return Freqs[Node.Index].Scaled;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000611}
612
Manman Ren72d44b12015-10-15 14:59:40 +0000613void BlockFrequencyInfoImplBase::setBlockFreq(const BlockNode &Node,
614 uint64_t Freq) {
615 assert(Node.isValid() && "Expected valid node");
616 assert(Node.Index < Freqs.size() && "Expected legal index");
617 Freqs[Node.Index].Integer = Freq;
618}
619
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000620std::string
621BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000622 return {};
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000623}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000624
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000625std::string
626BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
627 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
628}
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000629
630raw_ostream &
631BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
632 const BlockNode &Node) const {
633 return OS << getFloatingBlockFreq(Node);
634}
635
636raw_ostream &
637BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
638 const BlockFrequency &Freq) const {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000639 Scaled64 Block(Freq.getFrequency(), 0);
640 Scaled64 Entry(getEntryFreq(), 0);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000641
642 return OS << Block / Entry;
643}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000644
645void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
646 Start = OuterLoop.getHeader();
647 Nodes.reserve(OuterLoop.Nodes.size());
648 for (auto N : OuterLoop.Nodes)
649 addNode(N);
650 indexNodes();
651}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000652
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000653void IrreducibleGraph::addNodesInFunction() {
654 Start = 0;
655 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
656 if (!BFI.Working[Index].isPackaged())
657 addNode(Index);
658 indexNodes();
659}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000660
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000661void IrreducibleGraph::indexNodes() {
662 for (auto &I : Nodes)
663 Lookup[I.Node.Index] = &I;
664}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000665
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000666void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
667 const BFIBase::LoopData *OuterLoop) {
668 if (OuterLoop && OuterLoop->isHeader(Succ))
669 return;
670 auto L = Lookup.find(Succ.Index);
671 if (L == Lookup.end())
672 return;
673 IrrNode &SuccIrr = *L->second;
674 Irr.Edges.push_back(&SuccIrr);
675 SuccIrr.Edges.push_front(&Irr);
676 ++SuccIrr.NumIn;
677}
678
679namespace llvm {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000680
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000681template <> struct GraphTraits<IrreducibleGraph> {
682 using GraphT = bfi_detail::IrreducibleGraph;
683 using NodeRef = const GraphT::IrrNode *;
684 using ChildIteratorType = GraphT::IrrNode::iterator;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000685
Tim Shenf2187ed2016-08-22 21:09:30 +0000686 static NodeRef getEntryNode(const GraphT &G) { return G.StartIrr; }
687 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
688 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000689};
Eugene Zelenko38c02bc2017-07-21 21:37:46 +0000690
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000691} // end namespace llvm
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000692
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000693/// Find extra irreducible headers.
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000694///
695/// Find entry blocks and other blocks with backedges, which exist when \c G
696/// contains irreducible sub-SCCs.
697static void findIrreducibleHeaders(
698 const BlockFrequencyInfoImplBase &BFI,
699 const IrreducibleGraph &G,
700 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
701 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
702 // Map from nodes in the SCC to whether it's an entry block.
703 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
704
705 // InSCC also acts the set of nodes in the graph. Seed it.
706 for (const auto *I : SCC)
707 InSCC[I] = false;
708
709 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
710 auto &Irr = *I->first;
711 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
712 if (InSCC.count(P))
713 continue;
714
715 // This is an entry block.
716 I->second = true;
717 Headers.push_back(Irr.Node);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000718 LLVM_DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node)
719 << "\n");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000720 break;
721 }
722 }
Duncan P. N. Exon Smitha7a90a22014-10-06 17:42:00 +0000723 assert(Headers.size() >= 2 &&
724 "Expected irreducible CFG; -loop-info is likely invalid");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000725 if (Headers.size() == InSCC.size()) {
726 // Every block is a header.
Fangrui Song0cac7262018-09-27 02:13:45 +0000727 llvm::sort(Headers);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000728 return;
729 }
730
731 // Look for extra headers from irreducible sub-SCCs.
732 for (const auto &I : InSCC) {
733 // Entry blocks are already headers.
734 if (I.second)
735 continue;
736
737 auto &Irr = *I.first;
738 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
739 // Skip forward edges.
740 if (P->Node < Irr.Node)
741 continue;
742
743 // Skip predecessors from entry blocks. These can have inverted
744 // ordering.
745 if (InSCC.lookup(P))
746 continue;
747
748 // Store the extra header.
749 Headers.push_back(Irr.Node);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000750 LLVM_DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node)
751 << "\n");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000752 break;
753 }
754 if (Headers.back() == Irr.Node)
755 // Added this as a header.
756 continue;
757
758 // This is not a header.
759 Others.push_back(Irr.Node);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000760 LLVM_DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000761 }
Fangrui Song0cac7262018-09-27 02:13:45 +0000762 llvm::sort(Headers);
763 llvm::sort(Others);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000764}
765
766static void createIrreducibleLoop(
767 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
768 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
769 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
770 // Translate the SCC into RPO.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000771 LLVM_DEBUG(dbgs() << " - found-scc\n");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000772
773 LoopData::NodeList Headers;
774 LoopData::NodeList Others;
775 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
776
777 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
778 Headers.end(), Others.begin(), Others.end());
779
780 // Update loop hierarchy.
781 for (const auto &N : Loop->Nodes)
782 if (BFI.Working[N.Index].isLoopHeader())
783 BFI.Working[N.Index].Loop->Parent = &*Loop;
784 else
785 BFI.Working[N.Index].Loop = &*Loop;
786}
787
788iterator_range<std::list<LoopData>::iterator>
789BlockFrequencyInfoImplBase::analyzeIrreducible(
790 const IrreducibleGraph &G, LoopData *OuterLoop,
791 std::list<LoopData>::iterator Insert) {
792 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
793 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
794
795 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
796 if (I->size() < 2)
797 continue;
798
799 // Translate the SCC into RPO.
800 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
801 }
802
803 if (OuterLoop)
804 return make_range(std::next(Prev), Insert);
805 return make_range(Loops.begin(), Insert);
806}
807
808void
809BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
810 OuterLoop.Exits.clear();
Diego Novillo9a779622015-06-16 19:10:58 +0000811 for (auto &Mass : OuterLoop.BackedgeMass)
812 Mass = BlockMass::getEmpty();
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000813 auto O = OuterLoop.Nodes.begin() + 1;
814 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
815 if (!Working[I->Index].isPackaged())
816 *O++ = *I;
817 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
818}
Diego Novillo9a779622015-06-16 19:10:58 +0000819
820void BlockFrequencyInfoImplBase::adjustLoopHeaderMass(LoopData &Loop) {
821 assert(Loop.isIrreducible() && "this only makes sense on irreducible loops");
822
823 // Since the loop has more than one header block, the mass flowing back into
824 // each header will be different. Adjust the mass in each header loop to
825 // reflect the masses flowing through back edges.
826 //
827 // To do this, we distribute the initial mass using the backedge masses
828 // as weights for the distribution.
829 BlockMass LoopMass = BlockMass::getFull();
830 Distribution Dist;
831
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000832 LLVM_DEBUG(dbgs() << "adjust-loop-header-mass:\n");
Diego Novillo9a779622015-06-16 19:10:58 +0000833 for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
834 auto &HeaderNode = Loop.Nodes[H];
Diego Novillo8c49a572015-06-17 16:28:22 +0000835 auto &BackedgeMass = Loop.BackedgeMass[Loop.getHeaderIndex(HeaderNode)];
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000836 LLVM_DEBUG(dbgs() << " - Add back edge mass for node "
837 << getBlockName(HeaderNode) << ": " << BackedgeMass
838 << "\n");
Diego Novillof9aa39b2015-09-08 19:22:17 +0000839 if (BackedgeMass.getMass() > 0)
840 Dist.addLocal(HeaderNode, BackedgeMass.getMass());
841 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000842 LLVM_DEBUG(dbgs() << " Nothing added. Back edge mass is zero\n");
Diego Novillo9a779622015-06-16 19:10:58 +0000843 }
844
845 DitheringDistributer D(Dist, LoopMass);
846
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000847 LLVM_DEBUG(dbgs() << " Distribute loop mass " << LoopMass
848 << " to headers using above weights\n");
Diego Novillo9a779622015-06-16 19:10:58 +0000849 for (const Weight &W : Dist.Weights) {
850 BlockMass Taken = D.takeMass(W.Amount);
851 assert(W.Type == Weight::Local && "all weights should be local");
852 Working[W.TargetNode.Index].getMass() = Taken;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000853 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
Diego Novillo9a779622015-06-16 19:10:58 +0000854 }
855}
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000856
857void BlockFrequencyInfoImplBase::distributeIrrLoopHeaderMass(Distribution &Dist) {
858 BlockMass LoopMass = BlockMass::getFull();
859 DitheringDistributer D(Dist, LoopMass);
860 for (const Weight &W : Dist.Weights) {
861 BlockMass Taken = D.takeMass(W.Amount);
862 assert(W.Type == Weight::Local && "all weights should be local");
863 Working[W.TargetNode.Index].getMass() = Taken;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000864 LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000865 }
866}