blob: d0c750777f3e12e8607c86ad888995d5f89bcaf1 [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 Olesene93198a2010-11-10 23:55:56 +000019#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000020#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesen0a12b802010-10-26 00:11:35 +000021#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000022#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000023#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000025#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/raw_ostream.h"
31
32using namespace llvm;
33
34namespace {
35class InlineSpiller : public Spiller {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000036 MachineFunctionPass &Pass;
37 MachineFunction &MF;
38 LiveIntervals &LIS;
39 LiveStacks &LSS;
40 AliasAnalysis *AA;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000041 MachineDominatorTree &MDT;
42 MachineLoopInfo &Loops;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000043 VirtRegMap &VRM;
44 MachineFrameInfo &MFI;
45 MachineRegisterInfo &MRI;
46 const TargetInstrInfo &TII;
47 const TargetRegisterInfo &TRI;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +000048
49 // Variables that are valid during spill(), but used by multiple methods.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000050 LiveRangeEdit *Edit;
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +000051 LiveInterval *StackInt;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000052 int StackSlot;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000053 unsigned Original;
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000054
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000055 // All registers to spill to StackSlot, including the main register.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +000056 SmallVector<unsigned, 8> RegsToSpill;
57
58 // All COPY instructions to/from snippets.
59 // They are ignored since both operands refer to the same stack slot.
60 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
61
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +000062 // Values that failed to remat at some point.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000063 SmallPtrSet<VNInfo*, 8> UsedValues;
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +000064
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000065 // Information about a value that was defined by a copy from a sibling
66 // register.
67 struct SibValueInfo {
68 // True when all reaching defs were reloads: No spill is necessary.
69 bool AllDefsAreReloads;
70
71 // The preferred register to spill.
72 unsigned SpillReg;
73
74 // The value of SpillReg that should be spilled.
75 VNInfo *SpillVNI;
76
77 // A defining instruction that is not a sibling copy or a reload, or NULL.
78 // This can be used as a template for rematerialization.
79 MachineInstr *DefMI;
80
81 SibValueInfo(unsigned Reg, VNInfo *VNI)
82 : AllDefsAreReloads(false), SpillReg(Reg), SpillVNI(VNI), DefMI(0) {}
83 };
84
85 // Values in RegsToSpill defined by sibling copies.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +000086 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
87 SibValueMap SibValues;
88
89 // Dead defs generated during spilling.
90 SmallVector<MachineInstr*, 8> DeadDefs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000091
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000092 ~InlineSpiller() {}
93
94public:
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +000095 InlineSpiller(MachineFunctionPass &pass,
96 MachineFunction &mf,
97 VirtRegMap &vrm)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000098 : Pass(pass),
99 MF(mf),
100 LIS(pass.getAnalysis<LiveIntervals>()),
101 LSS(pass.getAnalysis<LiveStacks>()),
102 AA(&pass.getAnalysis<AliasAnalysis>()),
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000103 MDT(pass.getAnalysis<MachineDominatorTree>()),
104 Loops(pass.getAnalysis<MachineLoopInfo>()),
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000105 VRM(vrm),
106 MFI(*mf.getFrameInfo()),
107 MRI(mf.getRegInfo()),
108 TII(*mf.getTarget().getInstrInfo()),
109 TRI(*mf.getTarget().getRegisterInfo()) {}
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000110
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000111 void spill(LiveRangeEdit &);
112
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000113private:
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000114 bool isSnippet(const LiveInterval &SnipLI);
115 void collectRegsToSpill();
116
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000117 bool isRegToSpill(unsigned Reg) {
118 return std::find(RegsToSpill.begin(),
119 RegsToSpill.end(), Reg) != RegsToSpill.end();
120 }
121
122 bool isSibling(unsigned Reg);
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000123 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000124 void analyzeSiblingValues();
125
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000126 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000127 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000128
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000129 void markValueUsed(LiveInterval*, VNInfo*);
130 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000131 void reMaterializeAll();
132
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000133 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000134 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000135 const SmallVectorImpl<unsigned> &Ops,
136 MachineInstr *LoadMI = 0);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000137 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000138 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
139 MachineBasicBlock::iterator MI);
140
141 void spillAroundUses(unsigned Reg);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000142 void spillAll();
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000143};
144}
145
146namespace llvm {
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000147Spiller *createInlineSpiller(MachineFunctionPass &pass,
148 MachineFunction &mf,
149 VirtRegMap &vrm) {
150 return new InlineSpiller(pass, mf, vrm);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000151}
152}
153
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000154//===----------------------------------------------------------------------===//
155// Snippets
156//===----------------------------------------------------------------------===//
157
158// When spilling a virtual register, we also spill any snippets it is connected
159// to. The snippets are small live ranges that only have a single real use,
160// leftovers from live range splitting. Spilling them enables memory operand
161// folding or tightens the live range around the single use.
162//
163// This minimizes register pressure and maximizes the store-to-load distance for
164// spill slots which can be important in tight loops.
165
166/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
167/// otherwise return 0.
168static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
169 if (!MI->isCopy())
170 return 0;
171 if (MI->getOperand(0).getSubReg() != 0)
172 return 0;
173 if (MI->getOperand(1).getSubReg() != 0)
174 return 0;
175 if (MI->getOperand(0).getReg() == Reg)
176 return MI->getOperand(1).getReg();
177 if (MI->getOperand(1).getReg() == Reg)
178 return MI->getOperand(0).getReg();
179 return 0;
180}
181
182/// isSnippet - Identify if a live interval is a snippet that should be spilled.
183/// It is assumed that SnipLI is a virtual register with the same original as
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000184/// Edit->getReg().
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000185bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000186 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000187
188 // A snippet is a tiny live range with only a single instruction using it
189 // besides copies to/from Reg or spills/fills. We accept:
190 //
191 // %snip = COPY %Reg / FILL fi#
192 // %snip = USE %snip
193 // %Reg = COPY %snip / SPILL %snip, fi#
194 //
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000195 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000196 return false;
197
198 MachineInstr *UseMI = 0;
199
200 // Check that all uses satisfy our criteria.
201 for (MachineRegisterInfo::reg_nodbg_iterator
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000202 RI = MRI.reg_nodbg_begin(SnipLI.reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000203 MachineInstr *MI = RI.skipInstruction();) {
204
205 // Allow copies to/from Reg.
206 if (isFullCopyOf(MI, Reg))
207 continue;
208
209 // Allow stack slot loads.
210 int FI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000211 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000212 continue;
213
214 // Allow stack slot stores.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000215 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000216 continue;
217
218 // Allow a single additional instruction.
219 if (UseMI && MI != UseMI)
220 return false;
221 UseMI = MI;
222 }
223 return true;
224}
225
226/// collectRegsToSpill - Collect live range snippets that only have a single
227/// real use.
228void InlineSpiller::collectRegsToSpill() {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000229 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000230
231 // Main register always spills.
232 RegsToSpill.assign(1, Reg);
233 SnippetCopies.clear();
234
235 // Snippets all have the same original, so there can't be any for an original
236 // register.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000237 if (Original == Reg)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000238 return;
239
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000240 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000241 MachineInstr *MI = RI.skipInstruction();) {
242 unsigned SnipReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000243 if (!isSibling(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000244 continue;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000245 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000246 if (!isSnippet(SnipLI))
247 continue;
248 SnippetCopies.insert(MI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000249 if (!isRegToSpill(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000250 RegsToSpill.push_back(SnipReg);
251
252 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
253 }
254}
255
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000256
257//===----------------------------------------------------------------------===//
258// Sibling Values
259//===----------------------------------------------------------------------===//
260
261// After live range splitting, some values to be spilled may be defined by
262// copies from sibling registers. We trace the sibling copies back to the
263// original value if it still exists. We need it for rematerialization.
264//
265// Even when the value can't be rematerialized, we still want to determine if
266// the value has already been spilled, or we may want to hoist the spill from a
267// loop.
268
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000269bool InlineSpiller::isSibling(unsigned Reg) {
270 return TargetRegisterInfo::isVirtualRegister(Reg) &&
271 VRM.getOriginal(Reg) == Original;
272}
273
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000274/// traceSiblingValue - Trace a value that is about to be spilled back to the
275/// real defining instructions by looking through sibling copies. Always stay
276/// within the range of OrigVNI so the registers are known to carry the same
277/// value.
278///
279/// Determine if the value is defined by all reloads, so spilling isn't
280/// necessary - the value is already in the stack slot.
281///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000282/// Return a defining instruction that may be a candidate for rematerialization.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000283///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000284MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
285 VNInfo *OrigVNI) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000286 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
287 << UseVNI->id << '@' << UseVNI->def << '\n');
288 SmallPtrSet<VNInfo*, 8> Visited;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000289 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000290 WorkList.push_back(std::make_pair(UseReg, UseVNI));
291
292 // Best spill candidate seen so far. This must dominate UseVNI.
293 SibValueInfo SVI(UseReg, UseVNI);
294 MachineBasicBlock *UseMBB = LIS.getMBBFromIndex(UseVNI->def);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000295 unsigned SpillDepth = Loops.getLoopDepth(UseMBB);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000296 bool SeenOrigPHI = false; // Original PHI met.
297
298 do {
299 unsigned Reg;
300 VNInfo *VNI;
301 tie(Reg, VNI) = WorkList.pop_back_val();
302 if (!Visited.insert(VNI))
303 continue;
304
305 // Is this value a better spill candidate?
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000306 if (!isRegToSpill(Reg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000307 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000308 if (MBB != UseMBB && MDT.dominates(MBB, UseMBB)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000309 // This is a valid spill location dominating UseVNI.
310 // Prefer to spill at a smaller loop depth.
311 unsigned Depth = Loops.getLoopDepth(MBB);
312 if (Depth < SpillDepth) {
313 DEBUG(dbgs() << " spill depth " << Depth << ": " << PrintReg(Reg)
314 << ':' << VNI->id << '@' << VNI->def << '\n');
315 SVI.SpillReg = Reg;
316 SVI.SpillVNI = VNI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000317 SpillDepth = Depth;
318 }
319 }
320 }
321
322 // Trace through PHI-defs created by live range splitting.
323 if (VNI->isPHIDef()) {
324 if (VNI->def == OrigVNI->def) {
325 DEBUG(dbgs() << " orig phi value " << PrintReg(Reg) << ':'
326 << VNI->id << '@' << VNI->def << '\n');
327 SeenOrigPHI = true;
328 continue;
329 }
330 // Get values live-out of predecessors.
331 LiveInterval &LI = LIS.getInterval(Reg);
332 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
333 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
334 PE = MBB->pred_end(); PI != PE; ++PI) {
335 VNInfo *PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
336 if (PVNI)
337 WorkList.push_back(std::make_pair(Reg, PVNI));
338 }
339 continue;
340 }
341
342 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
343 assert(MI && "Missing def");
344
345 // Trace through sibling copies.
346 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000347 if (isSibling(SrcReg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000348 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
349 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
350 assert(SrcVNI && "Copy from non-existing value");
351 DEBUG(dbgs() << " copy of " << PrintReg(SrcReg) << ':'
352 << SrcVNI->id << '@' << SrcVNI->def << '\n');
353 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
354 continue;
355 }
356 }
357
358 // Track reachable reloads.
359 int FI;
360 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
361 DEBUG(dbgs() << " reload " << PrintReg(Reg) << ':'
362 << VNI->id << "@" << VNI->def << '\n');
363 SVI.AllDefsAreReloads = true;
364 continue;
365 }
366
367 // We have an 'original' def. Don't record trivial cases.
368 if (VNI == UseVNI) {
369 DEBUG(dbgs() << "Not a sibling copy.\n");
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000370 return MI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000371 }
372
373 // Potential remat candidate.
374 DEBUG(dbgs() << " def " << PrintReg(Reg) << ':'
375 << VNI->id << '@' << VNI->def << '\t' << *MI);
376 SVI.DefMI = MI;
377 } while (!WorkList.empty());
378
379 if (SeenOrigPHI || SVI.DefMI)
380 SVI.AllDefsAreReloads = false;
381
382 DEBUG({
383 if (SVI.AllDefsAreReloads)
384 dbgs() << "All defs are reloads.\n";
385 else
386 dbgs() << "Prefer to spill " << PrintReg(SVI.SpillReg) << ':'
387 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def << '\n';
388 });
389 SibValues.insert(std::make_pair(UseVNI, SVI));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000390 return SVI.DefMI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000391}
392
393/// analyzeSiblingValues - Trace values defined by sibling copies back to
394/// something that isn't a sibling copy.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000395///
396/// Keep track of values that may be rematerializable.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000397void InlineSpiller::analyzeSiblingValues() {
398 SibValues.clear();
399
400 // No siblings at all?
401 if (Edit->getReg() == Original)
402 return;
403
404 LiveInterval &OrigLI = LIS.getInterval(Original);
405 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
406 unsigned Reg = RegsToSpill[i];
407 LiveInterval &LI = LIS.getInterval(Reg);
408 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
409 VE = LI.vni_end(); VI != VE; ++VI) {
410 VNInfo *VNI = *VI;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000411 if (VNI->isUnused())
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000412 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000413 MachineInstr *DefMI = 0;
414 // Check possible sibling copies.
415 if (VNI->isPHIDef() || VNI->getCopy()) {
416 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
417 if (OrigVNI->def != VNI->def)
418 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
419 }
420 if (!DefMI && !VNI->isPHIDef())
421 DefMI = LIS.getInstructionFromIndex(VNI->def);
422 if (DefMI)
423 Edit->checkRematerializable(VNI, DefMI, TII, AA);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000424 }
425 }
426}
427
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000428/// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
429/// a spill at a better location.
430bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
431 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
432 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
433 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
434 SibValueMap::const_iterator I = SibValues.find(VNI);
435 if (I == SibValues.end())
436 return false;
437
438 const SibValueInfo &SVI = I->second;
439
440 // Let the normal folding code deal with the boring case.
441 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
442 return false;
443
444 // Conservatively extend the stack slot range to the range of the original
445 // value. We may be able to do better with stack slot coloring by being more
446 // careful here.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000447 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000448 LiveInterval &OrigLI = LIS.getInterval(Original);
449 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000450 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +0000451 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000452 << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000453
454 // Already spilled everywhere.
455 if (SVI.AllDefsAreReloads)
456 return true;
457
458 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
459 // any later spills of the same value.
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000460 eliminateRedundantSpills(LIS.getInterval(SVI.SpillReg), SVI.SpillVNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000461
462 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
463 MachineBasicBlock::iterator MII;
464 if (SVI.SpillVNI->isPHIDef())
465 MII = MBB->SkipPHIsAndLabels(MBB->begin());
466 else {
467 MII = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
468 ++MII;
469 }
470 // Insert spill without kill flag immediately after def.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000471 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
472 MRI.getRegClass(SVI.SpillReg), &TRI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000473 --MII; // Point to store instruction.
474 LIS.InsertMachineInstrInMaps(MII);
475 VRM.addSpillSlotUse(StackSlot, MII);
476 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
477 return true;
478}
479
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000480/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
481/// redundant spills of this value in SLI.reg and sibling copies.
482void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000483 assert(VNI && "Missing value");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000484 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
485 WorkList.push_back(std::make_pair(&SLI, VNI));
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000486 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000487
488 do {
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000489 LiveInterval *LI;
490 tie(LI, VNI) = WorkList.pop_back_val();
491 unsigned Reg = LI->reg;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000492 DEBUG(dbgs() << "Checking redundant spills for " << PrintReg(Reg) << ':'
493 << VNI->id << '@' << VNI->def << '\n');
494
495 // Regs to spill are taken care of.
496 if (isRegToSpill(Reg))
497 continue;
498
499 // Add all of VNI's live range to StackInt.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000500 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
501 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000502
503 // Find all spills and copies of VNI.
504 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
505 MachineInstr *MI = UI.skipInstruction();) {
506 if (!MI->isCopy() && !MI->getDesc().mayStore())
507 continue;
508 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000509 if (LI->getVNInfoAt(Idx) != VNI)
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000510 continue;
511
512 // Follow sibling copies down the dominator tree.
513 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
514 if (isSibling(DstReg)) {
515 LiveInterval &DstLI = LIS.getInterval(DstReg);
516 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
517 assert(DstVNI && "Missing defined value");
518 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000519 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000520 }
521 continue;
522 }
523
524 // Erase spills.
525 int FI;
526 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
527 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
528 // eliminateDeadDefs won't normally remove stores, so switch opcode.
529 MI->setDesc(TII.get(TargetOpcode::KILL));
530 DeadDefs.push_back(MI);
531 }
532 }
533 } while (!WorkList.empty());
534}
535
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000536
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000537//===----------------------------------------------------------------------===//
538// Rematerialization
539//===----------------------------------------------------------------------===//
540
541/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
542/// instruction cannot be eliminated. See through snippet copies
543void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
544 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
545 WorkList.push_back(std::make_pair(LI, VNI));
546 do {
547 tie(LI, VNI) = WorkList.pop_back_val();
548 if (!UsedValues.insert(VNI))
549 continue;
550
551 if (VNI->isPHIDef()) {
552 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
553 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
554 PE = MBB->pred_end(); PI != PE; ++PI) {
555 VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
556 if (PVNI)
557 WorkList.push_back(std::make_pair(LI, PVNI));
558 }
559 continue;
560 }
561
562 // Follow snippet copies.
563 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
564 if (!SnippetCopies.count(MI))
565 continue;
566 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
567 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
568 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex());
569 assert(SnipVNI && "Snippet undefined before copy");
570 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
571 } while (!WorkList.empty());
572}
573
574/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
575bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
576 MachineBasicBlock::iterator MI) {
577 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
578 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx);
579
580 if (!ParentVNI) {
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000581 DEBUG(dbgs() << "\tadding <undef> flags: ");
582 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
583 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000584 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000585 MO.setIsUndef();
586 }
587 DEBUG(dbgs() << UseIdx << '\t' << *MI);
588 return true;
589 }
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000590
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000591 if (SnippetCopies.count(MI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000592 return false;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000593
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000594 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
595 LiveRangeEdit::Remat RM(ParentVNI);
596 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
597 if (SibI != SibValues.end())
598 RM.OrigMI = SibI->second.DefMI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000599 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000600 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000601 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
602 return false;
603 }
604
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000605 // If the instruction also writes VirtReg.reg, it had better not require the
606 // same register for uses and defs.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000607 bool Reads, Writes;
608 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000609 tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000610 if (Writes) {
611 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
612 MachineOperand &MO = MI->getOperand(Ops[i]);
613 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000614 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000615 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
616 return false;
617 }
618 }
619 }
620
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000621 // Before rematerializing into a register for a single instruction, try to
622 // fold a load into the instruction. That avoids allocating a new register.
623 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
624 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000625 Edit->markRematerialized(RM.ParentVNI);
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000626 return true;
627 }
628
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000629 // Alocate a new register for the remat.
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000630 LiveInterval &NewLI = Edit->createFrom(VirtReg.reg, LIS, VRM);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000631 NewLI.markNotSpillable();
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000632
633 // Finally we can rematerialize OrigMI before MI.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000634 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
635 LIS, TII, TRI);
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000636 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000637 << *LIS.getInstructionFromIndex(DefIdx));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000638
639 // Replace operands
640 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
641 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000642 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000643 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000644 MO.setIsKill();
645 }
646 }
647 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
648
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000649 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000650 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000651 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000652 return true;
653}
654
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000655/// reMaterializeAll - Try to rematerialize as many uses as possible,
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000656/// and trim the live ranges after.
657void InlineSpiller::reMaterializeAll() {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000658 // analyzeSiblingValues has already tested all relevant defining instructions.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000659 if (!Edit->anyRematerializable(LIS, TII, AA))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000660 return;
661
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000662 UsedValues.clear();
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000663
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000664 // Try to remat before all uses of snippets.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000665 bool anyRemat = false;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000666 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
667 unsigned Reg = RegsToSpill[i];
668 LiveInterval &LI = LIS.getInterval(Reg);
669 for (MachineRegisterInfo::use_nodbg_iterator
670 RI = MRI.use_nodbg_begin(Reg);
671 MachineInstr *MI = RI.skipInstruction();)
672 anyRemat |= reMaterializeFor(LI, MI);
673 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000674 if (!anyRemat)
675 return;
676
677 // Remove any values that were completely rematted.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000678 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
679 unsigned Reg = RegsToSpill[i];
680 LiveInterval &LI = LIS.getInterval(Reg);
681 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
682 I != E; ++I) {
683 VNInfo *VNI = *I;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000684 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000685 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000686 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
687 MI->addRegisterDead(Reg, &TRI);
688 if (!MI->allDefsAreDead())
689 continue;
690 DEBUG(dbgs() << "All defs dead: " << *MI);
691 DeadDefs.push_back(MI);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000692 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000693 }
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000694
695 // Eliminate dead code after remat. Note that some snippet copies may be
696 // deleted here.
697 if (DeadDefs.empty())
698 return;
699 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
700 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
701
702 // Get rid of deleted and empty intervals.
703 for (unsigned i = RegsToSpill.size(); i != 0; --i) {
704 unsigned Reg = RegsToSpill[i-1];
705 if (!LIS.hasInterval(Reg)) {
706 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
707 continue;
708 }
709 LiveInterval &LI = LIS.getInterval(Reg);
710 if (!LI.empty())
711 continue;
712 Edit->eraseVirtReg(Reg, LIS);
713 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
714 }
715 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000716}
717
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000718
719//===----------------------------------------------------------------------===//
720// Spilling
721//===----------------------------------------------------------------------===//
722
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000723/// If MI is a load or store of StackSlot, it can be removed.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000724bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000725 int FI = 0;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000726 unsigned InstrReg;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000727 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
728 !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000729 return false;
730
731 // We have a stack access. Is it the right register and slot?
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000732 if (InstrReg != Reg || FI != StackSlot)
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000733 return false;
734
735 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000736 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000737 MI->eraseFromParent();
738 return true;
739}
740
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000741/// foldMemoryOperand - Try folding stack slot references in Ops into MI.
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000742/// @param MI Instruction using or defining the current register.
Jakob Stoklund Olesen39048252010-12-18 03:28:32 +0000743/// @param Ops Operand indices from readsWritesVirtualRegister().
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000744/// @param LoadMI Load instruction to use instead of stack slot when non-null.
745/// @return True on success, and MI will be erased.
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000746bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000747 const SmallVectorImpl<unsigned> &Ops,
748 MachineInstr *LoadMI) {
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000749 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
750 // operands.
751 SmallVector<unsigned, 8> FoldOps;
752 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
753 unsigned Idx = Ops[i];
754 MachineOperand &MO = MI->getOperand(Idx);
755 if (MO.isImplicit())
756 continue;
757 // FIXME: Teach targets to deal with subregs.
758 if (MO.getSubReg())
759 return false;
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000760 // We cannot fold a load instruction into a def.
761 if (LoadMI && MO.isDef())
762 return false;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000763 // Tied use operands should not be passed to foldMemoryOperand.
764 if (!MI->isRegTiedToDefOperand(Idx))
765 FoldOps.push_back(Idx);
766 }
767
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000768 MachineInstr *FoldMI =
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000769 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
770 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000771 if (!FoldMI)
772 return false;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000773 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000774 if (!LoadMI)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000775 VRM.addSpillSlotUse(StackSlot, FoldMI);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +0000776 MI->eraseFromParent();
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000777 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
778 return true;
779}
780
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000781/// insertReload - Insert a reload of NewLI.reg before MI.
782void InlineSpiller::insertReload(LiveInterval &NewLI,
783 MachineBasicBlock::iterator MI) {
784 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000785 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000786 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
787 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000788 --MI; // Point to load instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000789 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
790 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000791 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
Lang Hames6e2968c2010-09-25 12:04:16 +0000792 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000793 LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000794 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
795}
796
797/// insertSpill - Insert a spill of NewLI.reg after MI.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000798void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000799 MachineBasicBlock::iterator MI) {
800 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesen68257e62010-11-15 20:55:49 +0000801
802 // Get the defined value. It could be an early clobber so keep the def index.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000803 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000804 VNInfo *VNI = OldLI.getVNInfoAt(Idx);
Jakob Stoklund Olesen68257e62010-11-15 20:55:49 +0000805 assert(VNI && VNI->def.getDefIndex() == Idx && "Inconsistent VNInfo");
806 Idx = VNI->def;
807
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000808 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
809 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000810 --MI; // Point to store instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000811 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
812 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000813 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000814 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000815 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
816}
817
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000818/// spillAroundUses - insert spill code around each use of Reg.
819void InlineSpiller::spillAroundUses(unsigned Reg) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000820 LiveInterval &OldLI = LIS.getInterval(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000821
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000822 // Iterate over instructions using Reg.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000823 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000824 MachineInstr *MI = RI.skipInstruction();) {
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000825
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000826 // Debug values are not allowed to affect codegen.
827 if (MI->isDebugValue()) {
828 // Modify DBG_VALUE now that the value is in a spill slot.
829 uint64_t Offset = MI->getOperand(1).getImm();
830 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
831 DebugLoc DL = MI->getDebugLoc();
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000832 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000833 Offset, MDPtr, DL)) {
834 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
835 MachineBasicBlock *MBB = MI->getParent();
836 MBB->insert(MBB->erase(MI), NewDV);
837 } else {
838 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
839 MI->eraseFromParent();
840 }
841 continue;
842 }
843
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000844 // Ignore copies to/from snippets. We'll delete them.
845 if (SnippetCopies.count(MI))
846 continue;
847
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000848 // Stack slot accesses may coalesce away.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000849 if (coalesceStackAccess(MI, Reg))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000850 continue;
851
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000852 // Analyze instruction.
853 bool Reads, Writes;
854 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000855 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000856
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000857 // Check for a sibling copy.
858 unsigned SibReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000859 if (SibReg && isSibling(SibReg)) {
860 if (Writes) {
861 // Hoist the spill of a sib-reg copy.
862 if (hoistSpill(OldLI, MI)) {
863 // This COPY is now dead, the value is already in the stack slot.
864 MI->getOperand(0).setIsDead();
865 DeadDefs.push_back(MI);
866 continue;
867 }
868 } else {
869 // This is a reload for a sib-reg copy. Drop spills downstream.
870 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
871 LiveInterval &SibLI = LIS.getInterval(SibReg);
872 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
873 // The COPY will fold to a reload below.
874 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000875 }
876
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000877 // Attempt to fold memory ops.
878 if (foldMemoryOperand(MI, Ops))
879 continue;
880
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000881 // Allocate interval around instruction.
882 // FIXME: Infer regclass from instruction alone.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000883 LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000884 NewLI.markNotSpillable();
885
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000886 if (Reads)
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000887 insertReload(NewLI, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000888
889 // Rewrite instruction operands.
890 bool hasLiveDef = false;
891 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
892 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000893 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000894 if (MO.isUse()) {
895 if (!MI->isRegTiedToDefOperand(Ops[i]))
896 MO.setIsKill();
897 } else {
898 if (!MO.isDead())
899 hasLiveDef = true;
900 }
901 }
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000902
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000903 // FIXME: Use a second vreg if instruction has no tied ops.
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000904 if (Writes && hasLiveDef)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000905 insertSpill(NewLI, OldLI, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000906
907 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000908 }
909}
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000910
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000911/// spillAll - Spill all registers remaining after rematerialization.
912void InlineSpiller::spillAll() {
913 // Update LiveStacks now that we are committed to spilling.
914 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
915 StackSlot = VRM.assignVirt2StackSlot(Original);
916 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
917 StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
918 } else
919 StackInt = &LSS.getInterval(StackSlot);
920
921 if (Original != Edit->getReg())
922 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
923
924 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
925 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
926 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
927 StackInt->getValNumInfo(0));
928 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
929
930 // Spill around uses of all RegsToSpill.
931 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
932 spillAroundUses(RegsToSpill[i]);
933
934 // Hoisted spills may cause dead code.
935 if (!DeadDefs.empty()) {
936 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
937 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
938 }
939
940 // Finally delete the SnippetCopies.
941 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg());
942 MachineInstr *MI = RI.skipInstruction();) {
943 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
944 // FIXME: Do this with a LiveRangeEdit callback.
945 VRM.RemoveMachineInstrFromMaps(MI);
946 LIS.RemoveMachineInstrFromMaps(MI);
947 MI->eraseFromParent();
948 }
949
950 // Delete all spilled registers.
951 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
952 Edit->eraseVirtReg(RegsToSpill[i], LIS);
953}
954
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000955void InlineSpiller::spill(LiveRangeEdit &edit) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000956 Edit = &edit;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000957 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
958 && "Trying to spill a stack slot.");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000959 // Share a stack slot among all descendants of Original.
960 Original = VRM.getOriginal(edit.getReg());
961 StackSlot = VRM.getStackSlot(Original);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000962 StackInt = 0;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000963
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000964 DEBUG(dbgs() << "Inline spilling "
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000965 << MRI.getRegClass(edit.getReg())->getName()
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000966 << ':' << edit.getParent() << "\nFrom original "
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000967 << LIS.getInterval(Original) << '\n');
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000968 assert(edit.getParent().isSpillable() &&
969 "Attempting to spill already spilled value.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000970 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000971
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000972 collectRegsToSpill();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000973 analyzeSiblingValues();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000974 reMaterializeAll();
975
976 // Remat may handle everything.
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000977 if (!RegsToSpill.empty())
978 spillAll();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000979
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000980 Edit->calculateRegClassAndHint(MF, LIS, Loops);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000981}