blob: 01fe84030e33e83f59157d55434fd3a96824f448 [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 Olesen1ab7c8e2011-09-09 18:11:41 +000020#include "llvm/ADT/TinyPtrVector.h"
Jakob Stoklund Olesene93198a2010-11-10 23:55:56 +000021#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000022#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesen0a12b802010-10-26 00:11:35 +000023#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000024#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000025#include "llvm/CodeGen/MachineFrameInfo.h"
26#include "llvm/CodeGen/MachineFunction.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
29#include "llvm/Target/TargetMachine.h"
30#include "llvm/Target/TargetInstrInfo.h"
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +000031#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.h"
34
35using namespace llvm;
36
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000037STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000038STATISTIC(NumSnippets, "Number of spilled snippets");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000039STATISTIC(NumSpills, "Number of spills inserted");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000040STATISTIC(NumSpillsRemoved, "Number of spills removed");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000041STATISTIC(NumReloads, "Number of reloads inserted");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000042STATISTIC(NumReloadsRemoved, "Number of reloads removed");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000043STATISTIC(NumFolded, "Number of folded stack accesses");
44STATISTIC(NumFoldedLoads, "Number of folded loads");
45STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000046STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads");
47STATISTIC(NumHoists, "Number of hoisted spills");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000048
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +000049static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
50 cl::desc("Disable inline spill hoisting"));
51
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000052namespace {
53class InlineSpiller : public Spiller {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000054 MachineFunctionPass &Pass;
55 MachineFunction &MF;
56 LiveIntervals &LIS;
57 LiveStacks &LSS;
58 AliasAnalysis *AA;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000059 MachineDominatorTree &MDT;
60 MachineLoopInfo &Loops;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000061 VirtRegMap &VRM;
62 MachineFrameInfo &MFI;
63 MachineRegisterInfo &MRI;
64 const TargetInstrInfo &TII;
65 const TargetRegisterInfo &TRI;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +000066
67 // Variables that are valid during spill(), but used by multiple methods.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000068 LiveRangeEdit *Edit;
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +000069 LiveInterval *StackInt;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000070 int StackSlot;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000071 unsigned Original;
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000072
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000073 // All registers to spill to StackSlot, including the main register.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +000074 SmallVector<unsigned, 8> RegsToSpill;
75
76 // All COPY instructions to/from snippets.
77 // They are ignored since both operands refer to the same stack slot.
78 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
79
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +000080 // Values that failed to remat at some point.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000081 SmallPtrSet<VNInfo*, 8> UsedValues;
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +000082
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000083public:
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000084 // Information about a value that was defined by a copy from a sibling
85 // register.
86 struct SibValueInfo {
87 // True when all reaching defs were reloads: No spill is necessary.
88 bool AllDefsAreReloads;
89
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000090 // True when value is defined by an original PHI not from splitting.
91 bool DefByOrigPHI;
92
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000093 // The preferred register to spill.
94 unsigned SpillReg;
95
96 // The value of SpillReg that should be spilled.
97 VNInfo *SpillVNI;
98
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000099 // The block where SpillVNI should be spilled. Currently, this must be the
100 // block containing SpillVNI->def.
101 MachineBasicBlock *SpillMBB;
102
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000103 // A defining instruction that is not a sibling copy or a reload, or NULL.
104 // This can be used as a template for rematerialization.
105 MachineInstr *DefMI;
106
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000107 // List of values that depend on this one. These values are actually the
108 // same, but live range splitting has placed them in different registers,
109 // or SSA update needed to insert PHI-defs to preserve SSA form. This is
110 // copies of the current value and phi-kills. Usually only phi-kills cause
111 // more than one dependent value.
112 TinyPtrVector<VNInfo*> Deps;
113
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000114 SibValueInfo(unsigned Reg, VNInfo *VNI)
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000115 : AllDefsAreReloads(true), DefByOrigPHI(false),
116 SpillReg(Reg), SpillVNI(VNI), SpillMBB(0), DefMI(0) {}
117
118 // Returns true when a def has been found.
119 bool hasDef() const { return DefByOrigPHI || DefMI; }
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000120 };
121
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000122private:
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000123 // Values in RegsToSpill defined by sibling copies.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000124 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
125 SibValueMap SibValues;
126
127 // Dead defs generated during spilling.
128 SmallVector<MachineInstr*, 8> DeadDefs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000129
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000130 ~InlineSpiller() {}
131
132public:
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000133 InlineSpiller(MachineFunctionPass &pass,
134 MachineFunction &mf,
135 VirtRegMap &vrm)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000136 : Pass(pass),
137 MF(mf),
138 LIS(pass.getAnalysis<LiveIntervals>()),
139 LSS(pass.getAnalysis<LiveStacks>()),
140 AA(&pass.getAnalysis<AliasAnalysis>()),
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000141 MDT(pass.getAnalysis<MachineDominatorTree>()),
142 Loops(pass.getAnalysis<MachineLoopInfo>()),
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000143 VRM(vrm),
144 MFI(*mf.getFrameInfo()),
145 MRI(mf.getRegInfo()),
146 TII(*mf.getTarget().getInstrInfo()),
147 TRI(*mf.getTarget().getRegisterInfo()) {}
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000148
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000149 void spill(LiveRangeEdit &);
150
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000151private:
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000152 bool isSnippet(const LiveInterval &SnipLI);
153 void collectRegsToSpill();
154
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000155 bool isRegToSpill(unsigned Reg) {
156 return std::find(RegsToSpill.begin(),
157 RegsToSpill.end(), Reg) != RegsToSpill.end();
158 }
159
160 bool isSibling(unsigned Reg);
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000161 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000162 void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = 0);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000163 void analyzeSiblingValues();
164
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000165 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000166 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000167
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000168 void markValueUsed(LiveInterval*, VNInfo*);
169 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000170 void reMaterializeAll();
171
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000172 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000173 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000174 const SmallVectorImpl<unsigned> &Ops,
175 MachineInstr *LoadMI = 0);
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000176 void insertReload(LiveInterval &NewLI, SlotIndex,
177 MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000178 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000179 SlotIndex, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000180
181 void spillAroundUses(unsigned Reg);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000182 void spillAll();
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000183};
184}
185
186namespace llvm {
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000187Spiller *createInlineSpiller(MachineFunctionPass &pass,
188 MachineFunction &mf,
189 VirtRegMap &vrm) {
190 return new InlineSpiller(pass, mf, vrm);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000191}
192}
193
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000194//===----------------------------------------------------------------------===//
195// Snippets
196//===----------------------------------------------------------------------===//
197
198// When spilling a virtual register, we also spill any snippets it is connected
199// to. The snippets are small live ranges that only have a single real use,
200// leftovers from live range splitting. Spilling them enables memory operand
201// folding or tightens the live range around the single use.
202//
203// This minimizes register pressure and maximizes the store-to-load distance for
204// spill slots which can be important in tight loops.
205
206/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
207/// otherwise return 0.
208static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
Rafael Espindolacfe52542011-06-30 21:15:52 +0000209 if (!MI->isFullCopy())
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000210 return 0;
211 if (MI->getOperand(0).getReg() == Reg)
212 return MI->getOperand(1).getReg();
213 if (MI->getOperand(1).getReg() == Reg)
214 return MI->getOperand(0).getReg();
215 return 0;
216}
217
218/// isSnippet - Identify if a live interval is a snippet that should be spilled.
219/// It is assumed that SnipLI is a virtual register with the same original as
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000220/// Edit->getReg().
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000221bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000222 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000223
224 // A snippet is a tiny live range with only a single instruction using it
225 // besides copies to/from Reg or spills/fills. We accept:
226 //
227 // %snip = COPY %Reg / FILL fi#
228 // %snip = USE %snip
229 // %Reg = COPY %snip / SPILL %snip, fi#
230 //
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000231 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000232 return false;
233
234 MachineInstr *UseMI = 0;
235
236 // Check that all uses satisfy our criteria.
237 for (MachineRegisterInfo::reg_nodbg_iterator
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000238 RI = MRI.reg_nodbg_begin(SnipLI.reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000239 MachineInstr *MI = RI.skipInstruction();) {
240
241 // Allow copies to/from Reg.
242 if (isFullCopyOf(MI, Reg))
243 continue;
244
245 // Allow stack slot loads.
246 int FI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000247 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000248 continue;
249
250 // Allow stack slot stores.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000251 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000252 continue;
253
254 // Allow a single additional instruction.
255 if (UseMI && MI != UseMI)
256 return false;
257 UseMI = MI;
258 }
259 return true;
260}
261
262/// collectRegsToSpill - Collect live range snippets that only have a single
263/// real use.
264void InlineSpiller::collectRegsToSpill() {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000265 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000266
267 // Main register always spills.
268 RegsToSpill.assign(1, Reg);
269 SnippetCopies.clear();
270
271 // Snippets all have the same original, so there can't be any for an original
272 // register.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000273 if (Original == Reg)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000274 return;
275
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000276 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000277 MachineInstr *MI = RI.skipInstruction();) {
278 unsigned SnipReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000279 if (!isSibling(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000280 continue;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000281 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000282 if (!isSnippet(SnipLI))
283 continue;
284 SnippetCopies.insert(MI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000285 if (isRegToSpill(SnipReg))
286 continue;
287 RegsToSpill.push_back(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000288 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000289 ++NumSnippets;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000290 }
291}
292
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000293
294//===----------------------------------------------------------------------===//
295// Sibling Values
296//===----------------------------------------------------------------------===//
297
298// After live range splitting, some values to be spilled may be defined by
299// copies from sibling registers. We trace the sibling copies back to the
300// original value if it still exists. We need it for rematerialization.
301//
302// Even when the value can't be rematerialized, we still want to determine if
303// the value has already been spilled, or we may want to hoist the spill from a
304// loop.
305
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000306bool InlineSpiller::isSibling(unsigned Reg) {
307 return TargetRegisterInfo::isVirtualRegister(Reg) &&
308 VRM.getOriginal(Reg) == Original;
309}
310
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000311#ifndef NDEBUG
312static raw_ostream &operator<<(raw_ostream &OS,
313 const InlineSpiller::SibValueInfo &SVI) {
314 OS << "spill " << PrintReg(SVI.SpillReg) << ':'
315 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
316 if (SVI.SpillMBB)
317 OS << " in BB#" << SVI.SpillMBB->getNumber();
318 if (SVI.AllDefsAreReloads)
319 OS << " all-reloads";
320 if (SVI.DefByOrigPHI)
321 OS << " orig-phi";
322 OS << " deps[";
323 for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i)
324 OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def;
325 OS << " ]";
326 if (SVI.DefMI)
327 OS << " def: " << *SVI.DefMI;
328 else
329 OS << '\n';
330 return OS;
331}
332#endif
333
334/// propagateSiblingValue - Propagate the value in SVI to dependents if it is
335/// known. Otherwise remember the dependency for later.
336///
337/// @param SVI SibValues entry to propagate.
338/// @param VNI Dependent value, or NULL to propagate to all saved dependents.
339void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVI,
340 VNInfo *VNI) {
341 // When VNI is non-NULL, add it to SVI's deps, and only propagate to that.
342 TinyPtrVector<VNInfo*> FirstDeps;
343 if (VNI) {
344 FirstDeps.push_back(VNI);
345 SVI->second.Deps.push_back(VNI);
346 }
347
348 // Has the value been completely determined yet? If not, defer propagation.
349 if (!SVI->second.hasDef())
350 return;
351
352 // Work list of values to propagate. It would be nice to use a SetVector
353 // here, but then we would be forced to use a SmallSet.
354 SmallVector<SibValueMap::iterator, 8> WorkList(1, SVI);
355 SmallPtrSet<VNInfo*, 8> WorkSet;
356
357 do {
358 SVI = WorkList.pop_back_val();
359 WorkSet.erase(SVI->first);
360 TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps;
361 VNI = 0;
362
363 SibValueInfo &SV = SVI->second;
364 if (!SV.SpillMBB)
365 SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
366
367 DEBUG(dbgs() << " prop to " << Deps->size() << ": "
368 << SVI->first->id << '@' << SVI->first->def << ":\t" << SV);
369
370 assert(SV.hasDef() && "Propagating undefined value");
371
372 // Should this value be propagated as a preferred spill candidate? We don't
373 // propagate values of registers that are about to spill.
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +0000374 bool PropSpill = !DisableHoisting && !isRegToSpill(SV.SpillReg);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000375 unsigned SpillDepth = ~0u;
376
377 for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(),
378 DepE = Deps->end(); DepI != DepE; ++DepI) {
379 SibValueMap::iterator DepSVI = SibValues.find(*DepI);
380 assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
381 SibValueInfo &DepSV = DepSVI->second;
382 if (!DepSV.SpillMBB)
383 DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
384
385 bool Changed = false;
386
387 // Propagate defining instruction.
388 if (!DepSV.hasDef()) {
389 Changed = true;
390 DepSV.DefMI = SV.DefMI;
391 DepSV.DefByOrigPHI = SV.DefByOrigPHI;
392 }
393
394 // Propagate AllDefsAreReloads. For PHI values, this computes an AND of
395 // all predecessors.
396 if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
397 Changed = true;
398 DepSV.AllDefsAreReloads = false;
399 }
400
401 // Propagate best spill value.
402 if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
403 if (SV.SpillMBB == DepSV.SpillMBB) {
404 // DepSV is in the same block. Hoist when dominated.
405 if (SV.SpillVNI->def < DepSV.SpillVNI->def) {
406 // This is an alternative def earlier in the same MBB.
407 // Hoist the spill as far as possible in SpillMBB. This can ease
408 // register pressure:
409 //
410 // x = def
411 // y = use x
412 // s = copy x
413 //
414 // Hoisting the spill of s to immediately after the def removes the
415 // interference between x and y:
416 //
417 // x = def
418 // spill x
419 // y = use x<kill>
420 //
421 Changed = true;
422 DepSV.SpillReg = SV.SpillReg;
423 DepSV.SpillVNI = SV.SpillVNI;
424 DepSV.SpillMBB = SV.SpillMBB;
425 }
426 } else {
427 // DepSV is in a different block.
428 if (SpillDepth == ~0u)
429 SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
430
431 // Also hoist spills to blocks with smaller loop depth, but make sure
432 // that the new value dominates. Non-phi dependents are always
433 // dominated, phis need checking.
434 if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
435 (!DepSVI->first->isPHIDef() ||
436 MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
437 Changed = true;
438 DepSV.SpillReg = SV.SpillReg;
439 DepSV.SpillVNI = SV.SpillVNI;
440 DepSV.SpillMBB = SV.SpillMBB;
441 }
442 }
443 }
444
445 if (!Changed)
446 continue;
447
448 // Something changed in DepSVI. Propagate to dependents.
449 if (WorkSet.insert(DepSVI->first))
450 WorkList.push_back(DepSVI);
451
452 DEBUG(dbgs() << " update " << DepSVI->first->id << '@'
453 << DepSVI->first->def << " to:\t" << DepSV);
454 }
455 } while (!WorkList.empty());
456}
457
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000458/// traceSiblingValue - Trace a value that is about to be spilled back to the
459/// real defining instructions by looking through sibling copies. Always stay
460/// within the range of OrigVNI so the registers are known to carry the same
461/// value.
462///
463/// Determine if the value is defined by all reloads, so spilling isn't
464/// necessary - the value is already in the stack slot.
465///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000466/// Return a defining instruction that may be a candidate for rematerialization.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000467///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000468MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
469 VNInfo *OrigVNI) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000470 // Check if a cached value already exists.
471 SibValueMap::iterator SVI;
472 bool Inserted;
473 tie(SVI, Inserted) =
474 SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
475 if (!Inserted) {
476 DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
477 << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
478 return SVI->second.DefMI;
479 }
480
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000481 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
482 << UseVNI->id << '@' << UseVNI->def << '\n');
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000483
484 // List of (Reg, VNI) that have been inserted into SibValues, but need to be
485 // processed.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000486 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000487 WorkList.push_back(std::make_pair(UseReg, UseVNI));
488
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000489 do {
490 unsigned Reg;
491 VNInfo *VNI;
492 tie(Reg, VNI) = WorkList.pop_back_val();
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000493 DEBUG(dbgs() << " " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
494 << ":\t");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000495
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000496 // First check if this value has already been computed.
497 SVI = SibValues.find(VNI);
498 assert(SVI != SibValues.end() && "Missing SibValues entry");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000499
500 // Trace through PHI-defs created by live range splitting.
501 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000502 // Stop at original PHIs. We don't know the value at the predecessors.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000503 if (VNI->def == OrigVNI->def) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000504 DEBUG(dbgs() << "orig phi value\n");
505 SVI->second.DefByOrigPHI = true;
506 SVI->second.AllDefsAreReloads = false;
507 propagateSiblingValue(SVI);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000508 continue;
509 }
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000510
511 // This is a PHI inserted by live range splitting. We could trace the
512 // live-out value from predecessor blocks, but that search can be very
513 // expensive if there are many predecessors and many more PHIs as
514 // generated by tail-dup when it sees an indirectbr. Instead, look at
515 // all the non-PHI defs that have the same value as OrigVNI. They must
516 // jointly dominate VNI->def. This is not optimal since VNI may actually
517 // be jointly dominated by a smaller subset of defs, so there is a change
518 // we will miss a AllDefsAreReloads optimization.
519
520 // Separate all values dominated by OrigVNI into PHIs and non-PHIs.
521 SmallVector<VNInfo*, 8> PHIs, NonPHIs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000522 LiveInterval &LI = LIS.getInterval(Reg);
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000523 LiveInterval &OrigLI = LIS.getInterval(Original);
524
525 for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end();
526 VI != VE; ++VI) {
527 VNInfo *VNI2 = *VI;
528 if (VNI2->isUnused())
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000529 continue;
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000530 if (!OrigLI.containsOneValue() &&
531 OrigLI.getVNInfoAt(VNI2->def) != OrigVNI)
532 continue;
533 if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def)
534 PHIs.push_back(VNI2);
535 else
536 NonPHIs.push_back(VNI2);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000537 }
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000538 DEBUG(dbgs() << "split phi value, checking " << PHIs.size()
539 << " phi-defs, and " << NonPHIs.size()
540 << " non-phi/orig defs\n");
541
542 // Create entries for all the PHIs. Don't add them to the worklist, we
543 // are processing all of them in one go here.
544 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
545 SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i])));
546
547 // Add every PHI as a dependent of all the non-PHIs.
548 for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) {
549 VNInfo *NonPHI = NonPHIs[i];
550 // Known value? Try an insertion.
551 tie(SVI, Inserted) =
552 SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI)));
553 // Add all the PHIs as dependents of NonPHI.
554 for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi)
555 SVI->second.Deps.push_back(PHIs[pi]);
556 // This is the first time we see NonPHI, add it to the worklist.
557 if (Inserted)
558 WorkList.push_back(std::make_pair(Reg, NonPHI));
559 else
560 // Propagate to all inserted PHIs, not just VNI.
561 propagateSiblingValue(SVI);
562 }
563
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000564 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000565 continue;
566 }
567
568 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
569 assert(MI && "Missing def");
570
571 // Trace through sibling copies.
572 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000573 if (isSibling(SrcReg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000574 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
575 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
576 assert(SrcVNI && "Copy from non-existing value");
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000577 DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000578 << SrcVNI->id << '@' << SrcVNI->def << '\n');
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000579 // Known sibling source value? Try an insertion.
580 tie(SVI, Inserted) = SibValues.insert(std::make_pair(SrcVNI,
581 SibValueInfo(SrcReg, SrcVNI)));
582 // This is the first time we see Src, add it to the worklist.
583 if (Inserted)
584 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
585 propagateSiblingValue(SVI, VNI);
586 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000587 continue;
588 }
589 }
590
591 // Track reachable reloads.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000592 SVI->second.DefMI = MI;
593 SVI->second.SpillMBB = MI->getParent();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000594 int FI;
595 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000596 DEBUG(dbgs() << "reload\n");
597 propagateSiblingValue(SVI);
598 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000599 continue;
600 }
601
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000602 // Potential remat candidate.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000603 DEBUG(dbgs() << "def " << *MI);
604 SVI->second.AllDefsAreReloads = false;
605 propagateSiblingValue(SVI);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000606 } while (!WorkList.empty());
607
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000608 // Look up the value we were looking for. We already did this lokup at the
609 // top of the function, but SibValues may have been invalidated.
610 SVI = SibValues.find(UseVNI);
611 assert(SVI != SibValues.end() && "Didn't compute requested info");
612 DEBUG(dbgs() << " traced to:\t" << SVI->second);
613 return SVI->second.DefMI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000614}
615
616/// analyzeSiblingValues - Trace values defined by sibling copies back to
617/// something that isn't a sibling copy.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000618///
619/// Keep track of values that may be rematerializable.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000620void InlineSpiller::analyzeSiblingValues() {
621 SibValues.clear();
622
623 // No siblings at all?
624 if (Edit->getReg() == Original)
625 return;
626
627 LiveInterval &OrigLI = LIS.getInterval(Original);
628 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
629 unsigned Reg = RegsToSpill[i];
630 LiveInterval &LI = LIS.getInterval(Reg);
631 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
632 VE = LI.vni_end(); VI != VE; ++VI) {
633 VNInfo *VNI = *VI;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000634 if (VNI->isUnused())
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000635 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000636 MachineInstr *DefMI = 0;
637 // Check possible sibling copies.
638 if (VNI->isPHIDef() || VNI->getCopy()) {
639 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
Jakob Stoklund Olesen9693d4c2011-07-05 15:38:41 +0000640 assert(OrigVNI && "Def outside original live range");
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000641 if (OrigVNI->def != VNI->def)
642 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
643 }
644 if (!DefMI && !VNI->isPHIDef())
645 DefMI = LIS.getInstructionFromIndex(VNI->def);
Jakob Stoklund Olesen3b7d9172011-04-20 22:14:20 +0000646 if (DefMI && Edit->checkRematerializable(VNI, DefMI, TII, AA)) {
647 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
648 << VNI->def << " may remat from " << *DefMI);
649 }
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000650 }
651 }
652}
653
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000654/// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
655/// a spill at a better location.
656bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
657 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
658 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
659 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000660 SibValueMap::iterator I = SibValues.find(VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000661 if (I == SibValues.end())
662 return false;
663
664 const SibValueInfo &SVI = I->second;
665
666 // Let the normal folding code deal with the boring case.
667 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
668 return false;
669
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000670 // SpillReg may have been deleted by remat and DCE.
671 if (!LIS.hasInterval(SVI.SpillReg)) {
672 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
673 SibValues.erase(I);
674 return false;
675 }
676
677 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
678 if (!SibLI.containsValue(SVI.SpillVNI)) {
679 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
680 SibValues.erase(I);
681 return false;
682 }
683
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000684 // Conservatively extend the stack slot range to the range of the original
685 // value. We may be able to do better with stack slot coloring by being more
686 // careful here.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000687 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000688 LiveInterval &OrigLI = LIS.getInterval(Original);
689 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000690 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +0000691 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000692 << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000693
694 // Already spilled everywhere.
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000695 if (SVI.AllDefsAreReloads) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000696 DEBUG(dbgs() << "\tno spill needed: " << SVI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000697 ++NumOmitReloadSpill;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000698 return true;
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000699 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000700 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
701 // any later spills of the same value.
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000702 eliminateRedundantSpills(SibLI, SVI.SpillVNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000703
704 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
705 MachineBasicBlock::iterator MII;
706 if (SVI.SpillVNI->isPHIDef())
707 MII = MBB->SkipPHIsAndLabels(MBB->begin());
708 else {
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000709 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
710 assert(DefMI && "Defining instruction disappeared");
711 MII = DefMI;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000712 ++MII;
713 }
714 // Insert spill without kill flag immediately after def.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000715 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
716 MRI.getRegClass(SVI.SpillReg), &TRI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000717 --MII; // Point to store instruction.
718 LIS.InsertMachineInstrInMaps(MII);
719 VRM.addSpillSlotUse(StackSlot, MII);
720 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000721
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000722 ++NumSpills;
723 ++NumHoists;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000724 return true;
725}
726
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000727/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
728/// redundant spills of this value in SLI.reg and sibling copies.
729void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000730 assert(VNI && "Missing value");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000731 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
732 WorkList.push_back(std::make_pair(&SLI, VNI));
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000733 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000734
735 do {
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000736 LiveInterval *LI;
737 tie(LI, VNI) = WorkList.pop_back_val();
738 unsigned Reg = LI->reg;
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000739 DEBUG(dbgs() << "Checking redundant spills for "
740 << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000741
742 // Regs to spill are taken care of.
743 if (isRegToSpill(Reg))
744 continue;
745
746 // Add all of VNI's live range to StackInt.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000747 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
748 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000749
750 // Find all spills and copies of VNI.
751 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
752 MachineInstr *MI = UI.skipInstruction();) {
753 if (!MI->isCopy() && !MI->getDesc().mayStore())
754 continue;
755 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000756 if (LI->getVNInfoAt(Idx) != VNI)
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000757 continue;
758
759 // Follow sibling copies down the dominator tree.
760 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
761 if (isSibling(DstReg)) {
762 LiveInterval &DstLI = LIS.getInterval(DstReg);
763 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
764 assert(DstVNI && "Missing defined value");
765 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000766 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000767 }
768 continue;
769 }
770
771 // Erase spills.
772 int FI;
773 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
774 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
775 // eliminateDeadDefs won't normally remove stores, so switch opcode.
776 MI->setDesc(TII.get(TargetOpcode::KILL));
777 DeadDefs.push_back(MI);
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000778 ++NumSpillsRemoved;
779 --NumSpills;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000780 }
781 }
782 } while (!WorkList.empty());
783}
784
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000785
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000786//===----------------------------------------------------------------------===//
787// Rematerialization
788//===----------------------------------------------------------------------===//
789
790/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
791/// instruction cannot be eliminated. See through snippet copies
792void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
793 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
794 WorkList.push_back(std::make_pair(LI, VNI));
795 do {
796 tie(LI, VNI) = WorkList.pop_back_val();
797 if (!UsedValues.insert(VNI))
798 continue;
799
800 if (VNI->isPHIDef()) {
801 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
802 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
803 PE = MBB->pred_end(); PI != PE; ++PI) {
804 VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
805 if (PVNI)
806 WorkList.push_back(std::make_pair(LI, PVNI));
807 }
808 continue;
809 }
810
811 // Follow snippet copies.
812 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
813 if (!SnippetCopies.count(MI))
814 continue;
815 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
816 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
817 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex());
818 assert(SnipVNI && "Snippet undefined before copy");
819 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
820 } while (!WorkList.empty());
821}
822
823/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
824bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
825 MachineBasicBlock::iterator MI) {
826 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
Jakob Stoklund Olesen79413502011-07-18 05:31:59 +0000827 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000828
829 if (!ParentVNI) {
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000830 DEBUG(dbgs() << "\tadding <undef> flags: ");
831 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
832 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000833 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000834 MO.setIsUndef();
835 }
836 DEBUG(dbgs() << UseIdx << '\t' << *MI);
837 return true;
838 }
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000839
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000840 if (SnippetCopies.count(MI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000841 return false;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000842
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000843 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
844 LiveRangeEdit::Remat RM(ParentVNI);
845 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
846 if (SibI != SibValues.end())
847 RM.OrigMI = SibI->second.DefMI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000848 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000849 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000850 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
851 return false;
852 }
853
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000854 // If the instruction also writes VirtReg.reg, it had better not require the
855 // same register for uses and defs.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000856 bool Reads, Writes;
857 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000858 tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000859 if (Writes) {
860 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
861 MachineOperand &MO = MI->getOperand(Ops[i]);
862 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000863 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000864 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
865 return false;
866 }
867 }
868 }
869
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000870 // Before rematerializing into a register for a single instruction, try to
871 // fold a load into the instruction. That avoids allocating a new register.
872 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
873 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000874 Edit->markRematerialized(RM.ParentVNI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000875 ++NumFoldedLoads;
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000876 return true;
877 }
878
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000879 // Alocate a new register for the remat.
Jakob Stoklund Olesen312babc2011-03-31 03:54:44 +0000880 LiveInterval &NewLI = Edit->createFrom(Original, LIS, VRM);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000881 NewLI.markNotSpillable();
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000882
883 // Finally we can rematerialize OrigMI before MI.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000884 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
885 LIS, TII, TRI);
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000886 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000887 << *LIS.getInstructionFromIndex(DefIdx));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000888
889 // Replace operands
890 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
891 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000892 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000893 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000894 MO.setIsKill();
895 }
896 }
897 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
898
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000899 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000900 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000901 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000902 ++NumRemats;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000903 return true;
904}
905
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000906/// reMaterializeAll - Try to rematerialize as many uses as possible,
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000907/// and trim the live ranges after.
908void InlineSpiller::reMaterializeAll() {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000909 // analyzeSiblingValues has already tested all relevant defining instructions.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000910 if (!Edit->anyRematerializable(LIS, TII, AA))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000911 return;
912
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000913 UsedValues.clear();
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000914
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000915 // Try to remat before all uses of snippets.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000916 bool anyRemat = false;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000917 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
918 unsigned Reg = RegsToSpill[i];
919 LiveInterval &LI = LIS.getInterval(Reg);
920 for (MachineRegisterInfo::use_nodbg_iterator
921 RI = MRI.use_nodbg_begin(Reg);
922 MachineInstr *MI = RI.skipInstruction();)
923 anyRemat |= reMaterializeFor(LI, MI);
924 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000925 if (!anyRemat)
926 return;
927
928 // Remove any values that were completely rematted.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000929 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
930 unsigned Reg = RegsToSpill[i];
931 LiveInterval &LI = LIS.getInterval(Reg);
932 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
933 I != E; ++I) {
934 VNInfo *VNI = *I;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000935 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000936 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000937 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
938 MI->addRegisterDead(Reg, &TRI);
939 if (!MI->allDefsAreDead())
940 continue;
941 DEBUG(dbgs() << "All defs dead: " << *MI);
942 DeadDefs.push_back(MI);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000943 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000944 }
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000945
946 // Eliminate dead code after remat. Note that some snippet copies may be
947 // deleted here.
948 if (DeadDefs.empty())
949 return;
950 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
951 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
952
953 // Get rid of deleted and empty intervals.
954 for (unsigned i = RegsToSpill.size(); i != 0; --i) {
955 unsigned Reg = RegsToSpill[i-1];
956 if (!LIS.hasInterval(Reg)) {
957 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
958 continue;
959 }
960 LiveInterval &LI = LIS.getInterval(Reg);
961 if (!LI.empty())
962 continue;
963 Edit->eraseVirtReg(Reg, LIS);
964 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
965 }
966 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000967}
968
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000969
970//===----------------------------------------------------------------------===//
971// Spilling
972//===----------------------------------------------------------------------===//
973
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000974/// If MI is a load or store of StackSlot, it can be removed.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000975bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000976 int FI = 0;
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000977 unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI);
978 bool IsLoad = InstrReg;
979 if (!IsLoad)
980 InstrReg = TII.isStoreToStackSlot(MI, FI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000981
982 // We have a stack access. Is it the right register and slot?
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000983 if (InstrReg != Reg || FI != StackSlot)
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000984 return false;
985
986 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000987 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000988 MI->eraseFromParent();
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000989
990 if (IsLoad) {
991 ++NumReloadsRemoved;
992 --NumReloads;
993 } else {
994 ++NumSpillsRemoved;
995 --NumSpills;
996 }
997
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000998 return true;
999}
1000
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001001/// foldMemoryOperand - Try folding stack slot references in Ops into MI.
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001002/// @param MI Instruction using or defining the current register.
Jakob Stoklund Olesen39048252010-12-18 03:28:32 +00001003/// @param Ops Operand indices from readsWritesVirtualRegister().
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001004/// @param LoadMI Load instruction to use instead of stack slot when non-null.
1005/// @return True on success, and MI will be erased.
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001006bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001007 const SmallVectorImpl<unsigned> &Ops,
1008 MachineInstr *LoadMI) {
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001009 bool WasCopy = MI->isCopy();
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001010 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1011 // operands.
1012 SmallVector<unsigned, 8> FoldOps;
1013 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1014 unsigned Idx = Ops[i];
1015 MachineOperand &MO = MI->getOperand(Idx);
1016 if (MO.isImplicit())
1017 continue;
1018 // FIXME: Teach targets to deal with subregs.
1019 if (MO.getSubReg())
1020 return false;
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +00001021 // We cannot fold a load instruction into a def.
1022 if (LoadMI && MO.isDef())
1023 return false;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001024 // Tied use operands should not be passed to foldMemoryOperand.
1025 if (!MI->isRegTiedToDefOperand(Idx))
1026 FoldOps.push_back(Idx);
1027 }
1028
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001029 MachineInstr *FoldMI =
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001030 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
1031 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001032 if (!FoldMI)
1033 return false;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001034 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001035 if (!LoadMI)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001036 VRM.addSpillSlotUse(StackSlot, FoldMI);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001037 MI->eraseFromParent();
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001038 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001039 if (!WasCopy)
1040 ++NumFolded;
1041 else if (Ops.front() == 0)
1042 ++NumSpills;
1043 else
1044 ++NumReloads;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001045 return true;
1046}
1047
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001048/// insertReload - Insert a reload of NewLI.reg before MI.
1049void InlineSpiller::insertReload(LiveInterval &NewLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001050 SlotIndex Idx,
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001051 MachineBasicBlock::iterator MI) {
1052 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001053 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
1054 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001055 --MI; // Point to load instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001056 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
1057 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001058 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
Lang Hames6e2968c2010-09-25 12:04:16 +00001059 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001060 LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001061 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001062 ++NumReloads;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001063}
1064
1065/// insertSpill - Insert a spill of NewLI.reg after MI.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001066void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001067 SlotIndex Idx, MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001068 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001069 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
1070 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001071 --MI; // Point to store instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001072 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
1073 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001074 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001075 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001076 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001077 ++NumSpills;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001078}
1079
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001080/// spillAroundUses - insert spill code around each use of Reg.
1081void InlineSpiller::spillAroundUses(unsigned Reg) {
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001082 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001083 LiveInterval &OldLI = LIS.getInterval(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001084
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001085 // Iterate over instructions using Reg.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001086 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001087 MachineInstr *MI = RI.skipInstruction();) {
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001088
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +00001089 // Debug values are not allowed to affect codegen.
1090 if (MI->isDebugValue()) {
1091 // Modify DBG_VALUE now that the value is in a spill slot.
1092 uint64_t Offset = MI->getOperand(1).getImm();
1093 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
1094 DebugLoc DL = MI->getDebugLoc();
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001095 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +00001096 Offset, MDPtr, DL)) {
1097 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1098 MachineBasicBlock *MBB = MI->getParent();
1099 MBB->insert(MBB->erase(MI), NewDV);
1100 } else {
1101 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
1102 MI->eraseFromParent();
1103 }
1104 continue;
1105 }
1106
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001107 // Ignore copies to/from snippets. We'll delete them.
1108 if (SnippetCopies.count(MI))
1109 continue;
1110
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001111 // Stack slot accesses may coalesce away.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001112 if (coalesceStackAccess(MI, Reg))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001113 continue;
1114
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001115 // Analyze instruction.
1116 bool Reads, Writes;
1117 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001118 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001119
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001120 // Find the slot index where this instruction reads and writes OldLI.
1121 // This is usually the def slot, except for tied early clobbers.
1122 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
1123 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getUseIndex()))
1124 if (SlotIndex::isSameInstr(Idx, VNI->def))
1125 Idx = VNI->def;
1126
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001127 // Check for a sibling copy.
1128 unsigned SibReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001129 if (SibReg && isSibling(SibReg)) {
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001130 // This may actually be a copy between snippets.
1131 if (isRegToSpill(SibReg)) {
1132 DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1133 SnippetCopies.insert(MI);
1134 continue;
1135 }
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001136 if (Writes) {
1137 // Hoist the spill of a sib-reg copy.
1138 if (hoistSpill(OldLI, MI)) {
1139 // This COPY is now dead, the value is already in the stack slot.
1140 MI->getOperand(0).setIsDead();
1141 DeadDefs.push_back(MI);
1142 continue;
1143 }
1144 } else {
1145 // This is a reload for a sib-reg copy. Drop spills downstream.
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001146 LiveInterval &SibLI = LIS.getInterval(SibReg);
1147 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1148 // The COPY will fold to a reload below.
1149 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001150 }
1151
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +00001152 // Attempt to fold memory ops.
1153 if (foldMemoryOperand(MI, Ops))
1154 continue;
1155
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001156 // Allocate interval around instruction.
1157 // FIXME: Infer regclass from instruction alone.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001158 LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001159 NewLI.markNotSpillable();
1160
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +00001161 if (Reads)
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001162 insertReload(NewLI, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001163
1164 // Rewrite instruction operands.
1165 bool hasLiveDef = false;
1166 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1167 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +00001168 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001169 if (MO.isUse()) {
1170 if (!MI->isRegTiedToDefOperand(Ops[i]))
1171 MO.setIsKill();
1172 } else {
1173 if (!MO.isDead())
1174 hasLiveDef = true;
1175 }
1176 }
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001177 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001178
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001179 // FIXME: Use a second vreg if instruction has no tied ops.
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001180 if (Writes && hasLiveDef)
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001181 insertSpill(NewLI, OldLI, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001182
1183 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001184 }
1185}
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001186
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001187/// spillAll - Spill all registers remaining after rematerialization.
1188void InlineSpiller::spillAll() {
1189 // Update LiveStacks now that we are committed to spilling.
1190 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1191 StackSlot = VRM.assignVirt2StackSlot(Original);
1192 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1193 StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
1194 } else
1195 StackInt = &LSS.getInterval(StackSlot);
1196
1197 if (Original != Edit->getReg())
1198 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1199
1200 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1201 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1202 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
1203 StackInt->getValNumInfo(0));
1204 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1205
1206 // Spill around uses of all RegsToSpill.
1207 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1208 spillAroundUses(RegsToSpill[i]);
1209
1210 // Hoisted spills may cause dead code.
1211 if (!DeadDefs.empty()) {
1212 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1213 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
1214 }
1215
1216 // Finally delete the SnippetCopies.
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001217 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1218 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(RegsToSpill[i]);
1219 MachineInstr *MI = RI.skipInstruction();) {
1220 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1221 // FIXME: Do this with a LiveRangeEdit callback.
1222 VRM.RemoveMachineInstrFromMaps(MI);
1223 LIS.RemoveMachineInstrFromMaps(MI);
1224 MI->eraseFromParent();
1225 }
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001226 }
1227
1228 // Delete all spilled registers.
1229 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1230 Edit->eraseVirtReg(RegsToSpill[i], LIS);
1231}
1232
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001233void InlineSpiller::spill(LiveRangeEdit &edit) {
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001234 ++NumSpilledRanges;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001235 Edit = &edit;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001236 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1237 && "Trying to spill a stack slot.");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001238 // Share a stack slot among all descendants of Original.
1239 Original = VRM.getOriginal(edit.getReg());
1240 StackSlot = VRM.getStackSlot(Original);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001241 StackInt = 0;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001242
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001243 DEBUG(dbgs() << "Inline spilling "
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001244 << MRI.getRegClass(edit.getReg())->getName()
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001245 << ':' << edit.getParent() << "\nFrom original "
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001246 << LIS.getInterval(Original) << '\n');
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001247 assert(edit.getParent().isSpillable() &&
1248 "Attempting to spill already spilled value.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001249 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001250
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001251 collectRegsToSpill();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001252 analyzeSiblingValues();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001253 reMaterializeAll();
1254
1255 // Remat may handle everything.
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001256 if (!RegsToSpill.empty())
1257 spillAll();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001258
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001259 Edit->calculateRegClassAndHint(MF, LIS, Loops);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001260}