blob: cab18a124061fc855878048612ecaa91d3650917 [file] [log] [blame]
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +00001//===-- SpillPlacement.cpp - Optimal Spill Code Placement -----------------===//
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// This file implements the spill code placement analysis.
11//
12// Each edge bundle corresponds to a node in a Hopfield network. Constraints on
13// basic blocks are weighted by the block frequency and added to become the node
14// bias.
15//
16// Transparent basic blocks have the variable live through, but don't care if it
17// is spilled or in a register. These blocks become connections in the Hopfield
18// network, again weighted by block frequency.
19//
20// The Hopfield network minimizes (possibly locally) its energy function:
21//
22// E = -sum_n V_n * ( B_n + sum_{n, m linked by b} V_m * F_b )
23//
24// The energy function represents the expected spill code execution frequency,
25// or the cost of spilling. This is a Lyapunov function which never increases
26// when a node is updated. It is guaranteed to converge to a local minimum.
27//
28//===----------------------------------------------------------------------===//
29
Jakob Stoklund Olesenfc7d7752011-01-19 23:14:59 +000030#define DEBUG_TYPE "spillplacement"
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +000031#include "SpillPlacement.h"
32#include "llvm/CodeGen/EdgeBundles.h"
33#include "llvm/CodeGen/LiveIntervalAnalysis.h"
34#include "llvm/CodeGen/MachineBasicBlock.h"
35#include "llvm/CodeGen/MachineFunction.h"
36#include "llvm/CodeGen/MachineLoopInfo.h"
37#include "llvm/CodeGen/Passes.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/Format.h"
40
41using namespace llvm;
42
43char SpillPlacement::ID = 0;
44INITIALIZE_PASS_BEGIN(SpillPlacement, "spill-code-placement",
45 "Spill Code Placement Analysis", true, true)
46INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
47INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
48INITIALIZE_PASS_END(SpillPlacement, "spill-code-placement",
49 "Spill Code Placement Analysis", true, true)
50
51char &llvm::SpillPlacementID = SpillPlacement::ID;
52
53void SpillPlacement::getAnalysisUsage(AnalysisUsage &AU) const {
54 AU.setPreservesAll();
55 AU.addRequiredTransitive<EdgeBundles>();
56 AU.addRequiredTransitive<MachineLoopInfo>();
57 MachineFunctionPass::getAnalysisUsage(AU);
58}
59
60/// Node - Each edge bundle corresponds to a Hopfield node.
61///
62/// The node contains precomputed frequency data that only depends on the CFG,
63/// but Bias and Links are computed each time placeSpills is called.
64///
65/// The node Value is positive when the variable should be in a register. The
66/// value can change when linked nodes change, but convergence is very fast
67/// because all weights are positive.
68///
69struct SpillPlacement::Node {
Jakob Stoklund Olesen0bd2bd92011-04-07 17:27:48 +000070 /// Scale - Inverse block frequency feeding into[0] or out of[1] the bundle.
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +000071 /// Ideally, these two numbers should be identical, but inaccuracies in the
72 /// block frequency estimates means that we need to normalize ingoing and
73 /// outgoing frequencies separately so they are commensurate.
Jakob Stoklund Olesen0bd2bd92011-04-07 17:27:48 +000074 float Scale[2];
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +000075
76 /// Bias - Normalized contributions from non-transparent blocks.
77 /// A bundle connected to a MustSpill block has a huge negative bias,
78 /// otherwise it is a number in the range [-2;2].
79 float Bias;
80
81 /// Value - Output value of this node computed from the Bias and links.
82 /// This is always in the range [-1;1]. A positive number means the variable
83 /// should go in a register through this bundle.
84 float Value;
85
86 typedef SmallVector<std::pair<float, unsigned>, 4> LinkVector;
87
88 /// Links - (Weight, BundleNo) for all transparent blocks connecting to other
89 /// bundles. The weights are all positive and add up to at most 2, weights
90 /// from ingoing and outgoing nodes separately add up to a most 1. The weight
91 /// sum can be less than 2 when the variable is not live into / out of some
92 /// connected basic blocks.
93 LinkVector Links;
94
95 /// preferReg - Return true when this node prefers to be in a register.
96 bool preferReg() const {
97 // Undecided nodes (Value==0) go on the stack.
98 return Value > 0;
99 }
100
101 /// mustSpill - Return True if this node is so biased that it must spill.
102 bool mustSpill() const {
103 // Actually, we must spill if Bias < sum(weights).
104 // It may be worth it to compute the weight sum here?
105 return Bias < -2.0f;
106 }
107
108 /// Node - Create a blank Node.
109 Node() {
Jakob Stoklund Olesen0bd2bd92011-04-07 17:27:48 +0000110 Scale[0] = Scale[1] = 0;
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000111 }
112
113 /// clear - Reset per-query data, but preserve frequencies that only depend on
114 // the CFG.
115 void clear() {
116 Bias = Value = 0;
117 Links.clear();
118 }
119
120 /// addLink - Add a link to bundle b with weight w.
121 /// out=0 for an ingoing link, and 1 for an outgoing link.
122 void addLink(unsigned b, float w, bool out) {
123 // Normalize w relative to all connected blocks from that direction.
Jakob Stoklund Olesen0bd2bd92011-04-07 17:27:48 +0000124 w *= Scale[out];
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000125
126 // There can be multiple links to the same bundle, add them up.
127 for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)
128 if (I->second == b) {
129 I->first += w;
130 return;
131 }
132 // This must be the first link to b.
133 Links.push_back(std::make_pair(w, b));
134 }
135
136 /// addBias - Bias this node from an ingoing[0] or outgoing[1] link.
Jakob Stoklund Olesen70d43702011-04-06 19:14:00 +0000137 /// Return the change to the total number of positive biases.
138 int addBias(float w, bool out) {
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000139 // Normalize w relative to all connected blocks from that direction.
Jakob Stoklund Olesen0bd2bd92011-04-07 17:27:48 +0000140 w *= Scale[out];
Jakob Stoklund Olesen70d43702011-04-06 19:14:00 +0000141 int Before = Bias > 0;
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000142 Bias += w;
Jakob Stoklund Olesen70d43702011-04-06 19:14:00 +0000143 int After = Bias > 0;
144 return After - Before;
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000145 }
146
147 /// update - Recompute Value from Bias and Links. Return true when node
148 /// preference changes.
149 bool update(const Node nodes[]) {
150 // Compute the weighted sum of inputs.
151 float Sum = Bias;
152 for (LinkVector::iterator I = Links.begin(), E = Links.end(); I != E; ++I)
153 Sum += I->first * nodes[I->second].Value;
154
155 // The weighted sum is going to be in the range [-2;2]. Ideally, we should
156 // simply set Value = sign(Sum), but we will add a dead zone around 0 for
157 // two reasons:
158 // 1. It avoids arbitrary bias when all links are 0 as is possible during
159 // initial iterations.
160 // 2. It helps tame rounding errors when the links nominally sum to 0.
Jakob Stoklund Olesen9590c7f2011-02-03 17:04:12 +0000161 const float Thres = 1e-4f;
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000162 bool Before = preferReg();
163 if (Sum < -Thres)
164 Value = -1;
165 else if (Sum > Thres)
166 Value = 1;
167 else
168 Value = 0;
169 return Before != preferReg();
170 }
171};
172
173bool SpillPlacement::runOnMachineFunction(MachineFunction &mf) {
174 MF = &mf;
175 bundles = &getAnalysis<EdgeBundles>();
176 loops = &getAnalysis<MachineLoopInfo>();
177
178 assert(!nodes && "Leaking node array");
179 nodes = new Node[bundles->getNumBundles()];
180
181 // Compute total ingoing and outgoing block frequencies for all bundles.
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +0000182 BlockFrequency.resize(mf.getNumBlockIDs());
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000183 for (MachineFunction::iterator I = mf.begin(), E = mf.end(); I != E; ++I) {
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +0000184 float Freq = LiveIntervals::getSpillWeight(true, false,
185 loops->getLoopDepth(I));
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000186 unsigned Num = I->getNumber();
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +0000187 BlockFrequency[Num] = Freq;
Jakob Stoklund Olesen0bd2bd92011-04-07 17:27:48 +0000188 nodes[bundles->getBundle(Num, 1)].Scale[0] += Freq;
189 nodes[bundles->getBundle(Num, 0)].Scale[1] += Freq;
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000190 }
191
Jakob Stoklund Olesen0bd2bd92011-04-07 17:27:48 +0000192 // Scales are reciprocal frequencies.
193 for (unsigned i = 0, e = bundles->getNumBundles(); i != e; ++i)
194 for (unsigned d = 0; d != 2; ++d)
195 if (nodes[i].Scale[d] > 0)
196 nodes[i].Scale[d] = 1 / nodes[i].Scale[d];
197
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000198 // We never change the function.
199 return false;
200}
201
202void SpillPlacement::releaseMemory() {
203 delete[] nodes;
204 nodes = 0;
205}
206
207/// activate - mark node n as active if it wasn't already.
208void SpillPlacement::activate(unsigned n) {
209 if (ActiveNodes->test(n))
210 return;
211 ActiveNodes->set(n);
212 nodes[n].clear();
213}
214
215
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000216/// addConstraints - Compute node biases and weights from a set of constraints.
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000217/// Set a bit in NodeMask for each active node.
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000218void SpillPlacement::addConstraints(ArrayRef<BlockConstraint> LiveBlocks) {
219 for (ArrayRef<BlockConstraint>::iterator I = LiveBlocks.begin(),
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000220 E = LiveBlocks.end(); I != E; ++I) {
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +0000221 float Freq = getBlockFrequency(I->Number);
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000222 const float Bias[] = {
223 0, // DontCare,
224 1, // PrefReg,
225 -1, // PrefSpill
226 -HUGE_VALF // MustSpill
227 };
228
229 // Live-in to block?
230 if (I->Entry != DontCare) {
231 unsigned ib = bundles->getBundle(I->Number, 0);
232 activate(ib);
Jakob Stoklund Olesen70d43702011-04-06 19:14:00 +0000233 PositiveNodes += nodes[ib].addBias(Freq * Bias[I->Entry], 1);
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000234 }
235
236 // Live-out from block?
237 if (I->Exit != DontCare) {
238 unsigned ob = bundles->getBundle(I->Number, 1);
239 activate(ob);
Jakob Stoklund Olesen70d43702011-04-06 19:14:00 +0000240 PositiveNodes += nodes[ob].addBias(Freq * Bias[I->Exit], 0);
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000241 }
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000242 }
243}
244
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000245void SpillPlacement::addLinks(ArrayRef<unsigned> Links) {
246 for (ArrayRef<unsigned>::iterator I = Links.begin(), E = Links.end(); I != E;
247 ++I) {
248 unsigned Number = *I;
249 unsigned ib = bundles->getBundle(Number, 0);
250 unsigned ob = bundles->getBundle(Number, 1);
251
252 // Ignore self-loops.
253 if (ib == ob)
254 continue;
255 activate(ib);
256 activate(ob);
257 float Freq = getBlockFrequency(Number);
258 nodes[ib].addLink(ob, Freq, 1);
259 nodes[ob].addLink(ib, Freq, 0);
260 }
261}
262
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000263/// iterate - Repeatedly update the Hopfield nodes until stability or the
264/// maximum number of iterations is reached.
265/// @param Linked - Numbers of linked nodes that need updating.
266void SpillPlacement::iterate(const SmallVectorImpl<unsigned> &Linked) {
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000267 if (Linked.empty())
268 return;
269
270 // Run up to 10 iterations. The edge bundle numbering is closely related to
271 // basic block numbering, so there is a strong tendency towards chains of
272 // linked nodes with sequential numbers. By scanning the linked nodes
273 // backwards and forwards, we make it very likely that a single node can
274 // affect the entire network in a single iteration. That means very fast
275 // convergence, usually in a single iteration.
276 for (unsigned iteration = 0; iteration != 10; ++iteration) {
277 // Scan backwards, skipping the last node which was just updated.
278 bool Changed = false;
279 for (SmallVectorImpl<unsigned>::const_reverse_iterator I =
280 llvm::next(Linked.rbegin()), E = Linked.rend(); I != E; ++I) {
281 unsigned n = *I;
282 bool C = nodes[n].update(nodes);
283 Changed |= C;
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000284 }
285 if (!Changed)
286 return;
287
288 // Scan forwards, skipping the first node which was just updated.
289 Changed = false;
290 for (SmallVectorImpl<unsigned>::const_iterator I =
291 llvm::next(Linked.begin()), E = Linked.end(); I != E; ++I) {
292 unsigned n = *I;
293 bool C = nodes[n].update(nodes);
294 Changed |= C;
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000295 }
296 if (!Changed)
297 return;
298 }
299}
300
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000301void SpillPlacement::prepare(BitVector &RegBundles) {
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000302 // Reuse RegBundles as our ActiveNodes vector.
303 ActiveNodes = &RegBundles;
304 ActiveNodes->clear();
305 ActiveNodes->resize(bundles->getNumBundles());
Jakob Stoklund Olesen70d43702011-04-06 19:14:00 +0000306 PositiveNodes = 0;
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000307}
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000308
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000309bool
310SpillPlacement::finish() {
311 assert(ActiveNodes && "Call prepare() first");
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000312 // Update all active nodes, and find the ones that are actually linked to
313 // something so their value may change when iterating.
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000314 SmallVector<unsigned, 8> Linked;
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000315 for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n)) {
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000316 nodes[n].update(nodes);
317 // A node that must spill, or a node without any links is not going to
318 // change its value ever again, so exclude it from iterations.
319 if (!nodes[n].Links.empty() && !nodes[n].mustSpill())
320 Linked.push_back(n);
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000321 }
322
323 // Iterate the network to convergence.
324 iterate(Linked);
325
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000326 // Write preferences back to ActiveNodes.
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000327 bool Perfect = true;
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000328 for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n))
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000329 if (!nodes[n].preferReg()) {
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000330 ActiveNodes->reset(n);
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000331 Perfect = false;
332 }
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +0000333 ActiveNodes = 0;
Jakob Stoklund Olesen8bfe5082011-01-06 01:21:53 +0000334 return Perfect;
335}