blob: 0273891d690b04ddf4ae92c185e8e24a234e9cd1 [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) {
Rafael Espindolacfe52542011-06-30 21:15:52 +0000183 if (!MI->isFullCopy())
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000184 return 0;
185 if (MI->getOperand(0).getReg() == Reg)
186 return MI->getOperand(1).getReg();
187 if (MI->getOperand(1).getReg() == Reg)
188 return MI->getOperand(0).getReg();
189 return 0;
190}
191
192/// isSnippet - Identify if a live interval is a snippet that should be spilled.
193/// It is assumed that SnipLI is a virtual register with the same original as
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000194/// Edit->getReg().
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000195bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000196 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000197
198 // A snippet is a tiny live range with only a single instruction using it
199 // besides copies to/from Reg or spills/fills. We accept:
200 //
201 // %snip = COPY %Reg / FILL fi#
202 // %snip = USE %snip
203 // %Reg = COPY %snip / SPILL %snip, fi#
204 //
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000205 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000206 return false;
207
208 MachineInstr *UseMI = 0;
209
210 // Check that all uses satisfy our criteria.
211 for (MachineRegisterInfo::reg_nodbg_iterator
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000212 RI = MRI.reg_nodbg_begin(SnipLI.reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000213 MachineInstr *MI = RI.skipInstruction();) {
214
215 // Allow copies to/from Reg.
216 if (isFullCopyOf(MI, Reg))
217 continue;
218
219 // Allow stack slot loads.
220 int FI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000221 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000222 continue;
223
224 // Allow stack slot stores.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000225 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000226 continue;
227
228 // Allow a single additional instruction.
229 if (UseMI && MI != UseMI)
230 return false;
231 UseMI = MI;
232 }
233 return true;
234}
235
236/// collectRegsToSpill - Collect live range snippets that only have a single
237/// real use.
238void InlineSpiller::collectRegsToSpill() {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000239 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000240
241 // Main register always spills.
242 RegsToSpill.assign(1, Reg);
243 SnippetCopies.clear();
244
245 // Snippets all have the same original, so there can't be any for an original
246 // register.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000247 if (Original == Reg)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000248 return;
249
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000250 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000251 MachineInstr *MI = RI.skipInstruction();) {
252 unsigned SnipReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000253 if (!isSibling(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000254 continue;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000255 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000256 if (!isSnippet(SnipLI))
257 continue;
258 SnippetCopies.insert(MI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000259 if (isRegToSpill(SnipReg))
260 continue;
261 RegsToSpill.push_back(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000262 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000263 ++NumSnippets;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000264 }
265}
266
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000267
268//===----------------------------------------------------------------------===//
269// Sibling Values
270//===----------------------------------------------------------------------===//
271
272// After live range splitting, some values to be spilled may be defined by
273// copies from sibling registers. We trace the sibling copies back to the
274// original value if it still exists. We need it for rematerialization.
275//
276// Even when the value can't be rematerialized, we still want to determine if
277// the value has already been spilled, or we may want to hoist the spill from a
278// loop.
279
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000280bool InlineSpiller::isSibling(unsigned Reg) {
281 return TargetRegisterInfo::isVirtualRegister(Reg) &&
282 VRM.getOriginal(Reg) == Original;
283}
284
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000285/// traceSiblingValue - Trace a value that is about to be spilled back to the
286/// real defining instructions by looking through sibling copies. Always stay
287/// within the range of OrigVNI so the registers are known to carry the same
288/// value.
289///
290/// Determine if the value is defined by all reloads, so spilling isn't
291/// necessary - the value is already in the stack slot.
292///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000293/// Return a defining instruction that may be a candidate for rematerialization.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000294///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000295MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
296 VNInfo *OrigVNI) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000297 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
298 << UseVNI->id << '@' << UseVNI->def << '\n');
299 SmallPtrSet<VNInfo*, 8> Visited;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000300 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000301 WorkList.push_back(std::make_pair(UseReg, UseVNI));
302
303 // Best spill candidate seen so far. This must dominate UseVNI.
304 SibValueInfo SVI(UseReg, UseVNI);
305 MachineBasicBlock *UseMBB = LIS.getMBBFromIndex(UseVNI->def);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000306 unsigned SpillDepth = Loops.getLoopDepth(UseMBB);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000307 bool SeenOrigPHI = false; // Original PHI met.
308
309 do {
310 unsigned Reg;
311 VNInfo *VNI;
312 tie(Reg, VNI) = WorkList.pop_back_val();
313 if (!Visited.insert(VNI))
314 continue;
315
316 // Is this value a better spill candidate?
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000317 if (!isRegToSpill(Reg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000318 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000319 if (MBB != UseMBB && MDT.dominates(MBB, UseMBB)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000320 // This is a valid spill location dominating UseVNI.
321 // Prefer to spill at a smaller loop depth.
322 unsigned Depth = Loops.getLoopDepth(MBB);
323 if (Depth < SpillDepth) {
324 DEBUG(dbgs() << " spill depth " << Depth << ": " << PrintReg(Reg)
325 << ':' << VNI->id << '@' << VNI->def << '\n');
326 SVI.SpillReg = Reg;
327 SVI.SpillVNI = VNI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000328 SpillDepth = Depth;
329 }
330 }
331 }
332
333 // Trace through PHI-defs created by live range splitting.
334 if (VNI->isPHIDef()) {
335 if (VNI->def == OrigVNI->def) {
336 DEBUG(dbgs() << " orig phi value " << PrintReg(Reg) << ':'
337 << VNI->id << '@' << VNI->def << '\n');
338 SeenOrigPHI = true;
339 continue;
340 }
341 // Get values live-out of predecessors.
342 LiveInterval &LI = LIS.getInterval(Reg);
343 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
344 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
345 PE = MBB->pred_end(); PI != PE; ++PI) {
346 VNInfo *PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
347 if (PVNI)
348 WorkList.push_back(std::make_pair(Reg, PVNI));
349 }
350 continue;
351 }
352
353 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
354 assert(MI && "Missing def");
355
356 // Trace through sibling copies.
357 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000358 if (isSibling(SrcReg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000359 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
360 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
361 assert(SrcVNI && "Copy from non-existing value");
362 DEBUG(dbgs() << " copy of " << PrintReg(SrcReg) << ':'
363 << SrcVNI->id << '@' << SrcVNI->def << '\n');
364 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
365 continue;
366 }
367 }
368
369 // Track reachable reloads.
370 int FI;
371 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
372 DEBUG(dbgs() << " reload " << PrintReg(Reg) << ':'
373 << VNI->id << "@" << VNI->def << '\n');
374 SVI.AllDefsAreReloads = true;
375 continue;
376 }
377
378 // We have an 'original' def. Don't record trivial cases.
379 if (VNI == UseVNI) {
380 DEBUG(dbgs() << "Not a sibling copy.\n");
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000381 return MI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000382 }
383
384 // Potential remat candidate.
385 DEBUG(dbgs() << " def " << PrintReg(Reg) << ':'
386 << VNI->id << '@' << VNI->def << '\t' << *MI);
387 SVI.DefMI = MI;
388 } while (!WorkList.empty());
389
390 if (SeenOrigPHI || SVI.DefMI)
391 SVI.AllDefsAreReloads = false;
392
393 DEBUG({
394 if (SVI.AllDefsAreReloads)
395 dbgs() << "All defs are reloads.\n";
396 else
397 dbgs() << "Prefer to spill " << PrintReg(SVI.SpillReg) << ':'
398 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def << '\n';
399 });
400 SibValues.insert(std::make_pair(UseVNI, SVI));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000401 return SVI.DefMI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000402}
403
404/// analyzeSiblingValues - Trace values defined by sibling copies back to
405/// something that isn't a sibling copy.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000406///
407/// Keep track of values that may be rematerializable.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000408void InlineSpiller::analyzeSiblingValues() {
409 SibValues.clear();
410
411 // No siblings at all?
412 if (Edit->getReg() == Original)
413 return;
414
415 LiveInterval &OrigLI = LIS.getInterval(Original);
416 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
417 unsigned Reg = RegsToSpill[i];
418 LiveInterval &LI = LIS.getInterval(Reg);
419 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
420 VE = LI.vni_end(); VI != VE; ++VI) {
421 VNInfo *VNI = *VI;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000422 if (VNI->isUnused())
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000423 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000424 MachineInstr *DefMI = 0;
425 // Check possible sibling copies.
426 if (VNI->isPHIDef() || VNI->getCopy()) {
427 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
428 if (OrigVNI->def != VNI->def)
429 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
430 }
431 if (!DefMI && !VNI->isPHIDef())
432 DefMI = LIS.getInstructionFromIndex(VNI->def);
Jakob Stoklund Olesen3b7d9172011-04-20 22:14:20 +0000433 if (DefMI && Edit->checkRematerializable(VNI, DefMI, TII, AA)) {
434 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
435 << VNI->def << " may remat from " << *DefMI);
436 }
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000437 }
438 }
439}
440
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000441/// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
442/// a spill at a better location.
443bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
444 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
445 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
446 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000447 SibValueMap::iterator I = SibValues.find(VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000448 if (I == SibValues.end())
449 return false;
450
451 const SibValueInfo &SVI = I->second;
452
453 // Let the normal folding code deal with the boring case.
454 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
455 return false;
456
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000457 // SpillReg may have been deleted by remat and DCE.
458 if (!LIS.hasInterval(SVI.SpillReg)) {
459 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
460 SibValues.erase(I);
461 return false;
462 }
463
464 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
465 if (!SibLI.containsValue(SVI.SpillVNI)) {
466 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
467 SibValues.erase(I);
468 return false;
469 }
470
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000471 // Conservatively extend the stack slot range to the range of the original
472 // value. We may be able to do better with stack slot coloring by being more
473 // careful here.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000474 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000475 LiveInterval &OrigLI = LIS.getInterval(Original);
476 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000477 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +0000478 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000479 << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000480
481 // Already spilled everywhere.
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000482 if (SVI.AllDefsAreReloads) {
483 ++NumOmitReloadSpill;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000484 return true;
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000485 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000486 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
487 // any later spills of the same value.
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000488 eliminateRedundantSpills(SibLI, SVI.SpillVNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000489
490 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
491 MachineBasicBlock::iterator MII;
492 if (SVI.SpillVNI->isPHIDef())
493 MII = MBB->SkipPHIsAndLabels(MBB->begin());
494 else {
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000495 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
496 assert(DefMI && "Defining instruction disappeared");
497 MII = DefMI;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000498 ++MII;
499 }
500 // Insert spill without kill flag immediately after def.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000501 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
502 MRI.getRegClass(SVI.SpillReg), &TRI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000503 --MII; // Point to store instruction.
504 LIS.InsertMachineInstrInMaps(MII);
505 VRM.addSpillSlotUse(StackSlot, MII);
506 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000507
508 if (MBB == CopyMI->getParent())
509 ++NumHoistLocal;
510 else
511 ++NumHoistGlobal;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000512 return true;
513}
514
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000515/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
516/// redundant spills of this value in SLI.reg and sibling copies.
517void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000518 assert(VNI && "Missing value");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000519 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
520 WorkList.push_back(std::make_pair(&SLI, VNI));
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000521 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000522
523 do {
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000524 LiveInterval *LI;
525 tie(LI, VNI) = WorkList.pop_back_val();
526 unsigned Reg = LI->reg;
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000527 DEBUG(dbgs() << "Checking redundant spills for "
528 << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000529
530 // Regs to spill are taken care of.
531 if (isRegToSpill(Reg))
532 continue;
533
534 // Add all of VNI's live range to StackInt.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000535 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
536 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000537
538 // Find all spills and copies of VNI.
539 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
540 MachineInstr *MI = UI.skipInstruction();) {
541 if (!MI->isCopy() && !MI->getDesc().mayStore())
542 continue;
543 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000544 if (LI->getVNInfoAt(Idx) != VNI)
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000545 continue;
546
547 // Follow sibling copies down the dominator tree.
548 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
549 if (isSibling(DstReg)) {
550 LiveInterval &DstLI = LIS.getInterval(DstReg);
551 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
552 assert(DstVNI && "Missing defined value");
553 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000554 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000555 }
556 continue;
557 }
558
559 // Erase spills.
560 int FI;
561 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
562 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
563 // eliminateDeadDefs won't normally remove stores, so switch opcode.
564 MI->setDesc(TII.get(TargetOpcode::KILL));
565 DeadDefs.push_back(MI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000566 ++NumRedundantSpills;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000567 }
568 }
569 } while (!WorkList.empty());
570}
571
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000572
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000573//===----------------------------------------------------------------------===//
574// Rematerialization
575//===----------------------------------------------------------------------===//
576
577/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
578/// instruction cannot be eliminated. See through snippet copies
579void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
580 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
581 WorkList.push_back(std::make_pair(LI, VNI));
582 do {
583 tie(LI, VNI) = WorkList.pop_back_val();
584 if (!UsedValues.insert(VNI))
585 continue;
586
587 if (VNI->isPHIDef()) {
588 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
589 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
590 PE = MBB->pred_end(); PI != PE; ++PI) {
591 VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
592 if (PVNI)
593 WorkList.push_back(std::make_pair(LI, PVNI));
594 }
595 continue;
596 }
597
598 // Follow snippet copies.
599 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
600 if (!SnippetCopies.count(MI))
601 continue;
602 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
603 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
604 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex());
605 assert(SnipVNI && "Snippet undefined before copy");
606 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
607 } while (!WorkList.empty());
608}
609
610/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
611bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
612 MachineBasicBlock::iterator MI) {
613 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
614 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx);
615
616 if (!ParentVNI) {
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000617 DEBUG(dbgs() << "\tadding <undef> flags: ");
618 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
619 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000620 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000621 MO.setIsUndef();
622 }
623 DEBUG(dbgs() << UseIdx << '\t' << *MI);
624 return true;
625 }
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000626
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000627 if (SnippetCopies.count(MI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000628 return false;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000629
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000630 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
631 LiveRangeEdit::Remat RM(ParentVNI);
632 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
633 if (SibI != SibValues.end())
634 RM.OrigMI = SibI->second.DefMI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000635 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000636 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000637 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
638 return false;
639 }
640
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000641 // If the instruction also writes VirtReg.reg, it had better not require the
642 // same register for uses and defs.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000643 bool Reads, Writes;
644 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000645 tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000646 if (Writes) {
647 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
648 MachineOperand &MO = MI->getOperand(Ops[i]);
649 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000650 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000651 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
652 return false;
653 }
654 }
655 }
656
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000657 // Before rematerializing into a register for a single instruction, try to
658 // fold a load into the instruction. That avoids allocating a new register.
659 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
660 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000661 Edit->markRematerialized(RM.ParentVNI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000662 ++NumFoldedLoads;
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000663 return true;
664 }
665
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000666 // Alocate a new register for the remat.
Jakob Stoklund Olesen312babc2011-03-31 03:54:44 +0000667 LiveInterval &NewLI = Edit->createFrom(Original, LIS, VRM);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000668 NewLI.markNotSpillable();
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000669
670 // Finally we can rematerialize OrigMI before MI.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000671 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
672 LIS, TII, TRI);
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000673 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000674 << *LIS.getInstructionFromIndex(DefIdx));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000675
676 // Replace operands
677 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
678 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000679 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000680 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000681 MO.setIsKill();
682 }
683 }
684 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
685
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000686 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000687 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000688 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000689 ++NumRemats;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000690 return true;
691}
692
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000693/// reMaterializeAll - Try to rematerialize as many uses as possible,
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000694/// and trim the live ranges after.
695void InlineSpiller::reMaterializeAll() {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000696 // analyzeSiblingValues has already tested all relevant defining instructions.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000697 if (!Edit->anyRematerializable(LIS, TII, AA))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000698 return;
699
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000700 UsedValues.clear();
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000701
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000702 // Try to remat before all uses of snippets.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000703 bool anyRemat = false;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000704 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
705 unsigned Reg = RegsToSpill[i];
706 LiveInterval &LI = LIS.getInterval(Reg);
707 for (MachineRegisterInfo::use_nodbg_iterator
708 RI = MRI.use_nodbg_begin(Reg);
709 MachineInstr *MI = RI.skipInstruction();)
710 anyRemat |= reMaterializeFor(LI, MI);
711 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000712 if (!anyRemat)
713 return;
714
715 // Remove any values that were completely rematted.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000716 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
717 unsigned Reg = RegsToSpill[i];
718 LiveInterval &LI = LIS.getInterval(Reg);
719 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
720 I != E; ++I) {
721 VNInfo *VNI = *I;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000722 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000723 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000724 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
725 MI->addRegisterDead(Reg, &TRI);
726 if (!MI->allDefsAreDead())
727 continue;
728 DEBUG(dbgs() << "All defs dead: " << *MI);
729 DeadDefs.push_back(MI);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000730 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000731 }
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000732
733 // Eliminate dead code after remat. Note that some snippet copies may be
734 // deleted here.
735 if (DeadDefs.empty())
736 return;
737 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
738 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
739
740 // Get rid of deleted and empty intervals.
741 for (unsigned i = RegsToSpill.size(); i != 0; --i) {
742 unsigned Reg = RegsToSpill[i-1];
743 if (!LIS.hasInterval(Reg)) {
744 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
745 continue;
746 }
747 LiveInterval &LI = LIS.getInterval(Reg);
748 if (!LI.empty())
749 continue;
750 Edit->eraseVirtReg(Reg, LIS);
751 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
752 }
753 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000754}
755
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000756
757//===----------------------------------------------------------------------===//
758// Spilling
759//===----------------------------------------------------------------------===//
760
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000761/// If MI is a load or store of StackSlot, it can be removed.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000762bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000763 int FI = 0;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000764 unsigned InstrReg;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000765 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
766 !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000767 return false;
768
769 // We have a stack access. Is it the right register and slot?
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000770 if (InstrReg != Reg || FI != StackSlot)
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000771 return false;
772
773 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000774 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000775 MI->eraseFromParent();
776 return true;
777}
778
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000779/// foldMemoryOperand - Try folding stack slot references in Ops into MI.
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000780/// @param MI Instruction using or defining the current register.
Jakob Stoklund Olesen39048252010-12-18 03:28:32 +0000781/// @param Ops Operand indices from readsWritesVirtualRegister().
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000782/// @param LoadMI Load instruction to use instead of stack slot when non-null.
783/// @return True on success, and MI will be erased.
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000784bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000785 const SmallVectorImpl<unsigned> &Ops,
786 MachineInstr *LoadMI) {
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000787 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
788 // operands.
789 SmallVector<unsigned, 8> FoldOps;
790 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
791 unsigned Idx = Ops[i];
792 MachineOperand &MO = MI->getOperand(Idx);
793 if (MO.isImplicit())
794 continue;
795 // FIXME: Teach targets to deal with subregs.
796 if (MO.getSubReg())
797 return false;
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000798 // We cannot fold a load instruction into a def.
799 if (LoadMI && MO.isDef())
800 return false;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000801 // Tied use operands should not be passed to foldMemoryOperand.
802 if (!MI->isRegTiedToDefOperand(Idx))
803 FoldOps.push_back(Idx);
804 }
805
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000806 MachineInstr *FoldMI =
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000807 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
808 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000809 if (!FoldMI)
810 return false;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000811 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000812 if (!LoadMI)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000813 VRM.addSpillSlotUse(StackSlot, FoldMI);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +0000814 MI->eraseFromParent();
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000815 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000816 ++NumFolded;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000817 return true;
818}
819
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000820/// insertReload - Insert a reload of NewLI.reg before MI.
821void InlineSpiller::insertReload(LiveInterval &NewLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000822 SlotIndex Idx,
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000823 MachineBasicBlock::iterator MI) {
824 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000825 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
826 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000827 --MI; // Point to load instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000828 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
829 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000830 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
Lang Hames6e2968c2010-09-25 12:04:16 +0000831 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000832 LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000833 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000834 ++NumReloads;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000835}
836
837/// insertSpill - Insert a spill of NewLI.reg after MI.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000838void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000839 SlotIndex Idx, MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000840 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000841 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
842 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000843 --MI; // Point to store instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000844 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
845 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000846 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000847 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000848 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000849 ++NumSpills;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000850}
851
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000852/// spillAroundUses - insert spill code around each use of Reg.
853void InlineSpiller::spillAroundUses(unsigned Reg) {
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +0000854 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000855 LiveInterval &OldLI = LIS.getInterval(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000856
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000857 // Iterate over instructions using Reg.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000858 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000859 MachineInstr *MI = RI.skipInstruction();) {
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000860
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000861 // Debug values are not allowed to affect codegen.
862 if (MI->isDebugValue()) {
863 // Modify DBG_VALUE now that the value is in a spill slot.
864 uint64_t Offset = MI->getOperand(1).getImm();
865 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
866 DebugLoc DL = MI->getDebugLoc();
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000867 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000868 Offset, MDPtr, DL)) {
869 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
870 MachineBasicBlock *MBB = MI->getParent();
871 MBB->insert(MBB->erase(MI), NewDV);
872 } else {
873 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
874 MI->eraseFromParent();
875 }
876 continue;
877 }
878
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000879 // Ignore copies to/from snippets. We'll delete them.
880 if (SnippetCopies.count(MI))
881 continue;
882
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000883 // Stack slot accesses may coalesce away.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000884 if (coalesceStackAccess(MI, Reg))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000885 continue;
886
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000887 // Analyze instruction.
888 bool Reads, Writes;
889 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000890 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000891
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000892 // Find the slot index where this instruction reads and writes OldLI.
893 // This is usually the def slot, except for tied early clobbers.
894 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
895 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getUseIndex()))
896 if (SlotIndex::isSameInstr(Idx, VNI->def))
897 Idx = VNI->def;
898
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000899 // Check for a sibling copy.
900 unsigned SibReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000901 if (SibReg && isSibling(SibReg)) {
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +0000902 // This may actually be a copy between snippets.
903 if (isRegToSpill(SibReg)) {
904 DEBUG(dbgs() << "Found new snippet copy: " << *MI);
905 SnippetCopies.insert(MI);
906 continue;
907 }
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000908 if (Writes) {
909 // Hoist the spill of a sib-reg copy.
910 if (hoistSpill(OldLI, MI)) {
911 // This COPY is now dead, the value is already in the stack slot.
912 MI->getOperand(0).setIsDead();
913 DeadDefs.push_back(MI);
914 continue;
915 }
916 } else {
917 // This is a reload for a sib-reg copy. Drop spills downstream.
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000918 LiveInterval &SibLI = LIS.getInterval(SibReg);
919 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
920 // The COPY will fold to a reload below.
921 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000922 }
923
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000924 // Attempt to fold memory ops.
925 if (foldMemoryOperand(MI, Ops))
926 continue;
927
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000928 // Allocate interval around instruction.
929 // FIXME: Infer regclass from instruction alone.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000930 LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000931 NewLI.markNotSpillable();
932
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000933 if (Reads)
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000934 insertReload(NewLI, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000935
936 // Rewrite instruction operands.
937 bool hasLiveDef = false;
938 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
939 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000940 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000941 if (MO.isUse()) {
942 if (!MI->isRegTiedToDefOperand(Ops[i]))
943 MO.setIsKill();
944 } else {
945 if (!MO.isDead())
946 hasLiveDef = true;
947 }
948 }
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000949 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000950
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000951 // FIXME: Use a second vreg if instruction has no tied ops.
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000952 if (Writes && hasLiveDef)
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000953 insertSpill(NewLI, OldLI, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000954
955 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000956 }
957}
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000958
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000959/// spillAll - Spill all registers remaining after rematerialization.
960void InlineSpiller::spillAll() {
961 // Update LiveStacks now that we are committed to spilling.
962 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
963 StackSlot = VRM.assignVirt2StackSlot(Original);
964 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
965 StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
966 } else
967 StackInt = &LSS.getInterval(StackSlot);
968
969 if (Original != Edit->getReg())
970 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
971
972 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
973 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
974 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
975 StackInt->getValNumInfo(0));
976 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
977
978 // Spill around uses of all RegsToSpill.
979 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
980 spillAroundUses(RegsToSpill[i]);
981
982 // Hoisted spills may cause dead code.
983 if (!DeadDefs.empty()) {
984 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
985 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
986 }
987
988 // Finally delete the SnippetCopies.
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +0000989 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
990 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(RegsToSpill[i]);
991 MachineInstr *MI = RI.skipInstruction();) {
992 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
993 // FIXME: Do this with a LiveRangeEdit callback.
994 VRM.RemoveMachineInstrFromMaps(MI);
995 LIS.RemoveMachineInstrFromMaps(MI);
996 MI->eraseFromParent();
997 }
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000998 }
999
1000 // Delete all spilled registers.
1001 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1002 Edit->eraseVirtReg(RegsToSpill[i], LIS);
1003}
1004
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001005void InlineSpiller::spill(LiveRangeEdit &edit) {
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001006 ++NumSpilledRanges;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001007 Edit = &edit;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001008 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1009 && "Trying to spill a stack slot.");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001010 // Share a stack slot among all descendants of Original.
1011 Original = VRM.getOriginal(edit.getReg());
1012 StackSlot = VRM.getStackSlot(Original);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001013 StackInt = 0;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001014
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001015 DEBUG(dbgs() << "Inline spilling "
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001016 << MRI.getRegClass(edit.getReg())->getName()
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001017 << ':' << edit.getParent() << "\nFrom original "
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001018 << LIS.getInterval(Original) << '\n');
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001019 assert(edit.getParent().isSpillable() &&
1020 "Attempting to spill already spilled value.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001021 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001022
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001023 collectRegsToSpill();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001024 analyzeSiblingValues();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001025 reMaterializeAll();
1026
1027 // Remat may handle everything.
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001028 if (!RegsToSpill.empty())
1029 spillAll();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001030
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001031 Edit->calculateRegClassAndHint(MF, LIS, Loops);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001032}