blob: c3663d3651d0c19792d82ff018b1ac863da2c183 [file] [log] [blame]
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001//===-------- InlineSpiller.cpp - Insert spills and restores inline -------===//
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// The inline spiller modifies the machine function directly instead of
11// inserting spills and restores in VirtRegMap.
12//
13//===----------------------------------------------------------------------===//
14
Jakob Stoklund Olesen376dcbd2010-11-03 20:39:23 +000015#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000016#include "Spiller.h"
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +000017#include "LiveRangeEdit.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000018#include "VirtRegMap.h"
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000019#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesene93198a2010-11-10 23:55:56 +000020#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000021#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesen0a12b802010-10-26 00:11:35 +000022#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000023#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000024#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
28#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32
33using namespace llvm;
34
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000035STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
36STATISTIC(NumSnippets, "Number of snippets included in spills");
37STATISTIC(NumSpills, "Number of spills inserted");
38STATISTIC(NumReloads, "Number of reloads inserted");
39STATISTIC(NumFolded, "Number of folded stack accesses");
40STATISTIC(NumFoldedLoads, "Number of folded loads");
41STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
42STATISTIC(NumOmitReloadSpill, "Number of omitted spills after reloads");
43STATISTIC(NumHoistLocal, "Number of locally hoisted spills");
44STATISTIC(NumHoistGlobal, "Number of globally hoisted spills");
45STATISTIC(NumRedundantSpills, "Number of redundant spills identified");
46
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000047namespace {
48class InlineSpiller : public Spiller {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000049 MachineFunctionPass &Pass;
50 MachineFunction &MF;
51 LiveIntervals &LIS;
52 LiveStacks &LSS;
53 AliasAnalysis *AA;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000054 MachineDominatorTree &MDT;
55 MachineLoopInfo &Loops;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000056 VirtRegMap &VRM;
57 MachineFrameInfo &MFI;
58 MachineRegisterInfo &MRI;
59 const TargetInstrInfo &TII;
60 const TargetRegisterInfo &TRI;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +000061
62 // Variables that are valid during spill(), but used by multiple methods.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000063 LiveRangeEdit *Edit;
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +000064 LiveInterval *StackInt;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000065 int StackSlot;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000066 unsigned Original;
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000067
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000068 // All registers to spill to StackSlot, including the main register.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +000069 SmallVector<unsigned, 8> RegsToSpill;
70
71 // All COPY instructions to/from snippets.
72 // They are ignored since both operands refer to the same stack slot.
73 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
74
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +000075 // Values that failed to remat at some point.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000076 SmallPtrSet<VNInfo*, 8> UsedValues;
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +000077
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000078 // Information about a value that was defined by a copy from a sibling
79 // register.
80 struct SibValueInfo {
81 // True when all reaching defs were reloads: No spill is necessary.
82 bool AllDefsAreReloads;
83
84 // The preferred register to spill.
85 unsigned SpillReg;
86
87 // The value of SpillReg that should be spilled.
88 VNInfo *SpillVNI;
89
90 // A defining instruction that is not a sibling copy or a reload, or NULL.
91 // This can be used as a template for rematerialization.
92 MachineInstr *DefMI;
93
94 SibValueInfo(unsigned Reg, VNInfo *VNI)
95 : AllDefsAreReloads(false), SpillReg(Reg), SpillVNI(VNI), DefMI(0) {}
96 };
97
98 // Values in RegsToSpill defined by sibling copies.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +000099 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
100 SibValueMap SibValues;
101
102 // Dead defs generated during spilling.
103 SmallVector<MachineInstr*, 8> DeadDefs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000104
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000105 ~InlineSpiller() {}
106
107public:
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000108 InlineSpiller(MachineFunctionPass &pass,
109 MachineFunction &mf,
110 VirtRegMap &vrm)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000111 : Pass(pass),
112 MF(mf),
113 LIS(pass.getAnalysis<LiveIntervals>()),
114 LSS(pass.getAnalysis<LiveStacks>()),
115 AA(&pass.getAnalysis<AliasAnalysis>()),
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000116 MDT(pass.getAnalysis<MachineDominatorTree>()),
117 Loops(pass.getAnalysis<MachineLoopInfo>()),
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000118 VRM(vrm),
119 MFI(*mf.getFrameInfo()),
120 MRI(mf.getRegInfo()),
121 TII(*mf.getTarget().getInstrInfo()),
122 TRI(*mf.getTarget().getRegisterInfo()) {}
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000123
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000124 void spill(LiveRangeEdit &);
125
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000126private:
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000127 bool isSnippet(const LiveInterval &SnipLI);
128 void collectRegsToSpill();
129
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000130 bool isRegToSpill(unsigned Reg) {
131 return std::find(RegsToSpill.begin(),
132 RegsToSpill.end(), Reg) != RegsToSpill.end();
133 }
134
135 bool isSibling(unsigned Reg);
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000136 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000137 void analyzeSiblingValues();
138
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000139 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000140 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000141
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000142 void markValueUsed(LiveInterval*, VNInfo*);
143 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000144 void reMaterializeAll();
145
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000146 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000147 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000148 const SmallVectorImpl<unsigned> &Ops,
149 MachineInstr *LoadMI = 0);
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000150 void insertReload(LiveInterval &NewLI, SlotIndex,
151 MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000152 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000153 SlotIndex, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000154
155 void spillAroundUses(unsigned Reg);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000156 void spillAll();
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000157};
158}
159
160namespace llvm {
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000161Spiller *createInlineSpiller(MachineFunctionPass &pass,
162 MachineFunction &mf,
163 VirtRegMap &vrm) {
164 return new InlineSpiller(pass, mf, vrm);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000165}
166}
167
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000168//===----------------------------------------------------------------------===//
169// Snippets
170//===----------------------------------------------------------------------===//
171
172// When spilling a virtual register, we also spill any snippets it is connected
173// to. The snippets are small live ranges that only have a single real use,
174// leftovers from live range splitting. Spilling them enables memory operand
175// folding or tightens the live range around the single use.
176//
177// This minimizes register pressure and maximizes the store-to-load distance for
178// spill slots which can be important in tight loops.
179
180/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
181/// otherwise return 0.
182static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
183 if (!MI->isCopy())
184 return 0;
185 if (MI->getOperand(0).getSubReg() != 0)
186 return 0;
187 if (MI->getOperand(1).getSubReg() != 0)
188 return 0;
189 if (MI->getOperand(0).getReg() == Reg)
190 return MI->getOperand(1).getReg();
191 if (MI->getOperand(1).getReg() == Reg)
192 return MI->getOperand(0).getReg();
193 return 0;
194}
195
196/// isSnippet - Identify if a live interval is a snippet that should be spilled.
197/// It is assumed that SnipLI is a virtual register with the same original as
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000198/// Edit->getReg().
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000199bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000200 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000201
202 // A snippet is a tiny live range with only a single instruction using it
203 // besides copies to/from Reg or spills/fills. We accept:
204 //
205 // %snip = COPY %Reg / FILL fi#
206 // %snip = USE %snip
207 // %Reg = COPY %snip / SPILL %snip, fi#
208 //
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000209 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000210 return false;
211
212 MachineInstr *UseMI = 0;
213
214 // Check that all uses satisfy our criteria.
215 for (MachineRegisterInfo::reg_nodbg_iterator
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000216 RI = MRI.reg_nodbg_begin(SnipLI.reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000217 MachineInstr *MI = RI.skipInstruction();) {
218
219 // Allow copies to/from Reg.
220 if (isFullCopyOf(MI, Reg))
221 continue;
222
223 // Allow stack slot loads.
224 int FI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000225 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000226 continue;
227
228 // Allow stack slot stores.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000229 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000230 continue;
231
232 // Allow a single additional instruction.
233 if (UseMI && MI != UseMI)
234 return false;
235 UseMI = MI;
236 }
237 return true;
238}
239
240/// collectRegsToSpill - Collect live range snippets that only have a single
241/// real use.
242void InlineSpiller::collectRegsToSpill() {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000243 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000244
245 // Main register always spills.
246 RegsToSpill.assign(1, Reg);
247 SnippetCopies.clear();
248
249 // Snippets all have the same original, so there can't be any for an original
250 // register.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000251 if (Original == Reg)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000252 return;
253
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000254 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000255 MachineInstr *MI = RI.skipInstruction();) {
256 unsigned SnipReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000257 if (!isSibling(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000258 continue;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000259 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000260 if (!isSnippet(SnipLI))
261 continue;
262 SnippetCopies.insert(MI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000263 if (isRegToSpill(SnipReg))
264 continue;
265 RegsToSpill.push_back(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000266 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000267 ++NumSnippets;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000268 }
269}
270
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000271
272//===----------------------------------------------------------------------===//
273// Sibling Values
274//===----------------------------------------------------------------------===//
275
276// After live range splitting, some values to be spilled may be defined by
277// copies from sibling registers. We trace the sibling copies back to the
278// original value if it still exists. We need it for rematerialization.
279//
280// Even when the value can't be rematerialized, we still want to determine if
281// the value has already been spilled, or we may want to hoist the spill from a
282// loop.
283
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000284bool InlineSpiller::isSibling(unsigned Reg) {
285 return TargetRegisterInfo::isVirtualRegister(Reg) &&
286 VRM.getOriginal(Reg) == Original;
287}
288
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000289/// traceSiblingValue - Trace a value that is about to be spilled back to the
290/// real defining instructions by looking through sibling copies. Always stay
291/// within the range of OrigVNI so the registers are known to carry the same
292/// value.
293///
294/// Determine if the value is defined by all reloads, so spilling isn't
295/// necessary - the value is already in the stack slot.
296///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000297/// Return a defining instruction that may be a candidate for rematerialization.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000298///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000299MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
300 VNInfo *OrigVNI) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000301 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
302 << UseVNI->id << '@' << UseVNI->def << '\n');
303 SmallPtrSet<VNInfo*, 8> Visited;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000304 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000305 WorkList.push_back(std::make_pair(UseReg, UseVNI));
306
307 // Best spill candidate seen so far. This must dominate UseVNI.
308 SibValueInfo SVI(UseReg, UseVNI);
309 MachineBasicBlock *UseMBB = LIS.getMBBFromIndex(UseVNI->def);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000310 unsigned SpillDepth = Loops.getLoopDepth(UseMBB);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000311 bool SeenOrigPHI = false; // Original PHI met.
312
313 do {
314 unsigned Reg;
315 VNInfo *VNI;
316 tie(Reg, VNI) = WorkList.pop_back_val();
317 if (!Visited.insert(VNI))
318 continue;
319
320 // Is this value a better spill candidate?
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000321 if (!isRegToSpill(Reg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000322 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000323 if (MBB != UseMBB && MDT.dominates(MBB, UseMBB)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000324 // This is a valid spill location dominating UseVNI.
325 // Prefer to spill at a smaller loop depth.
326 unsigned Depth = Loops.getLoopDepth(MBB);
327 if (Depth < SpillDepth) {
328 DEBUG(dbgs() << " spill depth " << Depth << ": " << PrintReg(Reg)
329 << ':' << VNI->id << '@' << VNI->def << '\n');
330 SVI.SpillReg = Reg;
331 SVI.SpillVNI = VNI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000332 SpillDepth = Depth;
333 }
334 }
335 }
336
337 // Trace through PHI-defs created by live range splitting.
338 if (VNI->isPHIDef()) {
339 if (VNI->def == OrigVNI->def) {
340 DEBUG(dbgs() << " orig phi value " << PrintReg(Reg) << ':'
341 << VNI->id << '@' << VNI->def << '\n');
342 SeenOrigPHI = true;
343 continue;
344 }
345 // Get values live-out of predecessors.
346 LiveInterval &LI = LIS.getInterval(Reg);
347 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
348 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
349 PE = MBB->pred_end(); PI != PE; ++PI) {
350 VNInfo *PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
351 if (PVNI)
352 WorkList.push_back(std::make_pair(Reg, PVNI));
353 }
354 continue;
355 }
356
357 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
358 assert(MI && "Missing def");
359
360 // Trace through sibling copies.
361 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000362 if (isSibling(SrcReg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000363 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
364 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
365 assert(SrcVNI && "Copy from non-existing value");
366 DEBUG(dbgs() << " copy of " << PrintReg(SrcReg) << ':'
367 << SrcVNI->id << '@' << SrcVNI->def << '\n');
368 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
369 continue;
370 }
371 }
372
373 // Track reachable reloads.
374 int FI;
375 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
376 DEBUG(dbgs() << " reload " << PrintReg(Reg) << ':'
377 << VNI->id << "@" << VNI->def << '\n');
378 SVI.AllDefsAreReloads = true;
379 continue;
380 }
381
382 // We have an 'original' def. Don't record trivial cases.
383 if (VNI == UseVNI) {
384 DEBUG(dbgs() << "Not a sibling copy.\n");
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000385 return MI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000386 }
387
388 // Potential remat candidate.
389 DEBUG(dbgs() << " def " << PrintReg(Reg) << ':'
390 << VNI->id << '@' << VNI->def << '\t' << *MI);
391 SVI.DefMI = MI;
392 } while (!WorkList.empty());
393
394 if (SeenOrigPHI || SVI.DefMI)
395 SVI.AllDefsAreReloads = false;
396
397 DEBUG({
398 if (SVI.AllDefsAreReloads)
399 dbgs() << "All defs are reloads.\n";
400 else
401 dbgs() << "Prefer to spill " << PrintReg(SVI.SpillReg) << ':'
402 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def << '\n';
403 });
404 SibValues.insert(std::make_pair(UseVNI, SVI));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000405 return SVI.DefMI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000406}
407
408/// analyzeSiblingValues - Trace values defined by sibling copies back to
409/// something that isn't a sibling copy.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000410///
411/// Keep track of values that may be rematerializable.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000412void InlineSpiller::analyzeSiblingValues() {
413 SibValues.clear();
414
415 // No siblings at all?
416 if (Edit->getReg() == Original)
417 return;
418
419 LiveInterval &OrigLI = LIS.getInterval(Original);
420 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
421 unsigned Reg = RegsToSpill[i];
422 LiveInterval &LI = LIS.getInterval(Reg);
423 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
424 VE = LI.vni_end(); VI != VE; ++VI) {
425 VNInfo *VNI = *VI;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000426 if (VNI->isUnused())
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000427 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000428 MachineInstr *DefMI = 0;
429 // Check possible sibling copies.
430 if (VNI->isPHIDef() || VNI->getCopy()) {
431 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
432 if (OrigVNI->def != VNI->def)
433 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
434 }
435 if (!DefMI && !VNI->isPHIDef())
436 DefMI = LIS.getInstructionFromIndex(VNI->def);
Jakob Stoklund Olesen3b7d9172011-04-20 22:14:20 +0000437 if (DefMI && Edit->checkRematerializable(VNI, DefMI, TII, AA)) {
438 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
439 << VNI->def << " may remat from " << *DefMI);
440 }
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000441 }
442 }
443}
444
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000445/// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
446/// a spill at a better location.
447bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
448 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
449 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
450 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000451 SibValueMap::iterator I = SibValues.find(VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000452 if (I == SibValues.end())
453 return false;
454
455 const SibValueInfo &SVI = I->second;
456
457 // Let the normal folding code deal with the boring case.
458 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
459 return false;
460
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000461 // SpillReg may have been deleted by remat and DCE.
462 if (!LIS.hasInterval(SVI.SpillReg)) {
463 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
464 SibValues.erase(I);
465 return false;
466 }
467
468 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
469 if (!SibLI.containsValue(SVI.SpillVNI)) {
470 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
471 SibValues.erase(I);
472 return false;
473 }
474
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000475 // Conservatively extend the stack slot range to the range of the original
476 // value. We may be able to do better with stack slot coloring by being more
477 // careful here.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000478 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000479 LiveInterval &OrigLI = LIS.getInterval(Original);
480 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000481 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +0000482 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000483 << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000484
485 // Already spilled everywhere.
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000486 if (SVI.AllDefsAreReloads) {
487 ++NumOmitReloadSpill;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000488 return true;
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000489 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000490 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
491 // any later spills of the same value.
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000492 eliminateRedundantSpills(SibLI, SVI.SpillVNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000493
494 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
495 MachineBasicBlock::iterator MII;
496 if (SVI.SpillVNI->isPHIDef())
497 MII = MBB->SkipPHIsAndLabels(MBB->begin());
498 else {
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000499 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
500 assert(DefMI && "Defining instruction disappeared");
501 MII = DefMI;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000502 ++MII;
503 }
504 // Insert spill without kill flag immediately after def.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000505 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
506 MRI.getRegClass(SVI.SpillReg), &TRI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000507 --MII; // Point to store instruction.
508 LIS.InsertMachineInstrInMaps(MII);
509 VRM.addSpillSlotUse(StackSlot, MII);
510 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000511
512 if (MBB == CopyMI->getParent())
513 ++NumHoistLocal;
514 else
515 ++NumHoistGlobal;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000516 return true;
517}
518
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000519/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
520/// redundant spills of this value in SLI.reg and sibling copies.
521void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000522 assert(VNI && "Missing value");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000523 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
524 WorkList.push_back(std::make_pair(&SLI, VNI));
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000525 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000526
527 do {
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000528 LiveInterval *LI;
529 tie(LI, VNI) = WorkList.pop_back_val();
530 unsigned Reg = LI->reg;
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000531 DEBUG(dbgs() << "Checking redundant spills for "
532 << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000533
534 // Regs to spill are taken care of.
535 if (isRegToSpill(Reg))
536 continue;
537
538 // Add all of VNI's live range to StackInt.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000539 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
540 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000541
542 // Find all spills and copies of VNI.
543 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
544 MachineInstr *MI = UI.skipInstruction();) {
545 if (!MI->isCopy() && !MI->getDesc().mayStore())
546 continue;
547 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000548 if (LI->getVNInfoAt(Idx) != VNI)
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000549 continue;
550
551 // Follow sibling copies down the dominator tree.
552 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
553 if (isSibling(DstReg)) {
554 LiveInterval &DstLI = LIS.getInterval(DstReg);
555 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
556 assert(DstVNI && "Missing defined value");
557 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000558 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000559 }
560 continue;
561 }
562
563 // Erase spills.
564 int FI;
565 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
566 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
567 // eliminateDeadDefs won't normally remove stores, so switch opcode.
568 MI->setDesc(TII.get(TargetOpcode::KILL));
569 DeadDefs.push_back(MI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000570 ++NumRedundantSpills;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000571 }
572 }
573 } while (!WorkList.empty());
574}
575
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000576
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000577//===----------------------------------------------------------------------===//
578// Rematerialization
579//===----------------------------------------------------------------------===//
580
581/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
582/// instruction cannot be eliminated. See through snippet copies
583void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
584 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
585 WorkList.push_back(std::make_pair(LI, VNI));
586 do {
587 tie(LI, VNI) = WorkList.pop_back_val();
588 if (!UsedValues.insert(VNI))
589 continue;
590
591 if (VNI->isPHIDef()) {
592 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
593 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
594 PE = MBB->pred_end(); PI != PE; ++PI) {
595 VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
596 if (PVNI)
597 WorkList.push_back(std::make_pair(LI, PVNI));
598 }
599 continue;
600 }
601
602 // Follow snippet copies.
603 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
604 if (!SnippetCopies.count(MI))
605 continue;
606 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
607 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
608 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex());
609 assert(SnipVNI && "Snippet undefined before copy");
610 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
611 } while (!WorkList.empty());
612}
613
614/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
615bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
616 MachineBasicBlock::iterator MI) {
617 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
618 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx);
619
620 if (!ParentVNI) {
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000621 DEBUG(dbgs() << "\tadding <undef> flags: ");
622 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
623 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000624 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000625 MO.setIsUndef();
626 }
627 DEBUG(dbgs() << UseIdx << '\t' << *MI);
628 return true;
629 }
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000630
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000631 if (SnippetCopies.count(MI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000632 return false;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000633
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000634 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
635 LiveRangeEdit::Remat RM(ParentVNI);
636 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
637 if (SibI != SibValues.end())
638 RM.OrigMI = SibI->second.DefMI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000639 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000640 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000641 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
642 return false;
643 }
644
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000645 // If the instruction also writes VirtReg.reg, it had better not require the
646 // same register for uses and defs.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000647 bool Reads, Writes;
648 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000649 tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000650 if (Writes) {
651 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
652 MachineOperand &MO = MI->getOperand(Ops[i]);
653 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000654 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000655 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
656 return false;
657 }
658 }
659 }
660
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000661 // Before rematerializing into a register for a single instruction, try to
662 // fold a load into the instruction. That avoids allocating a new register.
663 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
664 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000665 Edit->markRematerialized(RM.ParentVNI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000666 ++NumFoldedLoads;
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000667 return true;
668 }
669
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000670 // Alocate a new register for the remat.
Jakob Stoklund Olesen312babc2011-03-31 03:54:44 +0000671 LiveInterval &NewLI = Edit->createFrom(Original, LIS, VRM);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000672 NewLI.markNotSpillable();
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000673
674 // Finally we can rematerialize OrigMI before MI.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000675 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
676 LIS, TII, TRI);
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000677 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000678 << *LIS.getInstructionFromIndex(DefIdx));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000679
680 // Replace operands
681 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
682 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000683 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000684 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000685 MO.setIsKill();
686 }
687 }
688 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
689
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000690 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000691 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000692 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000693 ++NumRemats;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000694 return true;
695}
696
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000697/// reMaterializeAll - Try to rematerialize as many uses as possible,
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000698/// and trim the live ranges after.
699void InlineSpiller::reMaterializeAll() {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000700 // analyzeSiblingValues has already tested all relevant defining instructions.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000701 if (!Edit->anyRematerializable(LIS, TII, AA))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000702 return;
703
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000704 UsedValues.clear();
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000705
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000706 // Try to remat before all uses of snippets.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000707 bool anyRemat = false;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000708 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
709 unsigned Reg = RegsToSpill[i];
710 LiveInterval &LI = LIS.getInterval(Reg);
711 for (MachineRegisterInfo::use_nodbg_iterator
712 RI = MRI.use_nodbg_begin(Reg);
713 MachineInstr *MI = RI.skipInstruction();)
714 anyRemat |= reMaterializeFor(LI, MI);
715 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000716 if (!anyRemat)
717 return;
718
719 // Remove any values that were completely rematted.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000720 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
721 unsigned Reg = RegsToSpill[i];
722 LiveInterval &LI = LIS.getInterval(Reg);
723 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
724 I != E; ++I) {
725 VNInfo *VNI = *I;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000726 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000727 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000728 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
729 MI->addRegisterDead(Reg, &TRI);
730 if (!MI->allDefsAreDead())
731 continue;
732 DEBUG(dbgs() << "All defs dead: " << *MI);
733 DeadDefs.push_back(MI);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000734 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000735 }
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000736
737 // Eliminate dead code after remat. Note that some snippet copies may be
738 // deleted here.
739 if (DeadDefs.empty())
740 return;
741 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
742 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
743
744 // Get rid of deleted and empty intervals.
745 for (unsigned i = RegsToSpill.size(); i != 0; --i) {
746 unsigned Reg = RegsToSpill[i-1];
747 if (!LIS.hasInterval(Reg)) {
748 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
749 continue;
750 }
751 LiveInterval &LI = LIS.getInterval(Reg);
752 if (!LI.empty())
753 continue;
754 Edit->eraseVirtReg(Reg, LIS);
755 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
756 }
757 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000758}
759
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000760
761//===----------------------------------------------------------------------===//
762// Spilling
763//===----------------------------------------------------------------------===//
764
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000765/// If MI is a load or store of StackSlot, it can be removed.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000766bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000767 int FI = 0;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000768 unsigned InstrReg;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000769 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
770 !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000771 return false;
772
773 // We have a stack access. Is it the right register and slot?
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000774 if (InstrReg != Reg || FI != StackSlot)
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000775 return false;
776
777 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000778 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000779 MI->eraseFromParent();
780 return true;
781}
782
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000783/// foldMemoryOperand - Try folding stack slot references in Ops into MI.
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000784/// @param MI Instruction using or defining the current register.
Jakob Stoklund Olesen39048252010-12-18 03:28:32 +0000785/// @param Ops Operand indices from readsWritesVirtualRegister().
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000786/// @param LoadMI Load instruction to use instead of stack slot when non-null.
787/// @return True on success, and MI will be erased.
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000788bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000789 const SmallVectorImpl<unsigned> &Ops,
790 MachineInstr *LoadMI) {
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000791 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
792 // operands.
793 SmallVector<unsigned, 8> FoldOps;
794 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
795 unsigned Idx = Ops[i];
796 MachineOperand &MO = MI->getOperand(Idx);
797 if (MO.isImplicit())
798 continue;
799 // FIXME: Teach targets to deal with subregs.
800 if (MO.getSubReg())
801 return false;
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000802 // We cannot fold a load instruction into a def.
803 if (LoadMI && MO.isDef())
804 return false;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000805 // Tied use operands should not be passed to foldMemoryOperand.
806 if (!MI->isRegTiedToDefOperand(Idx))
807 FoldOps.push_back(Idx);
808 }
809
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000810 MachineInstr *FoldMI =
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000811 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
812 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000813 if (!FoldMI)
814 return false;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000815 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000816 if (!LoadMI)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000817 VRM.addSpillSlotUse(StackSlot, FoldMI);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +0000818 MI->eraseFromParent();
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000819 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000820 ++NumFolded;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000821 return true;
822}
823
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000824/// insertReload - Insert a reload of NewLI.reg before MI.
825void InlineSpiller::insertReload(LiveInterval &NewLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000826 SlotIndex Idx,
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000827 MachineBasicBlock::iterator MI) {
828 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000829 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
830 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000831 --MI; // Point to load instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000832 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
833 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000834 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
Lang Hames6e2968c2010-09-25 12:04:16 +0000835 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000836 LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000837 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000838 ++NumReloads;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000839}
840
841/// insertSpill - Insert a spill of NewLI.reg after MI.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000842void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000843 SlotIndex Idx, MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000844 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000845 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
846 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000847 --MI; // Point to store instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000848 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
849 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000850 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000851 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000852 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000853 ++NumSpills;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000854}
855
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000856/// spillAroundUses - insert spill code around each use of Reg.
857void InlineSpiller::spillAroundUses(unsigned Reg) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000858 LiveInterval &OldLI = LIS.getInterval(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000859
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000860 // Iterate over instructions using Reg.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000861 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000862 MachineInstr *MI = RI.skipInstruction();) {
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000863
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000864 // Debug values are not allowed to affect codegen.
865 if (MI->isDebugValue()) {
866 // Modify DBG_VALUE now that the value is in a spill slot.
867 uint64_t Offset = MI->getOperand(1).getImm();
868 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
869 DebugLoc DL = MI->getDebugLoc();
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000870 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000871 Offset, MDPtr, DL)) {
872 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
873 MachineBasicBlock *MBB = MI->getParent();
874 MBB->insert(MBB->erase(MI), NewDV);
875 } else {
876 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
877 MI->eraseFromParent();
878 }
879 continue;
880 }
881
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000882 // Ignore copies to/from snippets. We'll delete them.
883 if (SnippetCopies.count(MI))
884 continue;
885
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000886 // Stack slot accesses may coalesce away.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000887 if (coalesceStackAccess(MI, Reg))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000888 continue;
889
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000890 // Analyze instruction.
891 bool Reads, Writes;
892 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000893 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000894
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000895 // Find the slot index where this instruction reads and writes OldLI.
896 // This is usually the def slot, except for tied early clobbers.
897 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
898 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getUseIndex()))
899 if (SlotIndex::isSameInstr(Idx, VNI->def))
900 Idx = VNI->def;
901
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000902 // Check for a sibling copy.
903 unsigned SibReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000904 if (SibReg && isSibling(SibReg)) {
905 if (Writes) {
906 // Hoist the spill of a sib-reg copy.
907 if (hoistSpill(OldLI, MI)) {
908 // This COPY is now dead, the value is already in the stack slot.
909 MI->getOperand(0).setIsDead();
910 DeadDefs.push_back(MI);
911 continue;
912 }
913 } else {
914 // This is a reload for a sib-reg copy. Drop spills downstream.
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000915 LiveInterval &SibLI = LIS.getInterval(SibReg);
916 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
917 // The COPY will fold to a reload below.
918 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000919 }
920
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000921 // Attempt to fold memory ops.
922 if (foldMemoryOperand(MI, Ops))
923 continue;
924
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000925 // Allocate interval around instruction.
926 // FIXME: Infer regclass from instruction alone.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000927 LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000928 NewLI.markNotSpillable();
929
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000930 if (Reads)
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000931 insertReload(NewLI, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000932
933 // Rewrite instruction operands.
934 bool hasLiveDef = false;
935 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
936 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000937 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000938 if (MO.isUse()) {
939 if (!MI->isRegTiedToDefOperand(Ops[i]))
940 MO.setIsKill();
941 } else {
942 if (!MO.isDead())
943 hasLiveDef = true;
944 }
945 }
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000946 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000947
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000948 // FIXME: Use a second vreg if instruction has no tied ops.
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000949 if (Writes && hasLiveDef)
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000950 insertSpill(NewLI, OldLI, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000951
952 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000953 }
954}
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000955
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000956/// spillAll - Spill all registers remaining after rematerialization.
957void InlineSpiller::spillAll() {
958 // Update LiveStacks now that we are committed to spilling.
959 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
960 StackSlot = VRM.assignVirt2StackSlot(Original);
961 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
962 StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
963 } else
964 StackInt = &LSS.getInterval(StackSlot);
965
966 if (Original != Edit->getReg())
967 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
968
969 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
970 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
971 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
972 StackInt->getValNumInfo(0));
973 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
974
975 // Spill around uses of all RegsToSpill.
976 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
977 spillAroundUses(RegsToSpill[i]);
978
979 // Hoisted spills may cause dead code.
980 if (!DeadDefs.empty()) {
981 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
982 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
983 }
984
985 // Finally delete the SnippetCopies.
986 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg());
987 MachineInstr *MI = RI.skipInstruction();) {
988 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
989 // FIXME: Do this with a LiveRangeEdit callback.
990 VRM.RemoveMachineInstrFromMaps(MI);
991 LIS.RemoveMachineInstrFromMaps(MI);
992 MI->eraseFromParent();
993 }
994
995 // Delete all spilled registers.
996 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
997 Edit->eraseVirtReg(RegsToSpill[i], LIS);
998}
999
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001000void InlineSpiller::spill(LiveRangeEdit &edit) {
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001001 ++NumSpilledRanges;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001002 Edit = &edit;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001003 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1004 && "Trying to spill a stack slot.");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001005 // Share a stack slot among all descendants of Original.
1006 Original = VRM.getOriginal(edit.getReg());
1007 StackSlot = VRM.getStackSlot(Original);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001008 StackInt = 0;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001009
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001010 DEBUG(dbgs() << "Inline spilling "
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001011 << MRI.getRegClass(edit.getReg())->getName()
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001012 << ':' << edit.getParent() << "\nFrom original "
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001013 << LIS.getInterval(Original) << '\n');
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001014 assert(edit.getParent().isSpillable() &&
1015 "Attempting to spill already spilled value.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001016 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001017
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001018 collectRegsToSpill();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001019 analyzeSiblingValues();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001020 reMaterializeAll();
1021
1022 // Remat may handle everything.
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001023 if (!RegsToSpill.empty())
1024 spillAll();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001025
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001026 Edit->calculateRegClassAndHint(MF, LIS, Loops);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001027}