blob: e5d8c3347c164732ec43c51750007c0324908b0e [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
Matthias Braun8c209aa2017-01-28 02:02:38 +000031#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +000032LLVM_DUMP_METHOD void BlockMass::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +000033#endif
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000034
35static char getHexDigit(int N) {
36 assert(N < 16);
37 if (N < 10)
38 return '0' + N;
39 return 'a' + N - 10;
40}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000041
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000042raw_ostream &BlockMass::print(raw_ostream &OS) const {
43 for (int Digits = 0; Digits < 16; ++Digits)
44 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
45 return OS;
46}
47
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000048namespace {
49
50typedef BlockFrequencyInfoImplBase::BlockNode BlockNode;
51typedef BlockFrequencyInfoImplBase::Distribution Distribution;
52typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList;
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +000053typedef BlockFrequencyInfoImplBase::Scaled64 Scaled64;
Duncan P. N. Exon Smithcc88ebf2014-04-22 03:31:31 +000054typedef BlockFrequencyInfoImplBase::LoopData LoopData;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000055typedef BlockFrequencyInfoImplBase::Weight Weight;
56typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData;
57
58/// \brief Dithering mass distributer.
59///
60/// This class splits up a single mass into portions by weight, dithering to
61/// spread out error. No mass is lost. The dithering precision depends on the
62/// precision of the product of \a BlockMass and \a BranchProbability.
63///
64/// The distribution algorithm follows.
65///
66/// 1. Initialize by saving the sum of the weights in \a RemWeight and the
67/// mass to distribute in \a RemMass.
68///
69/// 2. For each portion:
70///
71/// 1. Construct a branch probability, P, as the portion's weight divided
72/// by the current value of \a RemWeight.
73/// 2. Calculate the portion's mass as \a RemMass times P.
74/// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
75/// the current portion's weight and mass.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000076struct DitheringDistributer {
77 uint32_t RemWeight;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000078 BlockMass RemMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000079
80 DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
81
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000082 BlockMass takeMass(uint32_t Weight);
83};
Duncan P. N. Exon Smithb5650e52014-07-11 23:56:50 +000084
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000085} // end anonymous namespace
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000086
87DitheringDistributer::DitheringDistributer(Distribution &Dist,
88 const BlockMass &Mass) {
89 Dist.normalize();
90 RemWeight = Dist.Total;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000091 RemMass = Mass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000092}
93
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +000094BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
95 assert(Weight && "invalid weight");
96 assert(Weight <= RemWeight);
97 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
98
99 // Decrement totals (dither).
100 RemWeight -= Weight;
101 RemMass -= Mass;
102 return Mass;
103}
104
105void Distribution::add(const BlockNode &Node, uint64_t Amount,
106 Weight::DistType Type) {
107 assert(Amount && "invalid weight of 0");
108 uint64_t NewTotal = Total + Amount;
109
110 // Check for overflow. It should be impossible to overflow twice.
111 bool IsOverflow = NewTotal < Total;
112 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
113 DidOverflow |= IsOverflow;
114
115 // Update the total.
116 Total = NewTotal;
117
118 // Save the weight.
Duncan P. N. Exon Smith60755102014-07-12 00:26:00 +0000119 Weights.push_back(Weight(Type, Node, Amount));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000120}
121
122static void combineWeight(Weight &W, const Weight &OtherW) {
123 assert(OtherW.TargetNode.isValid());
124 if (!W.Amount) {
125 W = OtherW;
126 return;
127 }
128 assert(W.Type == OtherW.Type);
129 assert(W.TargetNode == OtherW.TargetNode);
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000130 assert(OtherW.Amount && "Expected non-zero weight");
131 if (W.Amount > W.Amount + OtherW.Amount)
132 // Saturate on overflow.
133 W.Amount = UINT64_MAX;
134 else
135 W.Amount += OtherW.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000136}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000137
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000138static void combineWeightsBySorting(WeightList &Weights) {
139 // Sort so edges to the same node are adjacent.
140 std::sort(Weights.begin(), Weights.end(),
141 [](const Weight &L,
142 const Weight &R) { return L.TargetNode < R.TargetNode; });
143
144 // Combine adjacent edges.
145 WeightList::iterator O = Weights.begin();
146 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
147 ++O, (I = L)) {
148 *O = *I;
149
150 // Find the adjacent weights to the same node.
151 for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
152 combineWeight(*O, *L);
153 }
154
155 // Erase extra entries.
156 Weights.erase(O, Weights.end());
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000157}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000158
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000159static void combineWeightsByHashing(WeightList &Weights) {
160 // Collect weights into a DenseMap.
161 typedef DenseMap<BlockNode::IndexType, Weight> HashTable;
162 HashTable Combined(NextPowerOf2(2 * Weights.size()));
163 for (const Weight &W : Weights)
164 combineWeight(Combined[W.TargetNode.Index], W);
165
166 // Check whether anything changed.
167 if (Weights.size() == Combined.size())
168 return;
169
170 // Fill in the new weights.
171 Weights.clear();
172 Weights.reserve(Combined.size());
173 for (const auto &I : Combined)
174 Weights.push_back(I.second);
175}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000176
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000177static void combineWeights(WeightList &Weights) {
178 // Use a hash table for many successors to keep this linear.
179 if (Weights.size() > 128) {
180 combineWeightsByHashing(Weights);
181 return;
182 }
183
184 combineWeightsBySorting(Weights);
185}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000186
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000187static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
188 assert(Shift >= 0);
189 assert(Shift < 64);
190 if (!Shift)
191 return N;
192 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
193}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000194
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000195void Distribution::normalize() {
196 // Early exit for termination nodes.
197 if (Weights.empty())
198 return;
199
200 // Only bother if there are multiple successors.
201 if (Weights.size() > 1)
202 combineWeights(Weights);
203
204 // Early exit when combined into a single successor.
205 if (Weights.size() == 1) {
206 Total = 1;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000207 Weights.front().Amount = 1;
208 return;
209 }
210
211 // Determine how much to shift right so that the total fits into 32-bits.
212 //
213 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
214 // for each weight can cause a 32-bit overflow.
215 int Shift = 0;
216 if (DidOverflow)
217 Shift = 33;
218 else if (Total > UINT32_MAX)
219 Shift = 33 - countLeadingZeros(Total);
220
221 // Early exit if nothing needs to be scaled.
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000222 if (!Shift) {
223 // If we didn't overflow then combineWeights() shouldn't have changed the
224 // sum of the weights, but let's double-check.
225 assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
226 [](uint64_t Sum, const Weight &W) {
227 return Sum + W.Amount;
228 }) &&
229 "Expected total to be correct");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000230 return;
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000231 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000232
233 // Recompute the total through accumulation (rather than shifting it) so that
Duncan P. N. Exon Smith57cbdfc2014-12-05 19:13:42 +0000234 // it's accurate after shifting and any changes combineWeights() made above.
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000235 Total = 0;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000236
237 // Sum the weights to each node and shift right if necessary.
238 for (Weight &W : Weights) {
239 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
240 // can round here without concern about overflow.
241 assert(W.TargetNode.isValid());
242 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
243 assert(W.Amount <= UINT32_MAX);
244
245 // Update the total.
246 Total += W.Amount;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000247 }
248 assert(Total <= UINT32_MAX);
249}
250
251void BlockFrequencyInfoImplBase::clear() {
Duncan P. N. Exon Smithdc2d66e2014-04-22 03:31:34 +0000252 // Swap with a default-constructed std::vector, since std::vector<>::clear()
253 // does not actually clear heap storage.
254 std::vector<FrequencyData>().swap(Freqs);
255 std::vector<WorkingData>().swap(Working);
Duncan P. N. Exon Smithfc7dc932014-04-25 04:30:06 +0000256 Loops.clear();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000257}
258
259/// \brief Clear all memory not needed downstream.
260///
261/// Releases all memory not used downstream. In particular, saves Freqs.
262static void cleanup(BlockFrequencyInfoImplBase &BFI) {
263 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
264 BFI.clear();
265 BFI.Freqs = std::move(SavedFreqs);
266}
267
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000268bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000269 const LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000270 const BlockNode &Pred,
271 const BlockNode &Succ,
272 uint64_t Weight) {
273 if (!Weight)
274 Weight = 1;
275
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000276 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
277 return OuterLoop && OuterLoop->isHeader(Node);
278 };
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000279
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000280 BlockNode Resolved = Working[Succ.Index].getResolvedNode();
281
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000282#ifndef NDEBUG
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000283 auto debugSuccessor = [&](const char *Type) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000284 dbgs() << " =>"
285 << " [" << Type << "] weight = " << Weight;
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000286 if (!isLoopHeader(Resolved))
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000287 dbgs() << ", succ = " << getBlockName(Succ);
288 if (Resolved != Succ)
289 dbgs() << ", resolved = " << getBlockName(Resolved);
290 dbgs() << "\n";
291 };
292 (void)debugSuccessor;
293#endif
294
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000295 if (isLoopHeader(Resolved)) {
296 DEBUG(debugSuccessor("backedge"));
Diego Novillo9a779622015-06-16 19:10:58 +0000297 Dist.addBackedge(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000298 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000299 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000300
Duncan P. N. Exon Smith39cc6482014-04-25 04:38:06 +0000301 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000302 DEBUG(debugSuccessor(" exit "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000303 Dist.addExit(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000304 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000305 }
306
Duncan P. N. Exon Smithb3380ea2014-04-22 03:31:53 +0000307 if (Resolved < Pred) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000308 if (!isLoopHeader(Pred)) {
309 // If OuterLoop is an irreducible loop, we can't actually handle this.
310 assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
311 "unhandled irreducible control flow");
312
313 // Irreducible backedge. Abort.
314 DEBUG(debugSuccessor("abort!!!"));
315 return false;
316 }
317
318 // If "Pred" is a loop header, then this isn't really a backedge; rather,
319 // OuterLoop must be irreducible. These false backedges can come only from
320 // secondary loop headers.
321 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
322 "unhandled irreducible control flow");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000323 }
324
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000325 DEBUG(debugSuccessor(" local "));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000326 Dist.addLocal(Resolved, Weight);
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000327 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000328}
329
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000330bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000331 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000332 // Copy the exit map into Dist.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000333 for (const auto &I : Loop.Exits)
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000334 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
335 I.second.getMass()))
336 // Irreducible backedge.
337 return false;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000338
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000339 return true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000340}
341
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000342/// \brief Compute the loop scale for a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000343void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000344 // Compute loop scale.
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000345 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000346
Diego Novilloa354f482015-04-01 17:42:27 +0000347 // Infinite loops need special handling. If we give the back edge an infinite
348 // mass, they may saturate all the other scales in the function down to 1,
349 // making all the other region temperatures look exactly the same. Choose an
350 // arbitrary scale to avoid these issues.
351 //
352 // FIXME: An alternate way would be to select a symbolic scale which is later
353 // replaced to be the maximum of all computed scales plus 1. This would
354 // appropriately describe the loop as having a large scale, without skewing
355 // the final frequency computation.
Sanjay Patel0fb98802016-05-09 16:07:45 +0000356 const Scaled64 InfiniteLoopScale(1, 12);
Diego Novilloa354f482015-04-01 17:42:27 +0000357
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000358 // LoopScale == 1 / ExitMass
359 // ExitMass == HeadMass - BackedgeMass
Diego Novillo9a779622015-06-16 19:10:58 +0000360 BlockMass TotalBackedgeMass;
361 for (auto &Mass : Loop.BackedgeMass)
362 TotalBackedgeMass += Mass;
363 BlockMass ExitMass = BlockMass::getFull() - TotalBackedgeMass;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000364
Diego Novilloa354f482015-04-01 17:42:27 +0000365 // Block scale stores the inverse of the scale. If this is an infinite loop,
366 // its exit mass will be zero. In this case, use an arbitrary scale for the
367 // loop scale.
368 Loop.Scale =
Sanjay Patel0fb98802016-05-09 16:07:45 +0000369 ExitMass.isEmpty() ? InfiniteLoopScale : ExitMass.toScaled().inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000370
371 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull()
Diego Novillo9a779622015-06-16 19:10:58 +0000372 << " - " << TotalBackedgeMass << ")\n"
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000373 << " - scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000374}
375
376/// \brief Package up a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000377void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000378 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
379
380 // Clear the subloop exits to prevent quadratic memory usage.
381 for (const BlockNode &M : Loop.Nodes) {
382 if (auto *Loop = Working[M.Index].getPackagedLoop())
383 Loop->Exits.clear();
384 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
385 }
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000386 Loop.IsPackaged = true;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000387}
388
Diego Novillo9a779622015-06-16 19:10:58 +0000389#ifndef NDEBUG
390static void debugAssign(const BlockFrequencyInfoImplBase &BFI,
391 const DitheringDistributer &D, const BlockNode &T,
392 const BlockMass &M, const char *Desc) {
393 dbgs() << " => assign " << M << " (" << D.RemMass << ")";
394 if (Desc)
395 dbgs() << " [" << Desc << "]";
396 if (T.isValid())
397 dbgs() << " to " << BFI.getBlockName(T);
398 dbgs() << "\n";
399}
400#endif
401
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000402void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000403 LoopData *OuterLoop,
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000404 Distribution &Dist) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000405 BlockMass Mass = Working[Source.Index].getMass();
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000406 DEBUG(dbgs() << " => mass: " << Mass << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000407
408 // Distribute mass to successors as laid out in Dist.
409 DitheringDistributer D(Dist, Mass);
410
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000411 for (const Weight &W : Dist.Weights) {
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000412 // Check for a local edge (non-backedge and non-exit).
413 BlockMass Taken = D.takeMass(W.Amount);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000414 if (W.Type == Weight::Local) {
Duncan P. N. Exon Smithda5eaed2014-04-25 18:47:04 +0000415 Working[W.TargetNode.Index].getMass() += Taken;
Diego Novillo9a779622015-06-16 19:10:58 +0000416 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000417 continue;
418 }
419
420 // Backedges and exits only make sense if we're processing a loop.
Duncan P. N. Exon Smithd1320402014-04-25 04:38:01 +0000421 assert(OuterLoop && "backedge or exit outside of loop");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000422
423 // Check for a backedge.
424 if (W.Type == Weight::Backedge) {
Diego Novillo8c49a572015-06-17 16:28:22 +0000425 OuterLoop->BackedgeMass[OuterLoop->getHeaderIndex(W.TargetNode)] += Taken;
Diego Novillo9a779622015-06-16 19:10:58 +0000426 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "back"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000427 continue;
428 }
429
430 // This must be an exit.
431 assert(W.Type == Weight::Exit);
Duncan P. N. Exon Smithcb7d29d2014-04-25 04:38:43 +0000432 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
Diego Novillo9a779622015-06-16 19:10:58 +0000433 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "exit"));
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000434 }
435}
436
437static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000438 const Scaled64 &Min, const Scaled64 &Max) {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000439 // Scale the Factor to a size that creates integers. Ideally, integers would
440 // be scaled so that Max == UINT64_MAX so that they can be best
Diego Novilloa354f482015-04-01 17:42:27 +0000441 // differentiated. However, in the presence of large frequency values, small
442 // frequencies are scaled down to 1, making it impossible to differentiate
443 // small, unequal numbers. When the spread between Min and Max frequencies
444 // fits well within MaxBits, we make the scale be at least 8.
445 const unsigned MaxBits = 64;
446 const unsigned SpreadBits = (Max / Min).lg();
447 Scaled64 ScalingFactor;
448 if (SpreadBits <= MaxBits - 3) {
449 // If the values are small enough, make the scaling factor at least 8 to
450 // allow distinguishing small values.
451 ScalingFactor = Min.inverse();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000452 ScalingFactor <<= 3;
Diego Novilloa354f482015-04-01 17:42:27 +0000453 } else {
454 // If the values need more than MaxBits to be represented, saturate small
455 // frequency values down to 1 by using a scaling factor that benefits large
456 // frequency values.
457 ScalingFactor = Scaled64(1, MaxBits) / Max;
458 }
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000459
460 // Translate the floats to integers.
461 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
462 << ", factor = " << ScalingFactor << "\n");
463 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000464 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000465 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
466 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000467 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000468 << ", int = " << BFI.Freqs[Index].Integer << "\n");
469 }
470}
471
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000472/// \brief Unwrap a loop package.
473///
474/// Visits all the members of a loop, adjusting their BlockData according to
475/// the loop's pseudo-node.
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000476static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000477 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000478 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
479 << "\n");
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000480 Loop.Scale *= Loop.Mass.toScaled();
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000481 Loop.IsPackaged = false;
Duncan P. N. Exon Smith3f086782014-04-25 04:38:32 +0000482 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000483
484 // Propagate the head scale through the loop. Since members are visited in
485 // RPO, the head scale will be updated by the loop scale first, and then the
486 // final head scale will be used for updated the rest of the members.
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000487 for (const BlockNode &N : Loop.Nodes) {
488 const auto &Working = BFI.Working[N.Index];
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000489 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
490 : BFI.Freqs[N.Index].Scaled;
491 Scaled64 New = Loop.Scale * F;
Duncan P. N. Exon Smith5291d2a2014-04-25 04:38:27 +0000492 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New
493 << "\n");
494 F = New;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000495 }
496}
497
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000498void BlockFrequencyInfoImplBase::unwrapLoops() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000499 // Set initial frequencies from loop-local masses.
500 for (size_t Index = 0; Index < Working.size(); ++Index)
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000501 Freqs[Index].Scaled = Working[Index].Mass.toScaled();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000502
Duncan P. N. Exon Smithda0b21c2014-04-25 04:38:23 +0000503 for (LoopData &Loop : Loops)
Duncan P. N. Exon Smith0633f0e2014-04-25 04:38:25 +0000504 unwrapLoop(*this, Loop);
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000505}
506
507void BlockFrequencyInfoImplBase::finalizeMetrics() {
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000508 // Unwrap loop packages in reverse post-order, tracking min and max
509 // frequencies.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000510 auto Min = Scaled64::getLargest();
511 auto Max = Scaled64::getZero();
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000512 for (size_t Index = 0; Index < Working.size(); ++Index) {
Duncan P. N. Exon Smith46d9a562014-04-25 04:38:17 +0000513 // Update min/max scale.
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000514 Min = std::min(Min, Freqs[Index].Scaled);
515 Max = std::max(Max, Freqs[Index].Scaled);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000516 }
517
518 // Convert to integers.
519 convertFloatingToInteger(*this, Min, Max);
520
521 // Clean up data structures.
522 cleanup(*this);
523
524 // Print out the final stats.
525 DEBUG(dump());
526}
527
528BlockFrequency
529BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
530 if (!Node.isValid())
531 return 0;
532 return Freqs[Node.Index].Integer;
533}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000534
Xinliang David Lib12b3532016-06-22 17:12:12 +0000535Optional<uint64_t>
536BlockFrequencyInfoImplBase::getBlockProfileCount(const Function &F,
537 const BlockNode &Node) const {
Sean Silvaf8015752016-08-02 02:15:45 +0000538 return getProfileCountFromFreq(F, getBlockFreq(Node).getFrequency());
539}
540
541Optional<uint64_t>
542BlockFrequencyInfoImplBase::getProfileCountFromFreq(const Function &F,
543 uint64_t Freq) const {
Xinliang David Lib12b3532016-06-22 17:12:12 +0000544 auto EntryCount = F.getEntryCount();
545 if (!EntryCount)
546 return None;
547 // Use 128 bit APInt to do the arithmetic to avoid overflow.
548 APInt BlockCount(128, EntryCount.getValue());
Sean Silvaf8015752016-08-02 02:15:45 +0000549 APInt BlockFreq(128, Freq);
Xinliang David Lib12b3532016-06-22 17:12:12 +0000550 APInt EntryFreq(128, getEntryFreq());
551 BlockCount *= BlockFreq;
552 BlockCount = BlockCount.udiv(EntryFreq);
553 return BlockCount.getLimitedValue();
554}
555
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000556Scaled64
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000557BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
558 if (!Node.isValid())
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000559 return Scaled64::getZero();
560 return Freqs[Node.Index].Scaled;
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000561}
562
Manman Ren72d44b12015-10-15 14:59:40 +0000563void BlockFrequencyInfoImplBase::setBlockFreq(const BlockNode &Node,
564 uint64_t Freq) {
565 assert(Node.isValid() && "Expected valid node");
566 assert(Node.Index < Freqs.size() && "Expected legal index");
567 Freqs[Node.Index].Integer = Freq;
568}
569
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000570std::string
571BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
572 return std::string();
573}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000574
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000575std::string
576BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
577 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
578}
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000579
580raw_ostream &
581BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
582 const BlockNode &Node) const {
583 return OS << getFloatingBlockFreq(Node);
584}
585
586raw_ostream &
587BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
588 const BlockFrequency &Freq) const {
Duncan P. N. Exon Smithbeaf8132014-06-24 00:26:13 +0000589 Scaled64 Block(Freq.getFrequency(), 0);
590 Scaled64 Entry(getEntryFreq(), 0);
Duncan P. N. Exon Smith10be9a82014-04-21 17:57:07 +0000591
592 return OS << Block / Entry;
593}
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000594
595void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
596 Start = OuterLoop.getHeader();
597 Nodes.reserve(OuterLoop.Nodes.size());
598 for (auto N : OuterLoop.Nodes)
599 addNode(N);
600 indexNodes();
601}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000602
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000603void IrreducibleGraph::addNodesInFunction() {
604 Start = 0;
605 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
606 if (!BFI.Working[Index].isPackaged())
607 addNode(Index);
608 indexNodes();
609}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000610
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000611void IrreducibleGraph::indexNodes() {
612 for (auto &I : Nodes)
613 Lookup[I.Node.Index] = &I;
614}
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000615
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000616void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
617 const BFIBase::LoopData *OuterLoop) {
618 if (OuterLoop && OuterLoop->isHeader(Succ))
619 return;
620 auto L = Lookup.find(Succ.Index);
621 if (L == Lookup.end())
622 return;
623 IrrNode &SuccIrr = *L->second;
624 Irr.Edges.push_back(&SuccIrr);
625 SuccIrr.Edges.push_front(&Irr);
626 ++SuccIrr.NumIn;
627}
628
629namespace llvm {
630template <> struct GraphTraits<IrreducibleGraph> {
631 typedef bfi_detail::IrreducibleGraph GraphT;
632
Tim Shenb44909e2016-08-01 22:32:20 +0000633 typedef const GraphT::IrrNode *NodeRef;
Duncan P. N. Exon Smith295b5e72014-04-28 20:22:29 +0000634 typedef GraphT::IrrNode::iterator ChildIteratorType;
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000635
Tim Shenf2187ed2016-08-22 21:09:30 +0000636 static NodeRef getEntryNode(const GraphT &G) { return G.StartIrr; }
637 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
638 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000639};
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000640} // end namespace llvm
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000641
642/// \brief Find extra irreducible headers.
643///
644/// Find entry blocks and other blocks with backedges, which exist when \c G
645/// contains irreducible sub-SCCs.
646static void findIrreducibleHeaders(
647 const BlockFrequencyInfoImplBase &BFI,
648 const IrreducibleGraph &G,
649 const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
650 LoopData::NodeList &Headers, LoopData::NodeList &Others) {
651 // Map from nodes in the SCC to whether it's an entry block.
652 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
653
654 // InSCC also acts the set of nodes in the graph. Seed it.
655 for (const auto *I : SCC)
656 InSCC[I] = false;
657
658 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
659 auto &Irr = *I->first;
660 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
661 if (InSCC.count(P))
662 continue;
663
664 // This is an entry block.
665 I->second = true;
666 Headers.push_back(Irr.Node);
667 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n");
668 break;
669 }
670 }
Duncan P. N. Exon Smitha7a90a22014-10-06 17:42:00 +0000671 assert(Headers.size() >= 2 &&
672 "Expected irreducible CFG; -loop-info is likely invalid");
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000673 if (Headers.size() == InSCC.size()) {
674 // Every block is a header.
675 std::sort(Headers.begin(), Headers.end());
676 return;
677 }
678
679 // Look for extra headers from irreducible sub-SCCs.
680 for (const auto &I : InSCC) {
681 // Entry blocks are already headers.
682 if (I.second)
683 continue;
684
685 auto &Irr = *I.first;
686 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
687 // Skip forward edges.
688 if (P->Node < Irr.Node)
689 continue;
690
691 // Skip predecessors from entry blocks. These can have inverted
692 // ordering.
693 if (InSCC.lookup(P))
694 continue;
695
696 // Store the extra header.
697 Headers.push_back(Irr.Node);
698 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n");
699 break;
700 }
701 if (Headers.back() == Irr.Node)
702 // Added this as a header.
703 continue;
704
705 // This is not a header.
706 Others.push_back(Irr.Node);
707 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
708 }
709 std::sort(Headers.begin(), Headers.end());
710 std::sort(Others.begin(), Others.end());
711}
712
713static void createIrreducibleLoop(
714 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
715 LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
716 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
717 // Translate the SCC into RPO.
718 DEBUG(dbgs() << " - found-scc\n");
719
720 LoopData::NodeList Headers;
721 LoopData::NodeList Others;
722 findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
723
724 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
725 Headers.end(), Others.begin(), Others.end());
726
727 // Update loop hierarchy.
728 for (const auto &N : Loop->Nodes)
729 if (BFI.Working[N.Index].isLoopHeader())
730 BFI.Working[N.Index].Loop->Parent = &*Loop;
731 else
732 BFI.Working[N.Index].Loop = &*Loop;
733}
734
735iterator_range<std::list<LoopData>::iterator>
736BlockFrequencyInfoImplBase::analyzeIrreducible(
737 const IrreducibleGraph &G, LoopData *OuterLoop,
738 std::list<LoopData>::iterator Insert) {
739 assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
740 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
741
742 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
743 if (I->size() < 2)
744 continue;
745
746 // Translate the SCC into RPO.
747 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
748 }
749
750 if (OuterLoop)
751 return make_range(std::next(Prev), Insert);
752 return make_range(Loops.begin(), Insert);
753}
754
755void
756BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
757 OuterLoop.Exits.clear();
Diego Novillo9a779622015-06-16 19:10:58 +0000758 for (auto &Mass : OuterLoop.BackedgeMass)
759 Mass = BlockMass::getEmpty();
Duncan P. N. Exon Smithc5a31392014-04-28 20:02:29 +0000760 auto O = OuterLoop.Nodes.begin() + 1;
761 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
762 if (!Working[I->Index].isPackaged())
763 *O++ = *I;
764 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
765}
Diego Novillo9a779622015-06-16 19:10:58 +0000766
767void BlockFrequencyInfoImplBase::adjustLoopHeaderMass(LoopData &Loop) {
768 assert(Loop.isIrreducible() && "this only makes sense on irreducible loops");
769
770 // Since the loop has more than one header block, the mass flowing back into
771 // each header will be different. Adjust the mass in each header loop to
772 // reflect the masses flowing through back edges.
773 //
774 // To do this, we distribute the initial mass using the backedge masses
775 // as weights for the distribution.
776 BlockMass LoopMass = BlockMass::getFull();
777 Distribution Dist;
778
779 DEBUG(dbgs() << "adjust-loop-header-mass:\n");
780 for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
781 auto &HeaderNode = Loop.Nodes[H];
Diego Novillo8c49a572015-06-17 16:28:22 +0000782 auto &BackedgeMass = Loop.BackedgeMass[Loop.getHeaderIndex(HeaderNode)];
Diego Novillo9a779622015-06-16 19:10:58 +0000783 DEBUG(dbgs() << " - Add back edge mass for node "
784 << getBlockName(HeaderNode) << ": " << BackedgeMass << "\n");
Diego Novillof9aa39b2015-09-08 19:22:17 +0000785 if (BackedgeMass.getMass() > 0)
786 Dist.addLocal(HeaderNode, BackedgeMass.getMass());
787 else
788 DEBUG(dbgs() << " Nothing added. Back edge mass is zero\n");
Diego Novillo9a779622015-06-16 19:10:58 +0000789 }
790
791 DitheringDistributer D(Dist, LoopMass);
792
793 DEBUG(dbgs() << " Distribute loop mass " << LoopMass
794 << " to headers using above weights\n");
795 for (const Weight &W : Dist.Weights) {
796 BlockMass Taken = D.takeMass(W.Amount);
797 assert(W.Type == Weight::Local && "all weights should be local");
798 Working[W.TargetNode.Index].getMass() = Taken;
799 DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
800 }
801}