blob: 5923a444d24eb873ddc1b98042162eae1e537b07 [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"
15#include "llvm/ADT/APFloat.h"
Duncan P. N. Exon Smith87c40fd2014-05-06 01:57:42 +000016#include "llvm/ADT/SCCIterator.h"
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000017#include "llvm/Support/raw_ostream.h"
18#include <deque>
19
20using namespace llvm;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +000021using namespace llvm::bfi_detail;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000022
Chandler Carruth1b9dde02014-04-22 02:02:50 +000023#define DEBUG_TYPE "block-freq"
24
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000025//===----------------------------------------------------------------------===//
26//
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000027// ScaledNumber implementation.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000028//
29//===----------------------------------------------------------------------===//
30#ifndef _MSC_VER
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000031const int32_t ScaledNumberBase::MaxExponent;
32const int32_t ScaledNumberBase::MinExponent;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000033#endif
34
35static void appendDigit(std::string &Str, unsigned D) {
36 assert(D < 10);
37 Str += '0' + D % 10;
38}
39
40static void appendNumber(std::string &Str, uint64_t N) {
41 while (N) {
42 appendDigit(Str, N % 10);
43 N /= 10;
44 }
45}
46
47static bool doesRoundUp(char Digit) {
48 switch (Digit) {
49 case '5':
50 case '6':
51 case '7':
52 case '8':
53 case '9':
54 return true;
55 default:
56 return false;
57 }
58}
59
60static std::string toStringAPFloat(uint64_t D, int E, unsigned Precision) {
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000061 assert(E >= ScaledNumberBase::MinExponent);
62 assert(E <= ScaledNumberBase::MaxExponent);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000063
64 // Find a new E, but don't let it increase past MaxExponent.
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000065 int LeadingZeros = ScaledNumberBase::countLeadingZeros64(D);
66 int NewE = std::min(ScaledNumberBase::MaxExponent, E + 63 - LeadingZeros);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000067 int Shift = 63 - (NewE - E);
68 assert(Shift <= LeadingZeros);
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000069 assert(Shift == LeadingZeros || NewE == ScaledNumberBase::MaxExponent);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000070 D <<= Shift;
71 E = NewE;
72
73 // Check for a denormal.
74 unsigned AdjustedE = E + 16383;
75 if (!(D >> 63)) {
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000076 assert(E == ScaledNumberBase::MaxExponent);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000077 AdjustedE = 0;
78 }
79
80 // Build the float and print it.
81 uint64_t RawBits[2] = {D, AdjustedE};
82 APFloat Float(APFloat::x87DoubleExtended, APInt(80, RawBits));
83 SmallVector<char, 24> Chars;
84 Float.toString(Chars, Precision, 0);
85 return std::string(Chars.begin(), Chars.end());
86}
87
88static std::string stripTrailingZeros(const std::string &Float) {
89 size_t NonZero = Float.find_last_not_of('0');
90 assert(NonZero != std::string::npos && "no . in floating point string");
91
92 if (Float[NonZero] == '.')
93 ++NonZero;
94
95 return Float.substr(0, NonZero + 1);
96}
97
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000098std::string ScaledNumberBase::toString(uint64_t D, int16_t E, int Width,
99 unsigned Precision) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000100 if (!D)
101 return "0.0";
102
103 // Canonicalize exponent and digits.
104 uint64_t Above0 = 0;
105 uint64_t Below0 = 0;
106 uint64_t Extra = 0;
107 int ExtraShift = 0;
108 if (E == 0) {
109 Above0 = D;
110 } else if (E > 0) {
111 if (int Shift = std::min(int16_t(countLeadingZeros64(D)), E)) {
112 D <<= Shift;
113 E -= Shift;
114
115 if (!E)
116 Above0 = D;
117 }
118 } else if (E > -64) {
119 Above0 = D >> -E;
120 Below0 = D << (64 + E);
121 } else if (E > -120) {
122 Below0 = D >> (-E - 64);
123 Extra = D << (128 + E);
124 ExtraShift = -64 - E;
125 }
126
127 // Fall back on APFloat for very small and very large numbers.
128 if (!Above0 && !Below0)
129 return toStringAPFloat(D, E, Precision);
130
131 // Append the digits before the decimal.
132 std::string Str;
133 size_t DigitsOut = 0;
134 if (Above0) {
135 appendNumber(Str, Above0);
136 DigitsOut = Str.size();
137 } else
138 appendDigit(Str, 0);
139 std::reverse(Str.begin(), Str.end());
140
141 // Return early if there's nothing after the decimal.
142 if (!Below0)
143 return Str + ".0";
144
145 // Append the decimal and beyond.
146 Str += '.';
147 uint64_t Error = UINT64_C(1) << (64 - Width);
148
149 // We need to shift Below0 to the right to make space for calculating
150 // digits. Save the precision we're losing in Extra.
151 Extra = (Below0 & 0xf) << 56 | (Extra >> 8);
152 Below0 >>= 4;
153 size_t SinceDot = 0;
154 size_t AfterDot = Str.size();
155 do {
156 if (ExtraShift) {
157 --ExtraShift;
158 Error *= 5;
159 } else
160 Error *= 10;
161
162 Below0 *= 10;
163 Extra *= 10;
164 Below0 += (Extra >> 60);
165 Extra = Extra & (UINT64_MAX >> 4);
166 appendDigit(Str, Below0 >> 60);
167 Below0 = Below0 & (UINT64_MAX >> 4);
168 if (DigitsOut || Str.back() != '0')
169 ++DigitsOut;
170 ++SinceDot;
171 } while (Error && (Below0 << 4 | Extra >> 60) >= Error / 2 &&
172 (!Precision || DigitsOut <= Precision || SinceDot < 2));
173
174 // Return early for maximum precision.
175 if (!Precision || DigitsOut <= Precision)
176 return stripTrailingZeros(Str);
177
178 // Find where to truncate.
179 size_t Truncate =
180 std::max(Str.size() - (DigitsOut - Precision), AfterDot + 1);
181
182 // Check if there's anything to truncate.
183 if (Truncate >= Str.size())
184 return stripTrailingZeros(Str);
185
186 bool Carry = doesRoundUp(Str[Truncate]);
187 if (!Carry)
188 return stripTrailingZeros(Str.substr(0, Truncate));
189
190 // Round with the first truncated digit.
191 for (std::string::reverse_iterator I(Str.begin() + Truncate), E = Str.rend();
192 I != E; ++I) {
193 if (*I == '.')
194 continue;
195 if (*I == '9') {
196 *I = '0';
197 continue;
198 }
199
200 ++*I;
201 Carry = false;
202 break;
203 }
204
205 // Add "1" in front if we still need to carry.
206 return stripTrailingZeros(std::string(Carry, '1') + Str.substr(0, Truncate));
207}
208
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +0000209raw_ostream &ScaledNumberBase::print(raw_ostream &OS, uint64_t D, int16_t E,
210 int Width, unsigned Precision) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000211 return OS << toString(D, E, Width, Precision);
212}
213
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +0000214void ScaledNumberBase::dump(uint64_t D, int16_t E, int Width) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000215 print(dbgs(), D, E, Width, 0) << "[" << Width << ":" << D << "*2^" << E
216 << "]";
217}
218
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000219//===----------------------------------------------------------------------===//
220//
221// BlockMass implementation.
222//
223//===----------------------------------------------------------------------===//
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +0000224ScaledNumber<uint64_t> BlockMass::toFloat() const {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000225 if (isFull())
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +0000226 return ScaledNumber<uint64_t>(1, 0);
227 return ScaledNumber<uint64_t>(getMass() + 1, -64);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000228}
229
230void BlockMass::dump() const { print(dbgs()); }
231
232static char getHexDigit(int N) {
233 assert(N < 16);
234 if (N < 10)
235 return '0' + N;
236 return 'a' + N - 10;
237}
238raw_ostream &BlockMass::print(raw_ostream &OS) const {
239 for (int Digits = 0; Digits < 16; ++Digits)
240 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
241 return OS;
242}
243
244//===----------------------------------------------------------------------===//
245//
246// BlockFrequencyInfoImpl implementation.
247//
248//===----------------------------------------------------------------------===//
249namespace {
250
251typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
252typedef BlockFrequencyInfoImplBase::Distribution Distribution;
253typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
254typedef BlockFrequencyInfoImplBase::Float Float;
Duncan P. N. Exon Smithcc88ebf2014-04-22 03:31:31 +0000255typedef BlockFrequencyInfoImplBase::LoopData LoopData;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000256typedef BlockFrequencyInfoImplBase::Weight Weight;
257typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
258
259/// \brief Dithering mass distributer.
260///
261/// This class splits up a single mass into portions by weight, dithering to
262/// spread out error. No mass is lost. The dithering precision depends on the
263/// precision of the product of \a BlockMass and \a BranchProbability.
264///
265/// The distribution algorithm follows.
266///
267/// 1. Initialize by saving the sum of the weights in \a RemWeight and the
268/// mass to distribute in \a RemMass.
269///
270/// 2. For each portion:
271///
272/// 1. Construct a branch probability, P, as the portion's weight divided
273/// by the current value of \a RemWeight.
274/// 2. Calculate the portion's mass as \a RemMass times P.
275/// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
276/// the current portion's weight and mass.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000277struct DitheringDistributer {
278 uint32_t RemWeight;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000279 BlockMass RemMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000280
281 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
282
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000283 BlockMass takeMass(uint32_t Weight);
284};
285}
286
287DitheringDistributer::DitheringDistributer(Distribution &Dist,
288 const BlockMass &Mass) {
289 Dist.normalize();
290 RemWeight = Dist.Total;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000291 RemMass = Mass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000292}
293
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000294BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
295 assert(Weight && "invalid weight");
296 assert(Weight <= RemWeight);
297 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
298
299 // Decrement totals (dither).
300 RemWeight -= Weight;
301 RemMass -= Mass;
302 return Mass;
303}
304
305void Distribution::add(const BlockNode &Node, uint64_t Amount,
306 Weight::DistType Type) {
307 assert(Amount && "invalid weight of 0");
308 uint64_t NewTotal = Total + Amount;
309
310 // Check for overflow. It should be impossible to overflow twice.
311 bool IsOverflow = NewTotal < Total;
312 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
313 DidOverflow |= IsOverflow;
314
315 // Update the total.
316 Total = NewTotal;
317
318 // Save the weight.
319 Weight W;
320 W.TargetNode = Node;
321 W.Amount = Amount;
322 W.Type = Type;
323 Weights.push_back(W);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000324}
325
326static void combineWeight(Weight &W, const Weight &OtherW) {
327 assert(OtherW.TargetNode.isValid());
328 if (!W.Amount) {
329 W = OtherW;
330 return;
331 }
332 assert(W.Type == OtherW.Type);
333 assert(W.TargetNode == OtherW.TargetNode);
Duncan P. N. Exon Smithebf76262014-04-25 04:38:40 +0000334 assert(W.Amount < W.Amount + OtherW.Amount && "Unexpected overflow");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000335 W.Amount += OtherW.Amount;
336}
337static void combineWeightsBySorting(WeightList &Weights) {
338 // Sort so edges to the same node are adjacent.
339 std::sort(Weights.begin(), Weights.end(),
340 [](const Weight &L,
341 const Weight &R) { return L.TargetNode < R.TargetNode; });
342
343 // Combine adjacent edges.
344 WeightList::iterator O = Weights.begin();
345 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
346 ++O, (I = L)) {
347 *O = *I;
348
349 // Find the adjacent weights to the same node.
350 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
351 combineWeight(*O, *L);
352 }
353
354 // Erase extra entries.
355 Weights.erase(O, Weights.end());
356 return;
357}
358static void combineWeightsByHashing(WeightList &Weights) {
359 // Collect weights into a DenseMap.
360 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
361 HashTable Combined(NextPowerOf2(2 * Weights.size()));
362 for (const Weight &W : Weights)
363 combineWeight(Combined[W.TargetNode.Index], W);
364
365 // Check whether anything changed.
366 if (Weights.size() == Combined.size())
367 return;
368
369 // Fill in the new weights.
370 Weights.clear();
371 Weights.reserve(Combined.size());
372 for (const auto &I : Combined)
373 Weights.push_back(I.second);
374}
375static void combineWeights(WeightList &Weights) {
376 // Use a hash table for many successors to keep this linear.
377 if (Weights.size() > 128) {
378 combineWeightsByHashing(Weights);
379 return;
380 }
381
382 combineWeightsBySorting(Weights);
383}
384static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
385 assert(Shift >= 0);
386 assert(Shift < 64);
387 if (!Shift)
388 return N;
389 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
390}
391void Distribution::normalize() {
392 // Early exit for termination nodes.
393 if (Weights.empty())
394 return;
395
396 // Only bother if there are multiple successors.
397 if (Weights.size() > 1)
398 combineWeights(Weights);
399
400 // Early exit when combined into a single successor.
401 if (Weights.size() == 1) {
402 Total = 1;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000403 Weights.front().Amount = 1;
404 return;
405 }
406
407 // Determine how much to shift right so that the total fits into 32-bits.
408 //
409 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
410 // for each weight can cause a 32-bit overflow.
411 int Shift = 0;
412 if (DidOverflow)
413 Shift = 33;
414 else if (Total > UINT32_MAX)
415 Shift = 33 - countLeadingZeros(Total);
416
417 // Early exit if nothing needs to be scaled.
418 if (!Shift)
419 return;
420
421 // Recompute the total through accumulation (rather than shifting it) so that
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000422 // it's accurate after shifting.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000423 Total = 0;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000424
425 // Sum the weights to each node and shift right if necessary.
426 for (Weight &W : Weights) {
427 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
428 // can round here without concern about overflow.
429 assert(W.TargetNode.isValid());
430 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
431 assert(W.Amount <= UINT32_MAX);
432
433 // Update the total.
434 Total += W.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000435 }
436 assert(Total <= UINT32_MAX);
437}
438
439void BlockFrequencyInfoImplBase::clear() {
Duncan P. N. Exon Smithdc2d66e2014-04-22 03:31:34 +0000440 // Swap with a default-constructed std::vector, since std::vector<>::clear()
441 // does not actually clear heap storage.
442 std::vector<FrequencyData>().swap(Freqs);
443 std::vector<WorkingData>().swap(Working);
Duncan P. N. Exon Smithfc7dc932014-04-25 04:30:06 +0000444 Loops.clear();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000445}
446
447/// \brief Clear all memory not needed downstream.
448///
449/// Releases all memory not used downstream. In particular, saves Freqs.
450static void cleanup(BlockFrequencyInfoImplBase &BFI) {
451 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
452 BFI.clear();
453 BFI.Freqs = std::move(SavedFreqs);
454}
455
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000456bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000457 const LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000458 const BlockNode &Pred,
459 const BlockNode &Succ,
460 uint64_t Weight) {
461 if (!Weight)
462 Weight = 1;
463
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000464 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
465 return OuterLoop && OuterLoop->isHeader(Node);
466 };
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000467
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000468 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
469
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000470#ifndef NDEBUG
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000471 auto debugSuccessor = [&](const char *Type) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000472 dbgs() << " =>"
473 << " [" << Type << "] weight = " << Weight;
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000474 if (!isLoopHeader(Resolved))
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000475 dbgs() << ", succ = " << getBlockName(Succ);
476 if (Resolved != Succ)
477 dbgs() << ", resolved = " << getBlockName(Resolved);
478 dbgs() << "\n";
479 };
480 (void)debugSuccessor;
481#endif
482
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000483 if (isLoopHeader(Resolved)) {
484 DEBUG(debugSuccessor("backedge"));
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000485 Dist.addBackedge(OuterLoop->getHeader(), Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000486 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000487 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000488
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000489 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000490 DEBUG(debugSuccessor(" exit "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000491 Dist.addExit(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000492 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000493 }
494
Duncan P. N. Exon Smithb3380ea2014-04-22 03:31:53 +0000495 if (Resolved < Pred) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000496 if (!isLoopHeader(Pred)) {
497 // If OuterLoop is an irreducible loop, we can't actually handle this.
498 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
499 "unhandled irreducible control flow");
500
501 // Irreducible backedge. Abort.
502 DEBUG(debugSuccessor("abort!!!"));
503 return false;
504 }
505
506 // If "Pred" is a loop header, then this isn't really a backedge; rather,
507 // OuterLoop must be irreducible. These false backedges can come only from
508 // secondary loop headers.
509 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
510 "unhandled irreducible control flow");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000511 }
512
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000513 DEBUG(debugSuccessor(" local "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000514 Dist.addLocal(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000515 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000516}
517
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000518bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000519 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000520 // Copy the exit map into Dist.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000521 for (const auto &I : Loop.Exits)
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000522 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
523 I.second.getMass()))
524 // Irreducible backedge.
525 return false;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000526
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000527 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000528}
529
530/// \brief Get the maximum allowed loop scale.
531///
Duncan P. N. Exon Smith254689f2014-04-21 18:31:58 +0000532/// Gives the maximum number of estimated iterations allowed for a loop. Very
533/// large numbers cause problems downstream (even within 64-bits).
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000534static Float getMaxLoopScale() { return Float(1, 12); }
535
536/// \brief Compute the loop scale for a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000537void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000538 // Compute loop scale.
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000539 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000540
541 // LoopScale == 1 / ExitMass
542 // ExitMass == HeadMass - BackedgeMass
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000543 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000544
545 // Block scale stores the inverse of the scale.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000546 Loop.Scale = ExitMass.toFloat().inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000547
548 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000549 << " - " << Loop.BackedgeMass << ")\n"
550 << " - scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000551
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000552 if (Loop.Scale > getMaxLoopScale()) {
553 Loop.Scale = getMaxLoopScale();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000554 DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n");
555 }
556}
557
558/// \brief Package up a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000559void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000560 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
561
562 // Clear the subloop exits to prevent quadratic memory usage.
563 for (const BlockNode &M : Loop.Nodes) {
564 if (auto *Loop = Working[M.Index].getPackagedLoop())
565 Loop->Exits.clear();
566 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
567 }
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000568 Loop.IsPackaged = true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000569}
570
571void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000572 LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000573 Distribution &Dist) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000574 BlockMass Mass = Working[Source.Index].getMass();
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000575 DEBUG(dbgs() << " => mass: " << Mass << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000576
577 // Distribute mass to successors as laid out in Dist.
578 DitheringDistributer D(Dist, Mass);
579
580#ifndef NDEBUG
581 auto debugAssign = [&](const BlockNode &T, const BlockMass &M,
582 const char *Desc) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000583 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000584 if (Desc)
585 dbgs() << " [" << Desc << "]";
586 if (T.isValid())
587 dbgs() << " to " << getBlockName(T);
588 dbgs() << "\n";
589 };
590 (void)debugAssign;
591#endif
592
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000593 for (const Weight &W : Dist.Weights) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000594 // Check for a local edge (non-backedge and non-exit).
595 BlockMass Taken = D.takeMass(W.Amount);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000596 if (W.Type == Weight::Local) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000597 Working[W.TargetNode.Index].getMass() += Taken;
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000598 DEBUG(debugAssign(W.TargetNode, Taken, nullptr));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000599 continue;
600 }
601
602 // Backedges and exits only make sense if we're processing a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000603 assert(OuterLoop && "backedge or exit outside of loop");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000604
605 // Check for a backedge.
606 if (W.Type == Weight::Backedge) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000607 OuterLoop->BackedgeMass += Taken;
608 DEBUG(debugAssign(BlockNode(), Taken, "back"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000609 continue;
610 }
611
612 // This must be an exit.
613 assert(W.Type == Weight::Exit);
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000614 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
615 DEBUG(debugAssign(W.TargetNode, Taken, "exit"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000616 }
617}
618
619static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
620 const Float &Min, const Float &Max) {
621 // Scale the Factor to a size that creates integers. Ideally, integers would
622 // be scaled so that Max == UINT64_MAX so that they can be best
623 // differentiated. However, the register allocator currently deals poorly
624 // with large numbers. Instead, push Min up a little from 1 to give some
625 // room to differentiate small, unequal numbers.
626 //
627 // TODO: fix issues downstream so that ScalingFactor can be Float(1,64)/Max.
628 Float ScalingFactor = Min.inverse();
629 if ((Max / Min).lg() < 60)
630 ScalingFactor <<= 3;
631
632 // Translate the floats to integers.
633 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
634 << ", factor = " << ScalingFactor << "\n");
635 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
636 Float Scaled = BFI.Freqs[Index].Floating * ScalingFactor;
637 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
638 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
639 << BFI.Freqs[Index].Floating << ", scaled = " << Scaled
640 << ", int = " << BFI.Freqs[Index].Integer << "\n");
641 }
642}
643
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000644/// \brief Unwrap a loop package.
645///
646/// Visits all the members of a loop, adjusting their BlockData according to
647/// the loop's pseudo-node.
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000648static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000649 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000650 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
651 << "\n");
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000652 Loop.Scale *= Loop.Mass.toFloat();
653 Loop.IsPackaged = false;
Duncan P. N. Exon Smith3f086782014-04-25 04:38:32 +0000654 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000655
656 // Propagate the head scale through the loop. Since members are visited in
657 // RPO, the head scale will be updated by the loop scale first, and then the
658 // final head scale will be used for updated the rest of the members.
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000659 for (const BlockNode &N : Loop.Nodes) {
660 const auto &Working = BFI.Working[N.Index];
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000661 Float &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000662 : BFI.Freqs[N.Index].Floating;
663 Float New = Loop.Scale * F;
664 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
665 << "\n");
666 F = New;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000667 }
668}
669
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000670void BlockFrequencyInfoImplBase::unwrapLoops() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000671 // Set initial frequencies from loop-local masses.
672 for (size_t Index = 0; Index < Working.size(); ++Index)
673 Freqs[Index].Floating = Working[Index].Mass.toFloat();
674
Duncan P. N. Exon Smithda0b21c2014-04-25 04:38:23 +0000675 for (LoopData &Loop : Loops)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000676 unwrapLoop(*this, Loop);
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000677}
678
679void BlockFrequencyInfoImplBase::finalizeMetrics() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000680 // Unwrap loop packages in reverse post-order, tracking min and max
681 // frequencies.
682 auto Min = Float::getLargest();
683 auto Max = Float::getZero();
684 for (size_t Index = 0; Index < Working.size(); ++Index) {
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000685 // Update min/max scale.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000686 Min = std::min(Min, Freqs[Index].Floating);
687 Max = std::max(Max, Freqs[Index].Floating);
688 }
689
690 // Convert to integers.
691 convertFloatingToInteger(*this, Min, Max);
692
693 // Clean up data structures.
694 cleanup(*this);
695
696 // Print out the final stats.
697 DEBUG(dump());
698}
699
700BlockFrequency
701BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
702 if (!Node.isValid())
703 return 0;
704 return Freqs[Node.Index].Integer;
705}
706Float
707BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
708 if (!Node.isValid())
709 return Float::getZero();
710 return Freqs[Node.Index].Floating;
711}
712
713std::string
714BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
715 return std::string();
716}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000717std::string
718BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
719 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
720}
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000721
722raw_ostream &
723BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
724 const BlockNode &Node) const {
725 return OS << getFloatingBlockFreq(Node);
726}
727
728raw_ostream &
729BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
730 const BlockFrequency &Freq) const {
731 Float Block(Freq.getFrequency(), 0);
732 Float Entry(getEntryFreq(), 0);
733
734 return OS << Block / Entry;
735}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000736
737void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
738 Start = OuterLoop.getHeader();
739 Nodes.reserve(OuterLoop.Nodes.size());
740 for (auto N : OuterLoop.Nodes)
741 addNode(N);
742 indexNodes();
743}
744void IrreducibleGraph::addNodesInFunction() {
745 Start = 0;
746 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
747 if (!BFI.Working[Index].isPackaged())
748 addNode(Index);
749 indexNodes();
750}
751void IrreducibleGraph::indexNodes() {
752 for (auto &I : Nodes)
753 Lookup[I.Node.Index] = &I;
754}
755void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
756 const BFIBase::LoopData *OuterLoop) {
757 if (OuterLoop && OuterLoop->isHeader(Succ))
758 return;
759 auto L = Lookup.find(Succ.Index);
760 if (L == Lookup.end())
761 return;
762 IrrNode &SuccIrr = *L->second;
763 Irr.Edges.push_back(&SuccIrr);
764 SuccIrr.Edges.push_front(&Irr);
765 ++SuccIrr.NumIn;
766}
767
768namespace llvm {
769template <> struct GraphTraits<IrreducibleGraph> {
770 typedef bfi_detail::IrreducibleGraph GraphT;
771
Duncan P. N. Exon Smith295b5e72014-04-28 20:22:29 +0000772 typedef const GraphT::IrrNode NodeType;
773 typedef GraphT::IrrNode::iterator ChildIteratorType;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000774
775 static const NodeType *getEntryNode(const GraphT &G) {
776 return G.StartIrr;
777 }
778 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
779 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
780};
781}
782
783/// \brief Find extra irreducible headers.
784///
785/// Find entry blocks and other blocks with backedges, which exist when \c G
786/// contains irreducible sub-SCCs.
787static void findIrreducibleHeaders(
788 const BlockFrequencyInfoImplBase &BFI,
789 const IrreducibleGraph &G,
790 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
791 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
792 // Map from nodes in the SCC to whether it's an entry block.
793 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
794
795 // InSCC also acts the set of nodes in the graph. Seed it.
796 for (const auto *I : SCC)
797 InSCC[I] = false;
798
799 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
800 auto &Irr = *I->first;
801 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
802 if (InSCC.count(P))
803 continue;
804
805 // This is an entry block.
806 I->second = true;
807 Headers.push_back(Irr.Node);
808 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
809 break;
810 }
811 }
812 assert(Headers.size() >= 2 && "Should be irreducible");
813 if (Headers.size() == InSCC.size()) {
814 // Every block is a header.
815 std::sort(Headers.begin(), Headers.end());
816 return;
817 }
818
819 // Look for extra headers from irreducible sub-SCCs.
820 for (const auto &I : InSCC) {
821 // Entry blocks are already headers.
822 if (I.second)
823 continue;
824
825 auto &Irr = *I.first;
826 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
827 // Skip forward edges.
828 if (P->Node < Irr.Node)
829 continue;
830
831 // Skip predecessors from entry blocks. These can have inverted
832 // ordering.
833 if (InSCC.lookup(P))
834 continue;
835
836 // Store the extra header.
837 Headers.push_back(Irr.Node);
838 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
839 break;
840 }
841 if (Headers.back() == Irr.Node)
842 // Added this as a header.
843 continue;
844
845 // This is not a header.
846 Others.push_back(Irr.Node);
847 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
848 }
849 std::sort(Headers.begin(), Headers.end());
850 std::sort(Others.begin(), Others.end());
851}
852
853static void createIrreducibleLoop(
854 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
855 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
856 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
857 // Translate the SCC into RPO.
858 DEBUG(dbgs() << " - found-scc\n");
859
860 LoopData::NodeList Headers;
861 LoopData::NodeList Others;
862 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
863
864 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
865 Headers.end(), Others.begin(), Others.end());
866
867 // Update loop hierarchy.
868 for (const auto &N : Loop->Nodes)
869 if (BFI.Working[N.Index].isLoopHeader())
870 BFI.Working[N.Index].Loop->Parent = &*Loop;
871 else
872 BFI.Working[N.Index].Loop = &*Loop;
873}
874
875iterator_range<std::list<LoopData>::iterator>
876BlockFrequencyInfoImplBase::analyzeIrreducible(
877 const IrreducibleGraph &G, LoopData *OuterLoop,
878 std::list<LoopData>::iterator Insert) {
879 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
880 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
881
882 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
883 if (I->size() < 2)
884 continue;
885
886 // Translate the SCC into RPO.
887 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
888 }
889
890 if (OuterLoop)
891 return make_range(std::next(Prev), Insert);
892 return make_range(Loops.begin(), Insert);
893}
894
895void
896BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
897 OuterLoop.Exits.clear();
898 OuterLoop.BackedgeMass = BlockMass::getEmpty();
899 auto O = OuterLoop.Nodes.begin() + 1;
900 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
901 if (!Working[I->Index].isPackaged())
902 *O++ = *I;
903 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
904}