blob: 9d3045c16a017b4af4d96e4290a5485550dce981 [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"
Xinliang David Lib12b3532016-06-22 17:12:12 +000016#include "llvm/IR/Function.h"
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000017#include "llvm/Support/raw_ostream.h"
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +000018#include <numeric>
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000019
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 Smithbeaf8132014-06-24 00:26:13 +000025ScaledNumber<uint64_t> BlockMass::toScaled() const {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000026 if (isFull())
Duncan P. N. Exon Smithc379c872014-06-23 23:36:17 +000027 return ScaledNumber<uint64_t>(1, 0);
28 return ScaledNumber<uint64_t>(getMass() + 1, -64);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000029}
30
Yaron Kereneb2a2542016-01-29 20:50:44 +000031LLVM_DUMP_METHOD void BlockMass::dump() const { print(dbgs()); }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000032
33static char getHexDigit(int N) {
34 assert(N < 16);
35 if (N < 10)
36 return '0' + N;
37 return 'a' + N - 10;
38}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000039
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000040raw_ostream &BlockMass::print(raw_ostream &OS) const {
41 for (int Digits = 0; Digits < 16; ++Digits)
42 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
43 return OS;
44}
45
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000046namespace {
47
48typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
49typedef BlockFrequencyInfoImplBase::Distribution Distribution;
50typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +000051typedef BlockFrequencyInfoImplBase::Scaled64 Scaled64;
Duncan P. N. Exon Smithcc88ebf2014-04-22 03:31:31 +000052typedef BlockFrequencyInfoImplBase::LoopData LoopData;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000053typedef BlockFrequencyInfoImplBase::Weight Weight;
54typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
55
56/// \brief Dithering mass distributer.
57///
58/// This class splits up a single mass into portions by weight, dithering to
59/// spread out error. No mass is lost. The dithering precision depends on the
60/// precision of the product of \a BlockMass and \a BranchProbability.
61///
62/// The distribution algorithm follows.
63///
64/// 1. Initialize by saving the sum of the weights in \a RemWeight and the
65/// mass to distribute in \a RemMass.
66///
67/// 2. For each portion:
68///
69/// 1. Construct a branch probability, P, as the portion's weight divided
70/// by the current value of \a RemWeight.
71/// 2. Calculate the portion's mass as \a RemMass times P.
72/// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
73/// the current portion's weight and mass.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000074struct DitheringDistributer {
75 uint32_t RemWeight;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000076 BlockMass RemMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000077
78 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
79
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000080 BlockMass takeMass(uint32_t Weight);
81};
Duncan P. N. Exon Smithb5650e52014-07-11 23:56:50 +000082
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000083} // end anonymous namespace
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000084
85DitheringDistributer::DitheringDistributer(Distribution &Dist,
86 const BlockMass &Mass) {
87 Dist.normalize();
88 RemWeight = Dist.Total;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000089 RemMass = Mass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000090}
91
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000092BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
93 assert(Weight && "invalid weight");
94 assert(Weight <= RemWeight);
95 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
96
97 // Decrement totals (dither).
98 RemWeight -= Weight;
99 RemMass -= Mass;
100 return Mass;
101}
102
103void Distribution::add(const BlockNode &Node, uint64_t Amount,
104 Weight::DistType Type) {
105 assert(Amount && "invalid weight of 0");
106 uint64_t NewTotal = Total + Amount;
107
108 // Check for overflow. It should be impossible to overflow twice.
109 bool IsOverflow = NewTotal < Total;
110 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
111 DidOverflow |= IsOverflow;
112
113 // Update the total.
114 Total = NewTotal;
115
116 // Save the weight.
Duncan P. N. Exon Smith60755102014-07-12 00:26:00 +0000117 Weights.push_back(Weight(Type, Node, Amount));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000118}
119
120static void combineWeight(Weight &W, const Weight &OtherW) {
121 assert(OtherW.TargetNode.isValid());
122 if (!W.Amount) {
123 W = OtherW;
124 return;
125 }
126 assert(W.Type == OtherW.Type);
127 assert(W.TargetNode == OtherW.TargetNode);
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000128 assert(OtherW.Amount && "Expected non-zero weight");
129 if (W.Amount > W.Amount + OtherW.Amount)
130 // Saturate on overflow.
131 W.Amount = UINT64_MAX;
132 else
133 W.Amount += OtherW.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000134}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000135
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000136static void combineWeightsBySorting(WeightList &Weights) {
137 // Sort so edges to the same node are adjacent.
138 std::sort(Weights.begin(), Weights.end(),
139 [](const Weight &L,
140 const Weight &R) { return L.TargetNode < R.TargetNode; });
141
142 // Combine adjacent edges.
143 WeightList::iterator O = Weights.begin();
144 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
145 ++O, (I = L)) {
146 *O = *I;
147
148 // Find the adjacent weights to the same node.
149 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
150 combineWeight(*O, *L);
151 }
152
153 // Erase extra entries.
154 Weights.erase(O, Weights.end());
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000155}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000156
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000157static void combineWeightsByHashing(WeightList &Weights) {
158 // Collect weights into a DenseMap.
159 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
160 HashTable Combined(NextPowerOf2(2 * Weights.size()));
161 for (const Weight &W : Weights)
162 combineWeight(Combined[W.TargetNode.Index], W);
163
164 // Check whether anything changed.
165 if (Weights.size() == Combined.size())
166 return;
167
168 // Fill in the new weights.
169 Weights.clear();
170 Weights.reserve(Combined.size());
171 for (const auto &I : Combined)
172 Weights.push_back(I.second);
173}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000174
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000175static void combineWeights(WeightList &Weights) {
176 // Use a hash table for many successors to keep this linear.
177 if (Weights.size() > 128) {
178 combineWeightsByHashing(Weights);
179 return;
180 }
181
182 combineWeightsBySorting(Weights);
183}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000184
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000185static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
186 assert(Shift >= 0);
187 assert(Shift < 64);
188 if (!Shift)
189 return N;
190 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
191}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000192
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000193void Distribution::normalize() {
194 // Early exit for termination nodes.
195 if (Weights.empty())
196 return;
197
198 // Only bother if there are multiple successors.
199 if (Weights.size() > 1)
200 combineWeights(Weights);
201
202 // Early exit when combined into a single successor.
203 if (Weights.size() == 1) {
204 Total = 1;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000205 Weights.front().Amount = 1;
206 return;
207 }
208
209 // Determine how much to shift right so that the total fits into 32-bits.
210 //
211 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
212 // for each weight can cause a 32-bit overflow.
213 int Shift = 0;
214 if (DidOverflow)
215 Shift = 33;
216 else if (Total > UINT32_MAX)
217 Shift = 33 - countLeadingZeros(Total);
218
219 // Early exit if nothing needs to be scaled.
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000220 if (!Shift) {
221 // If we didn't overflow then combineWeights() shouldn't have changed the
222 // sum of the weights, but let's double-check.
223 assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
224 [](uint64_t Sum, const Weight &W) {
225 return Sum + W.Amount;
226 }) &&
227 "Expected total to be correct");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000228 return;
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000229 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000230
231 // Recompute the total through accumulation (rather than shifting it) so that
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000232 // it's accurate after shifting and any changes combineWeights() made above.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000233 Total = 0;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000234
235 // Sum the weights to each node and shift right if necessary.
236 for (Weight &W : Weights) {
237 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
238 // can round here without concern about overflow.
239 assert(W.TargetNode.isValid());
240 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
241 assert(W.Amount <= UINT32_MAX);
242
243 // Update the total.
244 Total += W.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000245 }
246 assert(Total <= UINT32_MAX);
247}
248
249void BlockFrequencyInfoImplBase::clear() {
Duncan P. N. Exon Smithdc2d66e2014-04-22 03:31:34 +0000250 // Swap with a default-constructed std::vector, since std::vector<>::clear()
251 // does not actually clear heap storage.
252 std::vector<FrequencyData>().swap(Freqs);
253 std::vector<WorkingData>().swap(Working);
Duncan P. N. Exon Smithfc7dc932014-04-25 04:30:06 +0000254 Loops.clear();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000255}
256
257/// \brief Clear all memory not needed downstream.
258///
259/// Releases all memory not used downstream. In particular, saves Freqs.
260static void cleanup(BlockFrequencyInfoImplBase &BFI) {
261 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
262 BFI.clear();
263 BFI.Freqs = std::move(SavedFreqs);
264}
265
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000266bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000267 const LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000268 const BlockNode &Pred,
269 const BlockNode &Succ,
270 uint64_t Weight) {
271 if (!Weight)
272 Weight = 1;
273
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000274 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
275 return OuterLoop && OuterLoop->isHeader(Node);
276 };
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000277
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000278 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
279
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000280#ifndef NDEBUG
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000281 auto debugSuccessor = [&](const char *Type) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000282 dbgs() << " =>"
283 << " [" << Type << "] weight = " << Weight;
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000284 if (!isLoopHeader(Resolved))
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000285 dbgs() << ", succ = " << getBlockName(Succ);
286 if (Resolved != Succ)
287 dbgs() << ", resolved = " << getBlockName(Resolved);
288 dbgs() << "\n";
289 };
290 (void)debugSuccessor;
291#endif
292
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000293 if (isLoopHeader(Resolved)) {
294 DEBUG(debugSuccessor("backedge"));
Diego Novillo9a779622015-06-16 19:10:58 +0000295 Dist.addBackedge(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000296 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000297 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000298
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000299 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000300 DEBUG(debugSuccessor(" exit "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000301 Dist.addExit(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000302 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000303 }
304
Duncan P. N. Exon Smithb3380ea2014-04-22 03:31:53 +0000305 if (Resolved < Pred) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000306 if (!isLoopHeader(Pred)) {
307 // If OuterLoop is an irreducible loop, we can't actually handle this.
308 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
309 "unhandled irreducible control flow");
310
311 // Irreducible backedge. Abort.
312 DEBUG(debugSuccessor("abort!!!"));
313 return false;
314 }
315
316 // If "Pred" is a loop header, then this isn't really a backedge; rather,
317 // OuterLoop must be irreducible. These false backedges can come only from
318 // secondary loop headers.
319 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
320 "unhandled irreducible control flow");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000321 }
322
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000323 DEBUG(debugSuccessor(" local "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000324 Dist.addLocal(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000325 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000326}
327
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000328bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000329 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000330 // Copy the exit map into Dist.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000331 for (const auto &I : Loop.Exits)
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000332 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
333 I.second.getMass()))
334 // Irreducible backedge.
335 return false;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000336
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000337 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000338}
339
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000340/// \brief Compute the loop scale for a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000341void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000342 // Compute loop scale.
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000343 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000344
Diego Novilloa354f482015-04-01 17:42:27 +0000345 // Infinite loops need special handling. If we give the back edge an infinite
346 // mass, they may saturate all the other scales in the function down to 1,
347 // making all the other region temperatures look exactly the same. Choose an
348 // arbitrary scale to avoid these issues.
349 //
350 // FIXME: An alternate way would be to select a symbolic scale which is later
351 // replaced to be the maximum of all computed scales plus 1. This would
352 // appropriately describe the loop as having a large scale, without skewing
353 // the final frequency computation.
Sanjay Patel0fb98802016-05-09 16:07:45 +0000354 const Scaled64 InfiniteLoopScale(1, 12);
Diego Novilloa354f482015-04-01 17:42:27 +0000355
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000356 // LoopScale == 1 / ExitMass
357 // ExitMass == HeadMass - BackedgeMass
Diego Novillo9a779622015-06-16 19:10:58 +0000358 BlockMass TotalBackedgeMass;
359 for (auto &Mass : Loop.BackedgeMass)
360 TotalBackedgeMass += Mass;
361 BlockMass ExitMass = BlockMass::getFull() - TotalBackedgeMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000362
Diego Novilloa354f482015-04-01 17:42:27 +0000363 // Block scale stores the inverse of the scale. If this is an infinite loop,
364 // its exit mass will be zero. In this case, use an arbitrary scale for the
365 // loop scale.
366 Loop.Scale =
Sanjay Patel0fb98802016-05-09 16:07:45 +0000367 ExitMass.isEmpty() ? InfiniteLoopScale : ExitMass.toScaled().inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000368
369 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
Diego Novillo9a779622015-06-16 19:10:58 +0000370 << " - " << TotalBackedgeMass << ")\n"
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000371 << " - scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000372}
373
374/// \brief Package up a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000375void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000376 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
377
378 // Clear the subloop exits to prevent quadratic memory usage.
379 for (const BlockNode &M : Loop.Nodes) {
380 if (auto *Loop = Working[M.Index].getPackagedLoop())
381 Loop->Exits.clear();
382 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
383 }
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000384 Loop.IsPackaged = true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000385}
386
Diego Novillo9a779622015-06-16 19:10:58 +0000387#ifndef NDEBUG
388static void debugAssign(const BlockFrequencyInfoImplBase &BFI,
389 const DitheringDistributer &D, const BlockNode &T,
390 const BlockMass &M, const char *Desc) {
391 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
392 if (Desc)
393 dbgs() << " [" << Desc << "]";
394 if (T.isValid())
395 dbgs() << " to " << BFI.getBlockName(T);
396 dbgs() << "\n";
397}
398#endif
399
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000400void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000401 LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000402 Distribution &Dist) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000403 BlockMass Mass = Working[Source.Index].getMass();
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000404 DEBUG(dbgs() << " => mass: " << Mass << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000405
406 // Distribute mass to successors as laid out in Dist.
407 DitheringDistributer D(Dist, Mass);
408
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000409 for (const Weight &W : Dist.Weights) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000410 // Check for a local edge (non-backedge and non-exit).
411 BlockMass Taken = D.takeMass(W.Amount);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000412 if (W.Type == Weight::Local) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000413 Working[W.TargetNode.Index].getMass() += Taken;
Diego Novillo9a779622015-06-16 19:10:58 +0000414 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000415 continue;
416 }
417
418 // Backedges and exits only make sense if we're processing a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000419 assert(OuterLoop && "backedge or exit outside of loop");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000420
421 // Check for a backedge.
422 if (W.Type == Weight::Backedge) {
Diego Novillo8c49a572015-06-17 16:28:22 +0000423 OuterLoop->BackedgeMass[OuterLoop->getHeaderIndex(W.TargetNode)] += Taken;
Diego Novillo9a779622015-06-16 19:10:58 +0000424 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "back"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000425 continue;
426 }
427
428 // This must be an exit.
429 assert(W.Type == Weight::Exit);
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000430 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
Diego Novillo9a779622015-06-16 19:10:58 +0000431 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "exit"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000432 }
433}
434
435static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000436 const Scaled64 &Min, const Scaled64 &Max) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000437 // Scale the Factor to a size that creates integers. Ideally, integers would
438 // be scaled so that Max == UINT64_MAX so that they can be best
Diego Novilloa354f482015-04-01 17:42:27 +0000439 // differentiated. However, in the presence of large frequency values, small
440 // frequencies are scaled down to 1, making it impossible to differentiate
441 // small, unequal numbers. When the spread between Min and Max frequencies
442 // fits well within MaxBits, we make the scale be at least 8.
443 const unsigned MaxBits = 64;
444 const unsigned SpreadBits = (Max / Min).lg();
445 Scaled64 ScalingFactor;
446 if (SpreadBits <= MaxBits - 3) {
447 // If the values are small enough, make the scaling factor at least 8 to
448 // allow distinguishing small values.
449 ScalingFactor = Min.inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000450 ScalingFactor <<= 3;
Diego Novilloa354f482015-04-01 17:42:27 +0000451 } else {
452 // If the values need more than MaxBits to be represented, saturate small
453 // frequency values down to 1 by using a scaling factor that benefits large
454 // frequency values.
455 ScalingFactor = Scaled64(1, MaxBits) / Max;
456 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000457
458 // Translate the floats to integers.
459 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
460 << ", factor = " << ScalingFactor << "\n");
461 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000462 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000463 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
464 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000465 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000466 << ", int = " << BFI.Freqs[Index].Integer << "\n");
467 }
468}
469
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000470/// \brief Unwrap a loop package.
471///
472/// Visits all the members of a loop, adjusting their BlockData according to
473/// the loop's pseudo-node.
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000474static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000475 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000476 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
477 << "\n");
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000478 Loop.Scale *= Loop.Mass.toScaled();
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000479 Loop.IsPackaged = false;
Duncan P. N. Exon Smith3f086782014-04-25 04:38:32 +0000480 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000481
482 // Propagate the head scale through the loop. Since members are visited in
483 // RPO, the head scale will be updated by the loop scale first, and then the
484 // final head scale will be used for updated the rest of the members.
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000485 for (const BlockNode &N : Loop.Nodes) {
486 const auto &Working = BFI.Working[N.Index];
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000487 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
488 : BFI.Freqs[N.Index].Scaled;
489 Scaled64 New = Loop.Scale * F;
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000490 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
491 << "\n");
492 F = New;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000493 }
494}
495
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000496void BlockFrequencyInfoImplBase::unwrapLoops() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000497 // Set initial frequencies from loop-local masses.
498 for (size_t Index = 0; Index < Working.size(); ++Index)
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000499 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000500
Duncan P. N. Exon Smithda0b21c2014-04-25 04:38:23 +0000501 for (LoopData &Loop : Loops)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000502 unwrapLoop(*this, Loop);
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000503}
504
505void BlockFrequencyInfoImplBase::finalizeMetrics() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000506 // Unwrap loop packages in reverse post-order, tracking min and max
507 // frequencies.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000508 auto Min = Scaled64::getLargest();
509 auto Max = Scaled64::getZero();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000510 for (size_t Index = 0; Index < Working.size(); ++Index) {
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000511 // Update min/max scale.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000512 Min = std::min(Min, Freqs[Index].Scaled);
513 Max = std::max(Max, Freqs[Index].Scaled);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000514 }
515
516 // Convert to integers.
517 convertFloatingToInteger(*this, Min, Max);
518
519 // Clean up data structures.
520 cleanup(*this);
521
522 // Print out the final stats.
523 DEBUG(dump());
524}
525
526BlockFrequency
527BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
528 if (!Node.isValid())
529 return 0;
530 return Freqs[Node.Index].Integer;
531}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000532
Xinliang David Lib12b3532016-06-22 17:12:12 +0000533Optional<uint64_t>
534BlockFrequencyInfoImplBase::getBlockProfileCount(const Function &F,
535 const BlockNode &Node) const {
Sean Silvaf8015752016-08-02 02:15:45 +0000536 return getProfileCountFromFreq(F, getBlockFreq(Node).getFrequency());
537}
538
539Optional<uint64_t>
540BlockFrequencyInfoImplBase::getProfileCountFromFreq(const Function &F,
541 uint64_t Freq) const {
Xinliang David Lib12b3532016-06-22 17:12:12 +0000542 auto EntryCount = F.getEntryCount();
543 if (!EntryCount)
544 return None;
545 // Use 128 bit APInt to do the arithmetic to avoid overflow.
546 APInt BlockCount(128, EntryCount.getValue());
Sean Silvaf8015752016-08-02 02:15:45 +0000547 APInt BlockFreq(128, Freq);
Xinliang David Lib12b3532016-06-22 17:12:12 +0000548 APInt EntryFreq(128, getEntryFreq());
549 BlockCount *= BlockFreq;
550 BlockCount = BlockCount.udiv(EntryFreq);
551 return BlockCount.getLimitedValue();
552}
553
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000554Scaled64
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000555BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
556 if (!Node.isValid())
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000557 return Scaled64::getZero();
558 return Freqs[Node.Index].Scaled;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000559}
560
Manman Ren72d44b12015-10-15 14:59:40 +0000561void BlockFrequencyInfoImplBase::setBlockFreq(const BlockNode &Node,
562 uint64_t Freq) {
563 assert(Node.isValid() && "Expected valid node");
564 assert(Node.Index < Freqs.size() && "Expected legal index");
565 Freqs[Node.Index].Integer = Freq;
566}
567
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000568std::string
569BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
570 return std::string();
571}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000572
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000573std::string
574BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
575 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
576}
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000577
578raw_ostream &
579BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
580 const BlockNode &Node) const {
581 return OS << getFloatingBlockFreq(Node);
582}
583
584raw_ostream &
585BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
586 const BlockFrequency &Freq) const {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000587 Scaled64 Block(Freq.getFrequency(), 0);
588 Scaled64 Entry(getEntryFreq(), 0);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000589
590 return OS << Block / Entry;
591}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000592
593void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
594 Start = OuterLoop.getHeader();
595 Nodes.reserve(OuterLoop.Nodes.size());
596 for (auto N : OuterLoop.Nodes)
597 addNode(N);
598 indexNodes();
599}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000600
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000601void IrreducibleGraph::addNodesInFunction() {
602 Start = 0;
603 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
604 if (!BFI.Working[Index].isPackaged())
605 addNode(Index);
606 indexNodes();
607}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000608
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000609void IrreducibleGraph::indexNodes() {
610 for (auto &I : Nodes)
611 Lookup[I.Node.Index] = &I;
612}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000613
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000614void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
615 const BFIBase::LoopData *OuterLoop) {
616 if (OuterLoop && OuterLoop->isHeader(Succ))
617 return;
618 auto L = Lookup.find(Succ.Index);
619 if (L == Lookup.end())
620 return;
621 IrrNode &SuccIrr = *L->second;
622 Irr.Edges.push_back(&SuccIrr);
623 SuccIrr.Edges.push_front(&Irr);
624 ++SuccIrr.NumIn;
625}
626
627namespace llvm {
628template <> struct GraphTraits<IrreducibleGraph> {
629 typedef bfi_detail::IrreducibleGraph GraphT;
630
Duncan P. N. Exon Smith295b5e72014-04-28 20:22:29 +0000631 typedef const GraphT::IrrNode NodeType;
Tim Shenb44909e2016-08-01 22:32:20 +0000632 typedef const GraphT::IrrNode *NodeRef;
Duncan P. N. Exon Smith295b5e72014-04-28 20:22:29 +0000633 typedef GraphT::IrrNode::iterator ChildIteratorType;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000634
635 static const NodeType *getEntryNode(const GraphT &G) {
636 return G.StartIrr;
637 }
638 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); }
639 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); }
640};
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000641} // end namespace llvm
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000642
643/// \brief Find extra irreducible headers.
644///
645/// Find entry blocks and other blocks with backedges, which exist when \c G
646/// contains irreducible sub-SCCs.
647static void findIrreducibleHeaders(
648 const BlockFrequencyInfoImplBase &BFI,
649 const IrreducibleGraph &G,
650 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
651 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
652 // Map from nodes in the SCC to whether it's an entry block.
653 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
654
655 // InSCC also acts the set of nodes in the graph. Seed it.
656 for (const auto *I : SCC)
657 InSCC[I] = false;
658
659 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
660 auto &Irr = *I->first;
661 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
662 if (InSCC.count(P))
663 continue;
664
665 // This is an entry block.
666 I->second = true;
667 Headers.push_back(Irr.Node);
668 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
669 break;
670 }
671 }
Duncan P. N. Exon Smitha7a90a22014-10-06 17:42:00 +0000672 assert(Headers.size() >= 2 &&
673 "Expected irreducible CFG; -loop-info is likely invalid");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000674 if (Headers.size() == InSCC.size()) {
675 // Every block is a header.
676 std::sort(Headers.begin(), Headers.end());
677 return;
678 }
679
680 // Look for extra headers from irreducible sub-SCCs.
681 for (const auto &I : InSCC) {
682 // Entry blocks are already headers.
683 if (I.second)
684 continue;
685
686 auto &Irr = *I.first;
687 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
688 // Skip forward edges.
689 if (P->Node < Irr.Node)
690 continue;
691
692 // Skip predecessors from entry blocks. These can have inverted
693 // ordering.
694 if (InSCC.lookup(P))
695 continue;
696
697 // Store the extra header.
698 Headers.push_back(Irr.Node);
699 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
700 break;
701 }
702 if (Headers.back() == Irr.Node)
703 // Added this as a header.
704 continue;
705
706 // This is not a header.
707 Others.push_back(Irr.Node);
708 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
709 }
710 std::sort(Headers.begin(), Headers.end());
711 std::sort(Others.begin(), Others.end());
712}
713
714static void createIrreducibleLoop(
715 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
716 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
717 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
718 // Translate the SCC into RPO.
719 DEBUG(dbgs() << " - found-scc\n");
720
721 LoopData::NodeList Headers;
722 LoopData::NodeList Others;
723 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
724
725 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
726 Headers.end(), Others.begin(), Others.end());
727
728 // Update loop hierarchy.
729 for (const auto &N : Loop->Nodes)
730 if (BFI.Working[N.Index].isLoopHeader())
731 BFI.Working[N.Index].Loop->Parent = &*Loop;
732 else
733 BFI.Working[N.Index].Loop = &*Loop;
734}
735
736iterator_range<std::list<LoopData>::iterator>
737BlockFrequencyInfoImplBase::analyzeIrreducible(
738 const IrreducibleGraph &G, LoopData *OuterLoop,
739 std::list<LoopData>::iterator Insert) {
740 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
741 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
742
743 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
744 if (I->size() < 2)
745 continue;
746
747 // Translate the SCC into RPO.
748 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
749 }
750
751 if (OuterLoop)
752 return make_range(std::next(Prev), Insert);
753 return make_range(Loops.begin(), Insert);
754}
755
756void
757BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
758 OuterLoop.Exits.clear();
Diego Novillo9a779622015-06-16 19:10:58 +0000759 for (auto &Mass : OuterLoop.BackedgeMass)
760 Mass = BlockMass::getEmpty();
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000761 auto O = OuterLoop.Nodes.begin() + 1;
762 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
763 if (!Working[I->Index].isPackaged())
764 *O++ = *I;
765 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
766}
Diego Novillo9a779622015-06-16 19:10:58 +0000767
768void BlockFrequencyInfoImplBase::adjustLoopHeaderMass(LoopData &Loop) {
769 assert(Loop.isIrreducible() && "this only makes sense on irreducible loops");
770
771 // Since the loop has more than one header block, the mass flowing back into
772 // each header will be different. Adjust the mass in each header loop to
773 // reflect the masses flowing through back edges.
774 //
775 // To do this, we distribute the initial mass using the backedge masses
776 // as weights for the distribution.
777 BlockMass LoopMass = BlockMass::getFull();
778 Distribution Dist;
779
780 DEBUG(dbgs() << "adjust-loop-header-mass:\n");
781 for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
782 auto &HeaderNode = Loop.Nodes[H];
Diego Novillo8c49a572015-06-17 16:28:22 +0000783 auto &BackedgeMass = Loop.BackedgeMass[Loop.getHeaderIndex(HeaderNode)];
Diego Novillo9a779622015-06-16 19:10:58 +0000784 DEBUG(dbgs() << " - Add back edge mass for node "
785 << getBlockName(HeaderNode) << ": " << BackedgeMass << "\n");
Diego Novillof9aa39b2015-09-08 19:22:17 +0000786 if (BackedgeMass.getMass() > 0)
787 Dist.addLocal(HeaderNode, BackedgeMass.getMass());
788 else
789 DEBUG(dbgs() << " Nothing added. Back edge mass is zero\n");
Diego Novillo9a779622015-06-16 19:10:58 +0000790 }
791
792 DitheringDistributer D(Dist, LoopMass);
793
794 DEBUG(dbgs() << " Distribute loop mass " << LoopMass
795 << " to headers using above weights\n");
796 for (const Weight &W : Dist.Weights) {
797 BlockMass Taken = D.takeMass(W.Amount);
798 assert(W.Type == Weight::Local && "all weights should be local");
799 Working[W.TargetNode.Index].getMass() = Taken;
800 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
801 }
802}