blob: 06b8acd9c75f26cfc10012116b91202e31f41d2a [file] [log] [blame]
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +00001//===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Loops should be simplified before this analysis.
11//
12//===----------------------------------------------------------------------===//
13
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000014#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Duncan P. N. Exon Smith87c40fd2014-05-06 01:57:42 +000015#include "llvm/ADT/SCCIterator.h"
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000016#include "llvm/Support/raw_ostream.h"
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000017
18using namespace llvm;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +000019using namespace llvm::bfi_detail;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000020
Chandler Carruth1b9dde02014-04-22 02:02:50 +000021#define DEBUG_TYPE "block-freq"
22
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +000023ScaledNumber<uint64_t> BlockMass::toScaled() const {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000024 if (isFull())
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000025 return ScaledNumber<uint64_t>(1, 0);
26 return ScaledNumber<uint64_t>(getMass() + 1, -64);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000027}
28
29void BlockMass::dump() const { print(dbgs()); }
30
31static char getHexDigit(int N) {
32 assert(N < 16);
33 if (N < 10)
34 return '0' + N;
35 return 'a' + N - 10;
36}
37raw_ostream &BlockMass::print(raw_ostream &OS) const {
38 for (int Digits = 0; Digits < 16; ++Digits)
39 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
40 return OS;
41}
42
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000043namespace {
44
45typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
46typedef BlockFrequencyInfoImplBase::Distribution Distribution;
47typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +000048typedef BlockFrequencyInfoImplBase::Scaled64 Scaled64;
Duncan P. N. Exon Smithcc88ebf2014-04-22 03:31:31 +000049typedef BlockFrequencyInfoImplBase::LoopData LoopData;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000050typedef BlockFrequencyInfoImplBase::Weight Weight;
51typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
52
53/// \brief Dithering mass distributer.
54///
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.
58///
59/// The distribution algorithm follows.
60///
61/// 1. Initialize by saving the sum of the weights in \a RemWeight and the
62/// mass to distribute in \a RemMass.
63///
64/// 2. For each portion:
65///
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.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000071struct DitheringDistributer {
72 uint32_t RemWeight;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000073 BlockMass RemMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000074
75 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
76
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000077 BlockMass takeMass(uint32_t Weight);
78};
Duncan P. N. Exon Smithb5650e52014-07-11 23:56:50 +000079
80} // end namespace
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000081
82DitheringDistributer::DitheringDistributer(Distribution &Dist,
83 const BlockMass &Mass) {
84 Dist.normalize();
85 RemWeight = Dist.Total;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000086 RemMass = Mass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000087}
88
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000089BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
90 assert(Weight && "invalid weight");
91 assert(Weight <= RemWeight);
92 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
93
94 // Decrement totals (dither).
95 RemWeight -= Weight;
96 RemMass -= Mass;
97 return Mass;
98}
99
100void 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;
104
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;
109
110 // Update the total.
111 Total = NewTotal;
112
113 // Save the weight.
Duncan P. N. Exon Smith60755102014-07-12 00:26:00 +0000114 Weights.push_back(Weight(Type, Node, Amount));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000115}
116
117static void combineWeight(Weight &W, const Weight &OtherW) {
118 assert(OtherW.TargetNode.isValid());
119 if (!W.Amount) {
120 W = OtherW;
121 return;
122 }
123 assert(W.Type == OtherW.Type);
124 assert(W.TargetNode == OtherW.TargetNode);
Duncan P. N. Exon Smithebf76262014-04-25 04:38:40 +0000125 assert(W.Amount < W.Amount + OtherW.Amount && "Unexpected overflow");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000126 W.Amount += OtherW.Amount;
127}
128static void combineWeightsBySorting(WeightList &Weights) {
129 // Sort so edges to the same node are adjacent.
130 std::sort(Weights.begin(), Weights.end(),
131 [](const Weight &L,
132 const Weight &R) { return L.TargetNode < R.TargetNode; });
133
134 // Combine adjacent edges.
135 WeightList::iterator O = Weights.begin();
136 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
137 ++O, (I = L)) {
138 *O = *I;
139
140 // Find the adjacent weights to the same node.
141 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
142 combineWeight(*O, *L);
143 }
144
145 // Erase extra entries.
146 Weights.erase(O, Weights.end());
147 return;
148}
149static 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);
155
156 // Check whether anything changed.
157 if (Weights.size() == Combined.size())
158 return;
159
160 // Fill in the new weights.
161 Weights.clear();
162 Weights.reserve(Combined.size());
163 for (const auto &I : Combined)
164 Weights.push_back(I.second);
165}
166static void combineWeights(WeightList &Weights) {
167 // Use a hash table for many successors to keep this linear.
168 if (Weights.size() > 128) {
169 combineWeightsByHashing(Weights);
170 return;
171 }
172
173 combineWeightsBySorting(Weights);
174}
175static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
176 assert(Shift >= 0);
177 assert(Shift < 64);
178 if (!Shift)
179 return N;
180 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
181}
182void Distribution::normalize() {
183 // Early exit for termination nodes.
184 if (Weights.empty())
185 return;
186
187 // Only bother if there are multiple successors.
188 if (Weights.size() > 1)
189 combineWeights(Weights);
190
191 // Early exit when combined into a single successor.
192 if (Weights.size() == 1) {
193 Total = 1;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000194 Weights.front().Amount = 1;
195 return;
196 }
197
198 // Determine how much to shift right so that the total fits into 32-bits.
199 //
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.
202 int Shift = 0;
203 if (DidOverflow)
204 Shift = 33;
205 else if (Total > UINT32_MAX)
206 Shift = 33 - countLeadingZeros(Total);
207
208 // Early exit if nothing needs to be scaled.
209 if (!Shift)
210 return;
211
212 // Recompute the total through accumulation (rather than shifting it) so that
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000213 // it's accurate after shifting.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000214 Total = 0;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000215
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);
223
224 // Update the total.
225 Total += W.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000226 }
227 assert(Total <= UINT32_MAX);
228}
229
230void BlockFrequencyInfoImplBase::clear() {
Duncan P. N. Exon Smithdc2d66e2014-04-22 03:31:34 +0000231 // 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);
Duncan P. N. Exon Smithfc7dc932014-04-25 04:30:06 +0000235 Loops.clear();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000236}
237
238/// \brief Clear all memory not needed downstream.
239///
240/// Releases all memory not used downstream. In particular, saves Freqs.
241static void cleanup(BlockFrequencyInfoImplBase &BFI) {
242 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
243 BFI.clear();
244 BFI.Freqs = std::move(SavedFreqs);
245}
246
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000247bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000248 const LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000249 const BlockNode &Pred,
250 const BlockNode &Succ,
251 uint64_t Weight) {
252 if (!Weight)
253 Weight = 1;
254
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000255 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
256 return OuterLoop && OuterLoop->isHeader(Node);
257 };
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000258
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000259 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
260
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000261#ifndef NDEBUG
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000262 auto debugSuccessor = [&](const char *Type) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000263 dbgs() << " =>"
264 << " [" << Type << "] weight = " << Weight;
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000265 if (!isLoopHeader(Resolved))
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000266 dbgs() << ", succ = " << getBlockName(Succ);
267 if (Resolved != Succ)
268 dbgs() << ", resolved = " << getBlockName(Resolved);
269 dbgs() << "\n";
270 };
271 (void)debugSuccessor;
272#endif
273
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000274 if (isLoopHeader(Resolved)) {
275 DEBUG(debugSuccessor("backedge"));
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000276 Dist.addBackedge(OuterLoop->getHeader(), Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000277 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000278 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000279
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000280 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000281 DEBUG(debugSuccessor(" exit "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000282 Dist.addExit(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000283 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000284 }
285
Duncan P. N. Exon Smithb3380ea2014-04-22 03:31:53 +0000286 if (Resolved < Pred) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000287 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");
291
292 // Irreducible backedge. Abort.
293 DEBUG(debugSuccessor("abort!!!"));
294 return false;
295 }
296
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");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000302 }
303
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000304 DEBUG(debugSuccessor(" local "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000305 Dist.addLocal(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000306 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000307}
308
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000309bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000310 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000311 // Copy the exit map into Dist.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000312 for (const auto &I : Loop.Exits)
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000313 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
314 I.second.getMass()))
315 // Irreducible backedge.
316 return false;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000317
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000318 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000319}
320
321/// \brief Get the maximum allowed loop scale.
322///
Duncan P. N. Exon Smith254689f2014-04-21 18:31:58 +0000323/// Gives the maximum number of estimated iterations allowed for a loop. Very
324/// large numbers cause problems downstream (even within 64-bits).
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000325static Scaled64 getMaxLoopScale() { return Scaled64(1, 12); }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000326
327/// \brief Compute the loop scale for a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000328void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000329 // Compute loop scale.
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000330 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000331
332 // LoopScale == 1 / ExitMass
333 // ExitMass == HeadMass - BackedgeMass
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000334 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000335
336 // Block scale stores the inverse of the scale.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000337 Loop.Scale = ExitMass.toScaled().inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000338
339 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000340 << " - " << Loop.BackedgeMass << ")\n"
341 << " - scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000342
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000343 if (Loop.Scale > getMaxLoopScale()) {
344 Loop.Scale = getMaxLoopScale();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000345 DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
346 }
347}
348
349/// \brief Package up a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000350void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000351 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
352
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())
356 Loop->Exits.clear();
357 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
358 }
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000359 Loop.IsPackaged = true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000360}
361
362void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000363 LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000364 Distribution &Dist) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000365 BlockMass Mass = Working[Source.Index].getMass();
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000366 DEBUG(dbgs() << " => mass: " << Mass << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000367
368 // Distribute mass to successors as laid out in Dist.
369 DitheringDistributer D(Dist, Mass);
370
371#ifndef NDEBUG
372 auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
373 const char *Desc) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000374 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000375 if (Desc)
376 dbgs() << " [" << Desc << "]";
377 if (T.isValid())
378 dbgs() << " to " << getBlockName(T);
379 dbgs() << "\n";
380 };
381 (void)debugAssign;
382#endif
383
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000384 for (const Weight &W : Dist.Weights) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000385 // Check for a local edge (non-backedge and non-exit).
386 BlockMass Taken = D.takeMass(W.Amount);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000387 if (W.Type == Weight::Local) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000388 Working[W.TargetNode.Index].getMass() += Taken;
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000389 DEBUG(debugAssign(W.TargetNode, Taken, nullptr));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000390 continue;
391 }
392
393 // Backedges and exits only make sense if we're processing a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000394 assert(OuterLoop && "backedge or exit outside of loop");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000395
396 // Check for a backedge.
397 if (W.Type == Weight::Backedge) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000398 OuterLoop->BackedgeMass += Taken;
399 DEBUG(debugAssign(BlockNode(), Taken, "back"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000400 continue;
401 }
402
403 // This must be an exit.
404 assert(W.Type == Weight::Exit);
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000405 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
406 DEBUG(debugAssign(W.TargetNode, Taken, "exit"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000407 }
408}
409
410static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000411 const Scaled64 &Min, const Scaled64 &Max) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000412 // 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.
417 //
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000418 // TODO: fix issues downstream so that ScalingFactor can be
419 // Scaled64(1,64)/Max.
420 Scaled64 ScalingFactor = Min.inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000421 if ((Max / Min).lg() < 60)
422 ScalingFactor <<= 3;
423
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) {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000428 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000429 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
430 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000431 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000432 << ", int = " << BFI.Freqs[Index].Integer << "\n");
433 }
434}
435
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000436/// \brief Unwrap a loop package.
437///
438/// Visits all the members of a loop, adjusting their BlockData according to
439/// the loop's pseudo-node.
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000440static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000441 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000442 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
443 << "\n");
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000444 Loop.Scale *= Loop.Mass.toScaled();
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000445 Loop.IsPackaged = false;
Duncan P. N. Exon Smith3f086782014-04-25 04:38:32 +0000446 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000447
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.
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000451 for (const BlockNode &N : Loop.Nodes) {
452 const auto &Working = BFI.Working[N.Index];
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000453 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
454 : BFI.Freqs[N.Index].Scaled;
455 Scaled64 New = Loop.Scale * F;
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000456 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
457 << "\n");
458 F = New;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000459 }
460}
461
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000462void BlockFrequencyInfoImplBase::unwrapLoops() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000463 // Set initial frequencies from loop-local masses.
464 for (size_t Index = 0; Index < Working.size(); ++Index)
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000465 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000466
Duncan P. N. Exon Smithda0b21c2014-04-25 04:38:23 +0000467 for (LoopData &Loop : Loops)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000468 unwrapLoop(*this, Loop);
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000469}
470
471void BlockFrequencyInfoImplBase::finalizeMetrics() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000472 // Unwrap loop packages in reverse post-order, tracking min and max
473 // frequencies.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000474 auto Min = Scaled64::getLargest();
475 auto Max = Scaled64::getZero();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000476 for (size_t Index = 0; Index < Working.size(); ++Index) {
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000477 // Update min/max scale.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000478 Min = std::min(Min, Freqs[Index].Scaled);
479 Max = std::max(Max, Freqs[Index].Scaled);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000480 }
481
482 // Convert to integers.
483 convertFloatingToInteger(*this, Min, Max);
484
485 // Clean up data structures.
486 cleanup(*this);
487
488 // Print out the final stats.
489 DEBUG(dump());
490}
491
492BlockFrequency
493BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
494 if (!Node.isValid())
495 return 0;
496 return Freqs[Node.Index].Integer;
497}
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000498Scaled64
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000499BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
500 if (!Node.isValid())
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000501 return Scaled64::getZero();
502 return Freqs[Node.Index].Scaled;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000503}
504
505std::string
506BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
507 return std::string();
508}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000509std::string
510BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
511 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
512}
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000513
514raw_ostream &
515BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
516 const BlockNode &Node) const {
517 return OS << getFloatingBlockFreq(Node);
518}
519
520raw_ostream &
521BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
522 const BlockFrequency &Freq) const {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000523 Scaled64 Block(Freq.getFrequency(), 0);
524 Scaled64 Entry(getEntryFreq(), 0);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000525
526 return OS << Block / Entry;
527}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000528
529void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
530 Start = OuterLoop.getHeader();
531 Nodes.reserve(OuterLoop.Nodes.size());
532 for (auto N : OuterLoop.Nodes)
533 addNode(N);
534 indexNodes();
535}
536void IrreducibleGraph::addNodesInFunction() {
537 Start = 0;
538 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
539 if (!BFI.Working[Index].isPackaged())
540 addNode(Index);
541 indexNodes();
542}
543void IrreducibleGraph::indexNodes() {
544 for (auto &I : Nodes)
545 Lookup[I.Node.Index] = &I;
546}
547void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
548 const BFIBase::LoopData *OuterLoop) {
549 if (OuterLoop && OuterLoop->isHeader(Succ))
550 return;
551 auto L = Lookup.find(Succ.Index);
552 if (L == Lookup.end())
553 return;
554 IrrNode &SuccIrr = *L->second;
555 Irr.Edges.push_back(&SuccIrr);
556 SuccIrr.Edges.push_front(&Irr);
557 ++SuccIrr.NumIn;
558}
559
560namespace llvm {
561template <> struct GraphTraits<IrreducibleGraph> {
562 typedef bfi_detail::IrreducibleGraph GraphT;
563
Duncan P. N. Exon Smith295b5e72014-04-28 20:22:29 +0000564 typedef const GraphT::IrrNode NodeType;
565 typedef GraphT::IrrNode::iterator ChildIteratorType;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000566
567 static const NodeType *getEntryNode(const GraphT &G) {
568 return G.StartIrr;
569 }
570 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
571 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
572};
573}
574
575/// \brief Find extra irreducible headers.
576///
577/// Find entry blocks and other blocks with backedges, which exist when \c G
578/// contains irreducible sub-SCCs.
579static 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;
586
587 // InSCC also acts the set of nodes in the graph. Seed it.
588 for (const auto *I : SCC)
589 InSCC[I] = false;
590
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())) {
594 if (InSCC.count(P))
595 continue;
596
597 // This is an entry block.
598 I->second = true;
599 Headers.push_back(Irr.Node);
600 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
601 break;
602 }
603 }
Duncan P. N. Exon Smitha7a90a22014-10-06 17:42:00 +0000604 assert(Headers.size() >= 2 &&
605 "Expected irreducible CFG; -loop-info is likely invalid");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000606 if (Headers.size() == InSCC.size()) {
607 // Every block is a header.
608 std::sort(Headers.begin(), Headers.end());
609 return;
610 }
611
612 // Look for extra headers from irreducible sub-SCCs.
613 for (const auto &I : InSCC) {
614 // Entry blocks are already headers.
615 if (I.second)
616 continue;
617
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)
622 continue;
623
624 // Skip predecessors from entry blocks. These can have inverted
625 // ordering.
626 if (InSCC.lookup(P))
627 continue;
628
629 // Store the extra header.
630 Headers.push_back(Irr.Node);
631 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
632 break;
633 }
634 if (Headers.back() == Irr.Node)
635 // Added this as a header.
636 continue;
637
638 // This is not a header.
639 Others.push_back(Irr.Node);
640 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
641 }
642 std::sort(Headers.begin(), Headers.end());
643 std::sort(Others.begin(), Others.end());
644}
645
646static 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");
652
653 LoopData::NodeList Headers;
654 LoopData::NodeList Others;
655 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
656
657 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
658 Headers.end(), Others.begin(), Others.end());
659
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;
664 else
665 BFI.Working[N.Index].Loop = &*Loop;
666}
667
668iterator_range<std::list<LoopData>::iterator>
669BlockFrequencyInfoImplBase::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();
674
675 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
676 if (I->size() < 2)
677 continue;
678
679 // Translate the SCC into RPO.
680 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
681 }
682
683 if (OuterLoop)
684 return make_range(std::next(Prev), Insert);
685 return make_range(Loops.begin(), Insert);
686}
687
688void
689BlockFrequencyInfoImplBase::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())
695 *O++ = *I;
696 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
697}