blob: d132c23b0f6e4e52834ecc604816e7e4ea502039 [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"
17#include <deque>
18
19using namespace llvm;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +000020using namespace llvm::bfi_detail;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000021
Chandler Carruth1b9dde02014-04-22 02:02:50 +000022#define DEBUG_TYPE "block-freq"
23
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +000024ScaledNumber<uint64_t> BlockMass::toScaled() const {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000025 if (isFull())
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000026 return ScaledNumber<uint64_t>(1, 0);
27 return ScaledNumber<uint64_t>(getMass() + 1, -64);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000028}
29
30void BlockMass::dump() const { print(dbgs()); }
31
32static char getHexDigit(int N) {
33 assert(N < 16);
34 if (N < 10)
35 return '0' + N;
36 return 'a' + N - 10;
37}
38raw_ostream &BlockMass::print(raw_ostream &OS) const {
39 for (int Digits = 0; Digits < 16; ++Digits)
40 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
41 return OS;
42}
43
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000044namespace {
45
46typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
47typedef BlockFrequencyInfoImplBase::Distribution Distribution;
48typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +000049typedef BlockFrequencyInfoImplBase::Scaled64 Scaled64;
Duncan P. N. Exon Smithcc88ebf2014-04-22 03:31:31 +000050typedef BlockFrequencyInfoImplBase::LoopData LoopData;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000051typedef BlockFrequencyInfoImplBase::Weight Weight;
52typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
53
54/// \brief Dithering mass distributer.
55///
56/// This class splits up a single mass into portions by weight, dithering to
57/// spread out error. No mass is lost. The dithering precision depends on the
58/// precision of the product of \a BlockMass and \a BranchProbability.
59///
60/// The distribution algorithm follows.
61///
62/// 1. Initialize by saving the sum of the weights in \a RemWeight and the
63/// mass to distribute in \a RemMass.
64///
65/// 2. For each portion:
66///
67/// 1. Construct a branch probability, P, as the portion's weight divided
68/// by the current value of \a RemWeight.
69/// 2. Calculate the portion's mass as \a RemMass times P.
70/// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
71/// the current portion's weight and mass.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000072struct DitheringDistributer {
73 uint32_t RemWeight;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000074 BlockMass RemMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000075
76 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
77
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000078 BlockMass takeMass(uint32_t Weight);
79};
Duncan P. N. Exon Smithb5650e52014-07-11 23:56:50 +000080
81} // end namespace
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000082
83DitheringDistributer::DitheringDistributer(Distribution &Dist,
84 const BlockMass &Mass) {
85 Dist.normalize();
86 RemWeight = Dist.Total;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000087 RemMass = Mass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000088}
89
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000090BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
91 assert(Weight && "invalid weight");
92 assert(Weight <= RemWeight);
93 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
94
95 // Decrement totals (dither).
96 RemWeight -= Weight;
97 RemMass -= Mass;
98 return Mass;
99}
100
101void Distribution::add(const BlockNode &Node, uint64_t Amount,
102 Weight::DistType Type) {
103 assert(Amount && "invalid weight of 0");
104 uint64_t NewTotal = Total + Amount;
105
106 // Check for overflow. It should be impossible to overflow twice.
107 bool IsOverflow = NewTotal < Total;
108 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
109 DidOverflow |= IsOverflow;
110
111 // Update the total.
112 Total = NewTotal;
113
114 // Save the weight.
Duncan P. N. Exon Smith60755102014-07-12 00:26:00 +0000115 Weights.push_back(Weight(Type, Node, Amount));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000116}
117
118static void combineWeight(Weight &W, const Weight &OtherW) {
119 assert(OtherW.TargetNode.isValid());
120 if (!W.Amount) {
121 W = OtherW;
122 return;
123 }
124 assert(W.Type == OtherW.Type);
125 assert(W.TargetNode == OtherW.TargetNode);
Duncan P. N. Exon Smithebf76262014-04-25 04:38:40 +0000126 assert(W.Amount < W.Amount + OtherW.Amount && "Unexpected overflow");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000127 W.Amount += OtherW.Amount;
128}
129static void combineWeightsBySorting(WeightList &Weights) {
130 // Sort so edges to the same node are adjacent.
131 std::sort(Weights.begin(), Weights.end(),
132 [](const Weight &L,
133 const Weight &R) { return L.TargetNode < R.TargetNode; });
134
135 // Combine adjacent edges.
136 WeightList::iterator O = Weights.begin();
137 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
138 ++O, (I = L)) {
139 *O = *I;
140
141 // Find the adjacent weights to the same node.
142 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
143 combineWeight(*O, *L);
144 }
145
146 // Erase extra entries.
147 Weights.erase(O, Weights.end());
148 return;
149}
150static void combineWeightsByHashing(WeightList &Weights) {
151 // Collect weights into a DenseMap.
152 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
153 HashTable Combined(NextPowerOf2(2 * Weights.size()));
154 for (const Weight &W : Weights)
155 combineWeight(Combined[W.TargetNode.Index], W);
156
157 // Check whether anything changed.
158 if (Weights.size() == Combined.size())
159 return;
160
161 // Fill in the new weights.
162 Weights.clear();
163 Weights.reserve(Combined.size());
164 for (const auto &I : Combined)
165 Weights.push_back(I.second);
166}
167static void combineWeights(WeightList &Weights) {
168 // Use a hash table for many successors to keep this linear.
169 if (Weights.size() > 128) {
170 combineWeightsByHashing(Weights);
171 return;
172 }
173
174 combineWeightsBySorting(Weights);
175}
176static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
177 assert(Shift >= 0);
178 assert(Shift < 64);
179 if (!Shift)
180 return N;
181 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
182}
183void Distribution::normalize() {
184 // Early exit for termination nodes.
185 if (Weights.empty())
186 return;
187
188 // Only bother if there are multiple successors.
189 if (Weights.size() > 1)
190 combineWeights(Weights);
191
192 // Early exit when combined into a single successor.
193 if (Weights.size() == 1) {
194 Total = 1;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000195 Weights.front().Amount = 1;
196 return;
197 }
198
199 // Determine how much to shift right so that the total fits into 32-bits.
200 //
201 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
202 // for each weight can cause a 32-bit overflow.
203 int Shift = 0;
204 if (DidOverflow)
205 Shift = 33;
206 else if (Total > UINT32_MAX)
207 Shift = 33 - countLeadingZeros(Total);
208
209 // Early exit if nothing needs to be scaled.
210 if (!Shift)
211 return;
212
213 // Recompute the total through accumulation (rather than shifting it) so that
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000214 // it's accurate after shifting.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000215 Total = 0;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000216
217 // Sum the weights to each node and shift right if necessary.
218 for (Weight &W : Weights) {
219 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
220 // can round here without concern about overflow.
221 assert(W.TargetNode.isValid());
222 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
223 assert(W.Amount <= UINT32_MAX);
224
225 // Update the total.
226 Total += W.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000227 }
228 assert(Total <= UINT32_MAX);
229}
230
231void BlockFrequencyInfoImplBase::clear() {
Duncan P. N. Exon Smithdc2d66e2014-04-22 03:31:34 +0000232 // Swap with a default-constructed std::vector, since std::vector<>::clear()
233 // does not actually clear heap storage.
234 std::vector<FrequencyData>().swap(Freqs);
235 std::vector<WorkingData>().swap(Working);
Duncan P. N. Exon Smithfc7dc932014-04-25 04:30:06 +0000236 Loops.clear();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000237}
238
239/// \brief Clear all memory not needed downstream.
240///
241/// Releases all memory not used downstream. In particular, saves Freqs.
242static void cleanup(BlockFrequencyInfoImplBase &BFI) {
243 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
244 BFI.clear();
245 BFI.Freqs = std::move(SavedFreqs);
246}
247
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000248bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000249 const LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000250 const BlockNode &Pred,
251 const BlockNode &Succ,
252 uint64_t Weight) {
253 if (!Weight)
254 Weight = 1;
255
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000256 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
257 return OuterLoop && OuterLoop->isHeader(Node);
258 };
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000259
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000260 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
261
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000262#ifndef NDEBUG
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000263 auto debugSuccessor = [&](const char *Type) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000264 dbgs() << " =>"
265 << " [" << Type << "] weight = " << Weight;
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000266 if (!isLoopHeader(Resolved))
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000267 dbgs() << ", succ = " << getBlockName(Succ);
268 if (Resolved != Succ)
269 dbgs() << ", resolved = " << getBlockName(Resolved);
270 dbgs() << "\n";
271 };
272 (void)debugSuccessor;
273#endif
274
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000275 if (isLoopHeader(Resolved)) {
276 DEBUG(debugSuccessor("backedge"));
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000277 Dist.addBackedge(OuterLoop->getHeader(), Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000278 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000279 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000280
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000281 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000282 DEBUG(debugSuccessor(" exit "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000283 Dist.addExit(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000284 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000285 }
286
Duncan P. N. Exon Smithb3380ea2014-04-22 03:31:53 +0000287 if (Resolved < Pred) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000288 if (!isLoopHeader(Pred)) {
289 // If OuterLoop is an irreducible loop, we can't actually handle this.
290 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
291 "unhandled irreducible control flow");
292
293 // Irreducible backedge. Abort.
294 DEBUG(debugSuccessor("abort!!!"));
295 return false;
296 }
297
298 // If "Pred" is a loop header, then this isn't really a backedge; rather,
299 // OuterLoop must be irreducible. These false backedges can come only from
300 // secondary loop headers.
301 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
302 "unhandled irreducible control flow");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000303 }
304
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000305 DEBUG(debugSuccessor(" local "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000306 Dist.addLocal(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000307 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000308}
309
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000310bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000311 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000312 // Copy the exit map into Dist.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000313 for (const auto &I : Loop.Exits)
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000314 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
315 I.second.getMass()))
316 // Irreducible backedge.
317 return false;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000318
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000319 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000320}
321
322/// \brief Get the maximum allowed loop scale.
323///
Duncan P. N. Exon Smith254689f2014-04-21 18:31:58 +0000324/// Gives the maximum number of estimated iterations allowed for a loop. Very
325/// large numbers cause problems downstream (even within 64-bits).
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000326static Scaled64 getMaxLoopScale() { return Scaled64(1, 12); }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000327
328/// \brief Compute the loop scale for a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000329void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000330 // Compute loop scale.
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000331 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000332
333 // LoopScale == 1 / ExitMass
334 // ExitMass == HeadMass - BackedgeMass
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000335 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000336
337 // Block scale stores the inverse of the scale.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000338 Loop.Scale = ExitMass.toScaled().inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000339
340 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000341 << " - " << Loop.BackedgeMass << ")\n"
342 << " - scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000343
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000344 if (Loop.Scale > getMaxLoopScale()) {
345 Loop.Scale = getMaxLoopScale();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000346 DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
347 }
348}
349
350/// \brief Package up a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000351void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000352 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
353
354 // Clear the subloop exits to prevent quadratic memory usage.
355 for (const BlockNode &M : Loop.Nodes) {
356 if (auto *Loop = Working[M.Index].getPackagedLoop())
357 Loop->Exits.clear();
358 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
359 }
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000360 Loop.IsPackaged = true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000361}
362
363void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000364 LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000365 Distribution &Dist) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000366 BlockMass Mass = Working[Source.Index].getMass();
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000367 DEBUG(dbgs() << " => mass: " << Mass << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000368
369 // Distribute mass to successors as laid out in Dist.
370 DitheringDistributer D(Dist, Mass);
371
372#ifndef NDEBUG
373 auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
374 const char *Desc) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000375 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000376 if (Desc)
377 dbgs() << " [" << Desc << "]";
378 if (T.isValid())
379 dbgs() << " to " << getBlockName(T);
380 dbgs() << "\n";
381 };
382 (void)debugAssign;
383#endif
384
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000385 for (const Weight &W : Dist.Weights) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000386 // Check for a local edge (non-backedge and non-exit).
387 BlockMass Taken = D.takeMass(W.Amount);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000388 if (W.Type == Weight::Local) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000389 Working[W.TargetNode.Index].getMass() += Taken;
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000390 DEBUG(debugAssign(W.TargetNode, Taken, nullptr));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000391 continue;
392 }
393
394 // Backedges and exits only make sense if we're processing a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000395 assert(OuterLoop && "backedge or exit outside of loop");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000396
397 // Check for a backedge.
398 if (W.Type == Weight::Backedge) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000399 OuterLoop->BackedgeMass += Taken;
400 DEBUG(debugAssign(BlockNode(), Taken, "back"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000401 continue;
402 }
403
404 // This must be an exit.
405 assert(W.Type == Weight::Exit);
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000406 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
407 DEBUG(debugAssign(W.TargetNode, Taken, "exit"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000408 }
409}
410
411static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000412 const Scaled64 &Min, const Scaled64 &Max) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000413 // Scale the Factor to a size that creates integers. Ideally, integers would
414 // be scaled so that Max == UINT64_MAX so that they can be best
415 // differentiated. However, the register allocator currently deals poorly
416 // with large numbers. Instead, push Min up a little from 1 to give some
417 // room to differentiate small, unequal numbers.
418 //
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000419 // TODO: fix issues downstream so that ScalingFactor can be
420 // Scaled64(1,64)/Max.
421 Scaled64 ScalingFactor = Min.inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000422 if ((Max / Min).lg() < 60)
423 ScalingFactor <<= 3;
424
425 // Translate the floats to integers.
426 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
427 << ", factor = " << ScalingFactor << "\n");
428 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000429 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000430 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
431 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000432 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000433 << ", int = " << BFI.Freqs[Index].Integer << "\n");
434 }
435}
436
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000437/// \brief Unwrap a loop package.
438///
439/// Visits all the members of a loop, adjusting their BlockData according to
440/// the loop's pseudo-node.
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000441static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000442 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000443 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
444 << "\n");
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000445 Loop.Scale *= Loop.Mass.toScaled();
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000446 Loop.IsPackaged = false;
Duncan P. N. Exon Smith3f086782014-04-25 04:38:32 +0000447 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000448
449 // Propagate the head scale through the loop. Since members are visited in
450 // RPO, the head scale will be updated by the loop scale first, and then the
451 // final head scale will be used for updated the rest of the members.
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000452 for (const BlockNode &N : Loop.Nodes) {
453 const auto &Working = BFI.Working[N.Index];
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000454 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
455 : BFI.Freqs[N.Index].Scaled;
456 Scaled64 New = Loop.Scale * F;
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000457 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
458 << "\n");
459 F = New;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000460 }
461}
462
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000463void BlockFrequencyInfoImplBase::unwrapLoops() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000464 // Set initial frequencies from loop-local masses.
465 for (size_t Index = 0; Index < Working.size(); ++Index)
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000466 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000467
Duncan P. N. Exon Smithda0b21c2014-04-25 04:38:23 +0000468 for (LoopData &Loop : Loops)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000469 unwrapLoop(*this, Loop);
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000470}
471
472void BlockFrequencyInfoImplBase::finalizeMetrics() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000473 // Unwrap loop packages in reverse post-order, tracking min and max
474 // frequencies.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000475 auto Min = Scaled64::getLargest();
476 auto Max = Scaled64::getZero();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000477 for (size_t Index = 0; Index < Working.size(); ++Index) {
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000478 // Update min/max scale.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000479 Min = std::min(Min, Freqs[Index].Scaled);
480 Max = std::max(Max, Freqs[Index].Scaled);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000481 }
482
483 // Convert to integers.
484 convertFloatingToInteger(*this, Min, Max);
485
486 // Clean up data structures.
487 cleanup(*this);
488
489 // Print out the final stats.
490 DEBUG(dump());
491}
492
493BlockFrequency
494BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
495 if (!Node.isValid())
496 return 0;
497 return Freqs[Node.Index].Integer;
498}
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000499Scaled64
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000500BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
501 if (!Node.isValid())
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000502 return Scaled64::getZero();
503 return Freqs[Node.Index].Scaled;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000504}
505
506std::string
507BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
508 return std::string();
509}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000510std::string
511BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
512 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
513}
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000514
515raw_ostream &
516BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
517 const BlockNode &Node) const {
518 return OS << getFloatingBlockFreq(Node);
519}
520
521raw_ostream &
522BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
523 const BlockFrequency &Freq) const {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000524 Scaled64 Block(Freq.getFrequency(), 0);
525 Scaled64 Entry(getEntryFreq(), 0);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000526
527 return OS << Block / Entry;
528}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000529
530void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
531 Start = OuterLoop.getHeader();
532 Nodes.reserve(OuterLoop.Nodes.size());
533 for (auto N : OuterLoop.Nodes)
534 addNode(N);
535 indexNodes();
536}
537void IrreducibleGraph::addNodesInFunction() {
538 Start = 0;
539 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
540 if (!BFI.Working[Index].isPackaged())
541 addNode(Index);
542 indexNodes();
543}
544void IrreducibleGraph::indexNodes() {
545 for (auto &I : Nodes)
546 Lookup[I.Node.Index] = &I;
547}
548void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
549 const BFIBase::LoopData *OuterLoop) {
550 if (OuterLoop && OuterLoop->isHeader(Succ))
551 return;
552 auto L = Lookup.find(Succ.Index);
553 if (L == Lookup.end())
554 return;
555 IrrNode &SuccIrr = *L->second;
556 Irr.Edges.push_back(&SuccIrr);
557 SuccIrr.Edges.push_front(&Irr);
558 ++SuccIrr.NumIn;
559}
560
561namespace llvm {
562template <> struct GraphTraits<IrreducibleGraph> {
563 typedef bfi_detail::IrreducibleGraph GraphT;
564
Duncan P. N. Exon Smith295b5e72014-04-28 20:22:29 +0000565 typedef const GraphT::IrrNode NodeType;
566 typedef GraphT::IrrNode::iterator ChildIteratorType;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000567
568 static const NodeType *getEntryNode(const GraphT &G) {
569 return G.StartIrr;
570 }
571 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
572 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
573};
574}
575
576/// \brief Find extra irreducible headers.
577///
578/// Find entry blocks and other blocks with backedges, which exist when \c G
579/// contains irreducible sub-SCCs.
580static void findIrreducibleHeaders(
581 const BlockFrequencyInfoImplBase &BFI,
582 const IrreducibleGraph &G,
583 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
584 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
585 // Map from nodes in the SCC to whether it's an entry block.
586 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
587
588 // InSCC also acts the set of nodes in the graph. Seed it.
589 for (const auto *I : SCC)
590 InSCC[I] = false;
591
592 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
593 auto &Irr = *I->first;
594 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
595 if (InSCC.count(P))
596 continue;
597
598 // This is an entry block.
599 I->second = true;
600 Headers.push_back(Irr.Node);
601 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
602 break;
603 }
604 }
Duncan P. N. Exon Smitha7a90a22014-10-06 17:42:00 +0000605 assert(Headers.size() >= 2 &&
606 "Expected irreducible CFG; -loop-info is likely invalid");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000607 if (Headers.size() == InSCC.size()) {
608 // Every block is a header.
609 std::sort(Headers.begin(), Headers.end());
610 return;
611 }
612
613 // Look for extra headers from irreducible sub-SCCs.
614 for (const auto &I : InSCC) {
615 // Entry blocks are already headers.
616 if (I.second)
617 continue;
618
619 auto &Irr = *I.first;
620 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
621 // Skip forward edges.
622 if (P->Node < Irr.Node)
623 continue;
624
625 // Skip predecessors from entry blocks. These can have inverted
626 // ordering.
627 if (InSCC.lookup(P))
628 continue;
629
630 // Store the extra header.
631 Headers.push_back(Irr.Node);
632 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
633 break;
634 }
635 if (Headers.back() == Irr.Node)
636 // Added this as a header.
637 continue;
638
639 // This is not a header.
640 Others.push_back(Irr.Node);
641 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
642 }
643 std::sort(Headers.begin(), Headers.end());
644 std::sort(Others.begin(), Others.end());
645}
646
647static void createIrreducibleLoop(
648 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
649 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
650 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
651 // Translate the SCC into RPO.
652 DEBUG(dbgs() << " - found-scc\n");
653
654 LoopData::NodeList Headers;
655 LoopData::NodeList Others;
656 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
657
658 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
659 Headers.end(), Others.begin(), Others.end());
660
661 // Update loop hierarchy.
662 for (const auto &N : Loop->Nodes)
663 if (BFI.Working[N.Index].isLoopHeader())
664 BFI.Working[N.Index].Loop->Parent = &*Loop;
665 else
666 BFI.Working[N.Index].Loop = &*Loop;
667}
668
669iterator_range<std::list<LoopData>::iterator>
670BlockFrequencyInfoImplBase::analyzeIrreducible(
671 const IrreducibleGraph &G, LoopData *OuterLoop,
672 std::list<LoopData>::iterator Insert) {
673 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
674 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
675
676 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
677 if (I->size() < 2)
678 continue;
679
680 // Translate the SCC into RPO.
681 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
682 }
683
684 if (OuterLoop)
685 return make_range(std::next(Prev), Insert);
686 return make_range(Loops.begin(), Insert);
687}
688
689void
690BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
691 OuterLoop.Exits.clear();
692 OuterLoop.BackedgeMass = BlockMass::getEmpty();
693 auto O = OuterLoop.Nodes.begin() + 1;
694 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
695 if (!Working[I->Index].isPackaged())
696 *O++ = *I;
697 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
698}