blob: dd00d77c54c33a5711870b400d3036b84580f1b6 [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"
Benjamin Kramer2db14ba2013-05-23 15:42:57 +000017#include "llvm/ADT/SetVector.h"
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000018#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000019#include "llvm/ADT/TinyPtrVector.h"
Jakob Stoklund Olesene93198a2010-11-10 23:55:56 +000020#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000021#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000022#include "llvm/CodeGen/LiveRangeEdit.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"
David Blaikie6d9dbd52013-06-16 20:34:15 +000027#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000028#include "llvm/CodeGen/MachineInstrBundle.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000029#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000031#include "llvm/CodeGen/VirtRegMap.h"
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +000032#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000037
38using namespace llvm;
39
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000040STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000041STATISTIC(NumSnippets, "Number of spilled snippets");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000042STATISTIC(NumSpills, "Number of spills inserted");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000043STATISTIC(NumSpillsRemoved, "Number of spills removed");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000044STATISTIC(NumReloads, "Number of reloads inserted");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000045STATISTIC(NumReloadsRemoved, "Number of reloads removed");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000046STATISTIC(NumFolded, "Number of folded stack accesses");
47STATISTIC(NumFoldedLoads, "Number of folded loads");
48STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000049STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads");
50STATISTIC(NumHoists, "Number of hoisted spills");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000051
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +000052static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
53 cl::desc("Disable inline spill hoisting"));
54
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000055namespace {
56class InlineSpiller : public Spiller {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000057 MachineFunction &MF;
58 LiveIntervals &LIS;
59 LiveStacks &LSS;
60 AliasAnalysis *AA;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000061 MachineDominatorTree &MDT;
62 MachineLoopInfo &Loops;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000063 VirtRegMap &VRM;
64 MachineFrameInfo &MFI;
65 MachineRegisterInfo &MRI;
66 const TargetInstrInfo &TII;
67 const TargetRegisterInfo &TRI;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +000068
69 // Variables that are valid during spill(), but used by multiple methods.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000070 LiveRangeEdit *Edit;
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +000071 LiveInterval *StackInt;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000072 int StackSlot;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000073 unsigned Original;
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000074
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000075 // All registers to spill to StackSlot, including the main register.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +000076 SmallVector<unsigned, 8> RegsToSpill;
77
78 // All COPY instructions to/from snippets.
79 // They are ignored since both operands refer to the same stack slot.
80 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
81
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +000082 // Values that failed to remat at some point.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000083 SmallPtrSet<VNInfo*, 8> UsedValues;
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +000084
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000085public:
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000086 // Information about a value that was defined by a copy from a sibling
87 // register.
88 struct SibValueInfo {
89 // True when all reaching defs were reloads: No spill is necessary.
90 bool AllDefsAreReloads;
91
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000092 // True when value is defined by an original PHI not from splitting.
93 bool DefByOrigPHI;
94
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +000095 // True when the COPY defining this value killed its source.
96 bool KillsSource;
97
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000098 // The preferred register to spill.
99 unsigned SpillReg;
100
101 // The value of SpillReg that should be spilled.
102 VNInfo *SpillVNI;
103
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000104 // The block where SpillVNI should be spilled. Currently, this must be the
105 // block containing SpillVNI->def.
106 MachineBasicBlock *SpillMBB;
107
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000108 // A defining instruction that is not a sibling copy or a reload, or NULL.
109 // This can be used as a template for rematerialization.
110 MachineInstr *DefMI;
111
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000112 // List of values that depend on this one. These values are actually the
113 // same, but live range splitting has placed them in different registers,
114 // or SSA update needed to insert PHI-defs to preserve SSA form. This is
115 // copies of the current value and phi-kills. Usually only phi-kills cause
116 // more than one dependent value.
117 TinyPtrVector<VNInfo*> Deps;
118
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000119 SibValueInfo(unsigned Reg, VNInfo *VNI)
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000120 : AllDefsAreReloads(true), DefByOrigPHI(false), KillsSource(false),
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000121 SpillReg(Reg), SpillVNI(VNI), SpillMBB(0), DefMI(0) {}
122
123 // Returns true when a def has been found.
124 bool hasDef() const { return DefByOrigPHI || DefMI; }
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000125 };
126
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000127private:
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000128 // Values in RegsToSpill defined by sibling copies.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000129 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
130 SibValueMap SibValues;
131
132 // Dead defs generated during spilling.
133 SmallVector<MachineInstr*, 8> DeadDefs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000134
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000135 ~InlineSpiller() {}
136
137public:
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000138 InlineSpiller(MachineFunctionPass &pass,
139 MachineFunction &mf,
140 VirtRegMap &vrm)
Benjamin Kramer95a9d932012-06-06 19:47:08 +0000141 : MF(mf),
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000142 LIS(pass.getAnalysis<LiveIntervals>()),
143 LSS(pass.getAnalysis<LiveStacks>()),
144 AA(&pass.getAnalysis<AliasAnalysis>()),
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000145 MDT(pass.getAnalysis<MachineDominatorTree>()),
146 Loops(pass.getAnalysis<MachineLoopInfo>()),
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000147 VRM(vrm),
148 MFI(*mf.getFrameInfo()),
149 MRI(mf.getRegInfo()),
150 TII(*mf.getTarget().getInstrInfo()),
151 TRI(*mf.getTarget().getRegisterInfo()) {}
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000152
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000153 void spill(LiveRangeEdit &);
154
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000155private:
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000156 bool isSnippet(const LiveInterval &SnipLI);
157 void collectRegsToSpill();
158
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000159 bool isRegToSpill(unsigned Reg) {
160 return std::find(RegsToSpill.begin(),
161 RegsToSpill.end(), Reg) != RegsToSpill.end();
162 }
163
164 bool isSibling(unsigned Reg);
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000165 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000166 void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = 0);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000167 void analyzeSiblingValues();
168
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000169 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000170 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000171
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000172 void markValueUsed(LiveInterval*, VNInfo*);
173 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000174 void reMaterializeAll();
175
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000176 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000177 bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> >,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000178 MachineInstr *LoadMI = 0);
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000179 void insertReload(LiveInterval &NewLI, SlotIndex,
180 MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000181 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000182 SlotIndex, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000183
184 void spillAroundUses(unsigned Reg);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000185 void spillAll();
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000186};
187}
188
189namespace llvm {
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000190Spiller *createInlineSpiller(MachineFunctionPass &pass,
191 MachineFunction &mf,
192 VirtRegMap &vrm) {
193 return new InlineSpiller(pass, mf, vrm);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000194}
195}
196
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000197//===----------------------------------------------------------------------===//
198// Snippets
199//===----------------------------------------------------------------------===//
200
201// When spilling a virtual register, we also spill any snippets it is connected
202// to. The snippets are small live ranges that only have a single real use,
203// leftovers from live range splitting. Spilling them enables memory operand
204// folding or tightens the live range around the single use.
205//
206// This minimizes register pressure and maximizes the store-to-load distance for
207// spill slots which can be important in tight loops.
208
209/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
210/// otherwise return 0.
211static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
Rafael Espindolacfe52542011-06-30 21:15:52 +0000212 if (!MI->isFullCopy())
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000213 return 0;
214 if (MI->getOperand(0).getReg() == Reg)
215 return MI->getOperand(1).getReg();
216 if (MI->getOperand(1).getReg() == Reg)
217 return MI->getOperand(0).getReg();
218 return 0;
219}
220
221/// isSnippet - Identify if a live interval is a snippet that should be spilled.
222/// It is assumed that SnipLI is a virtual register with the same original as
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000223/// Edit->getReg().
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000224bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000225 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000226
227 // A snippet is a tiny live range with only a single instruction using it
228 // besides copies to/from Reg or spills/fills. We accept:
229 //
230 // %snip = COPY %Reg / FILL fi#
231 // %snip = USE %snip
232 // %Reg = COPY %snip / SPILL %snip, fi#
233 //
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000234 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000235 return false;
236
237 MachineInstr *UseMI = 0;
238
239 // Check that all uses satisfy our criteria.
240 for (MachineRegisterInfo::reg_nodbg_iterator
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000241 RI = MRI.reg_nodbg_begin(SnipLI.reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000242 MachineInstr *MI = RI.skipInstruction();) {
243
244 // Allow copies to/from Reg.
245 if (isFullCopyOf(MI, Reg))
246 continue;
247
248 // Allow stack slot loads.
249 int FI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000250 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000251 continue;
252
253 // Allow stack slot stores.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000254 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000255 continue;
256
257 // Allow a single additional instruction.
258 if (UseMI && MI != UseMI)
259 return false;
260 UseMI = MI;
261 }
262 return true;
263}
264
265/// collectRegsToSpill - Collect live range snippets that only have a single
266/// real use.
267void InlineSpiller::collectRegsToSpill() {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000268 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000269
270 // Main register always spills.
271 RegsToSpill.assign(1, Reg);
272 SnippetCopies.clear();
273
274 // Snippets all have the same original, so there can't be any for an original
275 // register.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000276 if (Original == Reg)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000277 return;
278
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000279 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000280 MachineInstr *MI = RI.skipInstruction();) {
281 unsigned SnipReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000282 if (!isSibling(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000283 continue;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000284 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000285 if (!isSnippet(SnipLI))
286 continue;
287 SnippetCopies.insert(MI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000288 if (isRegToSpill(SnipReg))
289 continue;
290 RegsToSpill.push_back(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000291 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000292 ++NumSnippets;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000293 }
294}
295
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000296
297//===----------------------------------------------------------------------===//
298// Sibling Values
299//===----------------------------------------------------------------------===//
300
301// After live range splitting, some values to be spilled may be defined by
302// copies from sibling registers. We trace the sibling copies back to the
303// original value if it still exists. We need it for rematerialization.
304//
305// Even when the value can't be rematerialized, we still want to determine if
306// the value has already been spilled, or we may want to hoist the spill from a
307// loop.
308
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000309bool InlineSpiller::isSibling(unsigned Reg) {
310 return TargetRegisterInfo::isVirtualRegister(Reg) &&
311 VRM.getOriginal(Reg) == Original;
312}
313
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000314#ifndef NDEBUG
315static raw_ostream &operator<<(raw_ostream &OS,
316 const InlineSpiller::SibValueInfo &SVI) {
317 OS << "spill " << PrintReg(SVI.SpillReg) << ':'
318 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
319 if (SVI.SpillMBB)
320 OS << " in BB#" << SVI.SpillMBB->getNumber();
321 if (SVI.AllDefsAreReloads)
322 OS << " all-reloads";
323 if (SVI.DefByOrigPHI)
324 OS << " orig-phi";
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000325 if (SVI.KillsSource)
326 OS << " kill";
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000327 OS << " deps[";
328 for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i)
329 OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def;
330 OS << " ]";
331 if (SVI.DefMI)
332 OS << " def: " << *SVI.DefMI;
333 else
334 OS << '\n';
335 return OS;
336}
337#endif
338
339/// propagateSiblingValue - Propagate the value in SVI to dependents if it is
340/// known. Otherwise remember the dependency for later.
341///
Benjamin Kramer2db14ba2013-05-23 15:42:57 +0000342/// @param SVIIter SibValues entry to propagate.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000343/// @param VNI Dependent value, or NULL to propagate to all saved dependents.
Benjamin Kramer2db14ba2013-05-23 15:42:57 +0000344void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVIIter,
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000345 VNInfo *VNI) {
Benjamin Kramer2db14ba2013-05-23 15:42:57 +0000346 SibValueMap::value_type *SVI = &*SVIIter;
347
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000348 // When VNI is non-NULL, add it to SVI's deps, and only propagate to that.
349 TinyPtrVector<VNInfo*> FirstDeps;
350 if (VNI) {
351 FirstDeps.push_back(VNI);
352 SVI->second.Deps.push_back(VNI);
353 }
354
355 // Has the value been completely determined yet? If not, defer propagation.
356 if (!SVI->second.hasDef())
357 return;
358
Benjamin Kramer2db14ba2013-05-23 15:42:57 +0000359 // Work list of values to propagate.
360 SmallSetVector<SibValueMap::value_type *, 8> WorkList;
361 WorkList.insert(SVI);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000362
363 do {
364 SVI = WorkList.pop_back_val();
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000365 TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps;
366 VNI = 0;
367
368 SibValueInfo &SV = SVI->second;
369 if (!SV.SpillMBB)
370 SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
371
372 DEBUG(dbgs() << " prop to " << Deps->size() << ": "
373 << SVI->first->id << '@' << SVI->first->def << ":\t" << SV);
374
375 assert(SV.hasDef() && "Propagating undefined value");
376
377 // Should this value be propagated as a preferred spill candidate? We don't
378 // propagate values of registers that are about to spill.
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +0000379 bool PropSpill = !DisableHoisting && !isRegToSpill(SV.SpillReg);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000380 unsigned SpillDepth = ~0u;
381
382 for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(),
383 DepE = Deps->end(); DepI != DepE; ++DepI) {
384 SibValueMap::iterator DepSVI = SibValues.find(*DepI);
385 assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
386 SibValueInfo &DepSV = DepSVI->second;
387 if (!DepSV.SpillMBB)
388 DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
389
390 bool Changed = false;
391
392 // Propagate defining instruction.
393 if (!DepSV.hasDef()) {
394 Changed = true;
395 DepSV.DefMI = SV.DefMI;
396 DepSV.DefByOrigPHI = SV.DefByOrigPHI;
397 }
398
399 // Propagate AllDefsAreReloads. For PHI values, this computes an AND of
400 // all predecessors.
401 if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
402 Changed = true;
403 DepSV.AllDefsAreReloads = false;
404 }
405
406 // Propagate best spill value.
407 if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
408 if (SV.SpillMBB == DepSV.SpillMBB) {
409 // DepSV is in the same block. Hoist when dominated.
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000410 if (DepSV.KillsSource && SV.SpillVNI->def < DepSV.SpillVNI->def) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000411 // This is an alternative def earlier in the same MBB.
412 // Hoist the spill as far as possible in SpillMBB. This can ease
413 // register pressure:
414 //
415 // x = def
416 // y = use x
417 // s = copy x
418 //
419 // Hoisting the spill of s to immediately after the def removes the
420 // interference between x and y:
421 //
422 // x = def
423 // spill x
424 // y = use x<kill>
425 //
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000426 // This hoist only helps when the DepSV copy kills its source.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000427 Changed = true;
428 DepSV.SpillReg = SV.SpillReg;
429 DepSV.SpillVNI = SV.SpillVNI;
430 DepSV.SpillMBB = SV.SpillMBB;
431 }
432 } else {
433 // DepSV is in a different block.
434 if (SpillDepth == ~0u)
435 SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
436
437 // Also hoist spills to blocks with smaller loop depth, but make sure
438 // that the new value dominates. Non-phi dependents are always
439 // dominated, phis need checking.
440 if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
441 (!DepSVI->first->isPHIDef() ||
442 MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
443 Changed = true;
444 DepSV.SpillReg = SV.SpillReg;
445 DepSV.SpillVNI = SV.SpillVNI;
446 DepSV.SpillMBB = SV.SpillMBB;
447 }
448 }
449 }
450
451 if (!Changed)
452 continue;
453
454 // Something changed in DepSVI. Propagate to dependents.
Benjamin Kramer2db14ba2013-05-23 15:42:57 +0000455 WorkList.insert(&*DepSVI);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000456
457 DEBUG(dbgs() << " update " << DepSVI->first->id << '@'
458 << DepSVI->first->def << " to:\t" << DepSV);
459 }
460 } while (!WorkList.empty());
461}
462
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000463/// traceSiblingValue - Trace a value that is about to be spilled back to the
464/// real defining instructions by looking through sibling copies. Always stay
465/// within the range of OrigVNI so the registers are known to carry the same
466/// value.
467///
468/// Determine if the value is defined by all reloads, so spilling isn't
469/// necessary - the value is already in the stack slot.
470///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000471/// Return a defining instruction that may be a candidate for rematerialization.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000472///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000473MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
474 VNInfo *OrigVNI) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000475 // Check if a cached value already exists.
476 SibValueMap::iterator SVI;
477 bool Inserted;
478 tie(SVI, Inserted) =
479 SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
480 if (!Inserted) {
481 DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
482 << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
483 return SVI->second.DefMI;
484 }
485
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000486 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
487 << UseVNI->id << '@' << UseVNI->def << '\n');
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000488
489 // List of (Reg, VNI) that have been inserted into SibValues, but need to be
490 // processed.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000491 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000492 WorkList.push_back(std::make_pair(UseReg, UseVNI));
493
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000494 do {
495 unsigned Reg;
496 VNInfo *VNI;
497 tie(Reg, VNI) = WorkList.pop_back_val();
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000498 DEBUG(dbgs() << " " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
499 << ":\t");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000500
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000501 // First check if this value has already been computed.
502 SVI = SibValues.find(VNI);
503 assert(SVI != SibValues.end() && "Missing SibValues entry");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000504
505 // Trace through PHI-defs created by live range splitting.
506 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000507 // Stop at original PHIs. We don't know the value at the predecessors.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000508 if (VNI->def == OrigVNI->def) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000509 DEBUG(dbgs() << "orig phi value\n");
510 SVI->second.DefByOrigPHI = true;
511 SVI->second.AllDefsAreReloads = false;
512 propagateSiblingValue(SVI);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000513 continue;
514 }
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000515
516 // This is a PHI inserted by live range splitting. We could trace the
517 // live-out value from predecessor blocks, but that search can be very
518 // expensive if there are many predecessors and many more PHIs as
519 // generated by tail-dup when it sees an indirectbr. Instead, look at
520 // all the non-PHI defs that have the same value as OrigVNI. They must
521 // jointly dominate VNI->def. This is not optimal since VNI may actually
522 // be jointly dominated by a smaller subset of defs, so there is a change
523 // we will miss a AllDefsAreReloads optimization.
524
525 // Separate all values dominated by OrigVNI into PHIs and non-PHIs.
526 SmallVector<VNInfo*, 8> PHIs, NonPHIs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000527 LiveInterval &LI = LIS.getInterval(Reg);
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000528 LiveInterval &OrigLI = LIS.getInterval(Original);
529
530 for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end();
531 VI != VE; ++VI) {
532 VNInfo *VNI2 = *VI;
533 if (VNI2->isUnused())
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000534 continue;
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000535 if (!OrigLI.containsOneValue() &&
536 OrigLI.getVNInfoAt(VNI2->def) != OrigVNI)
537 continue;
538 if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def)
539 PHIs.push_back(VNI2);
540 else
541 NonPHIs.push_back(VNI2);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000542 }
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000543 DEBUG(dbgs() << "split phi value, checking " << PHIs.size()
544 << " phi-defs, and " << NonPHIs.size()
545 << " non-phi/orig defs\n");
546
547 // Create entries for all the PHIs. Don't add them to the worklist, we
548 // are processing all of them in one go here.
549 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
550 SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i])));
551
552 // Add every PHI as a dependent of all the non-PHIs.
553 for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) {
554 VNInfo *NonPHI = NonPHIs[i];
555 // Known value? Try an insertion.
556 tie(SVI, Inserted) =
557 SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI)));
558 // Add all the PHIs as dependents of NonPHI.
559 for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi)
560 SVI->second.Deps.push_back(PHIs[pi]);
561 // This is the first time we see NonPHI, add it to the worklist.
562 if (Inserted)
563 WorkList.push_back(std::make_pair(Reg, NonPHI));
564 else
565 // Propagate to all inserted PHIs, not just VNI.
566 propagateSiblingValue(SVI);
567 }
568
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000569 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000570 continue;
571 }
572
573 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
574 assert(MI && "Missing def");
575
576 // Trace through sibling copies.
577 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000578 if (isSibling(SrcReg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000579 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
Jakob Stoklund Olesen92a05fa2012-05-20 02:44:33 +0000580 LiveRangeQuery SrcQ(SrcLI, VNI->def);
581 assert(SrcQ.valueIn() && "Copy from non-existing value");
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000582 // Check if this COPY kills its source.
Jakob Stoklund Olesen92a05fa2012-05-20 02:44:33 +0000583 SVI->second.KillsSource = SrcQ.isKill();
584 VNInfo *SrcVNI = SrcQ.valueIn();
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000585 DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000586 << SrcVNI->id << '@' << SrcVNI->def
587 << " kill=" << unsigned(SVI->second.KillsSource) << '\n');
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000588 // Known sibling source value? Try an insertion.
589 tie(SVI, Inserted) = SibValues.insert(std::make_pair(SrcVNI,
590 SibValueInfo(SrcReg, SrcVNI)));
591 // This is the first time we see Src, add it to the worklist.
592 if (Inserted)
593 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
594 propagateSiblingValue(SVI, VNI);
595 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000596 continue;
597 }
598 }
599
600 // Track reachable reloads.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000601 SVI->second.DefMI = MI;
602 SVI->second.SpillMBB = MI->getParent();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000603 int FI;
604 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000605 DEBUG(dbgs() << "reload\n");
606 propagateSiblingValue(SVI);
607 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000608 continue;
609 }
610
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000611 // Potential remat candidate.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000612 DEBUG(dbgs() << "def " << *MI);
613 SVI->second.AllDefsAreReloads = false;
614 propagateSiblingValue(SVI);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000615 } while (!WorkList.empty());
616
Logan Chiene2ac5522012-09-01 12:11:41 +0000617 // Look up the value we were looking for. We already did this lookup at the
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000618 // top of the function, but SibValues may have been invalidated.
619 SVI = SibValues.find(UseVNI);
620 assert(SVI != SibValues.end() && "Didn't compute requested info");
621 DEBUG(dbgs() << " traced to:\t" << SVI->second);
622 return SVI->second.DefMI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000623}
624
625/// analyzeSiblingValues - Trace values defined by sibling copies back to
626/// something that isn't a sibling copy.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000627///
628/// Keep track of values that may be rematerializable.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000629void InlineSpiller::analyzeSiblingValues() {
630 SibValues.clear();
631
632 // No siblings at all?
633 if (Edit->getReg() == Original)
634 return;
635
636 LiveInterval &OrigLI = LIS.getInterval(Original);
637 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
638 unsigned Reg = RegsToSpill[i];
639 LiveInterval &LI = LIS.getInterval(Reg);
640 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
641 VE = LI.vni_end(); VI != VE; ++VI) {
642 VNInfo *VNI = *VI;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000643 if (VNI->isUnused())
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000644 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000645 MachineInstr *DefMI = 0;
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000646 if (!VNI->isPHIDef()) {
647 DefMI = LIS.getInstructionFromIndex(VNI->def);
648 assert(DefMI && "No defining instruction");
649 }
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000650 // Check possible sibling copies.
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000651 if (VNI->isPHIDef() || DefMI->isCopy()) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000652 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
Jakob Stoklund Olesen9693d4c2011-07-05 15:38:41 +0000653 assert(OrigVNI && "Def outside original live range");
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000654 if (OrigVNI->def != VNI->def)
655 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
656 }
Pete Cooper8a06af92012-04-02 22:22:53 +0000657 if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) {
Jakob Stoklund Olesen3b7d9172011-04-20 22:14:20 +0000658 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
659 << VNI->def << " may remat from " << *DefMI);
660 }
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000661 }
662 }
663}
664
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000665/// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
666/// a spill at a better location.
667bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
668 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000669 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
670 assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000671 SibValueMap::iterator I = SibValues.find(VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000672 if (I == SibValues.end())
673 return false;
674
675 const SibValueInfo &SVI = I->second;
676
677 // Let the normal folding code deal with the boring case.
678 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
679 return false;
680
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000681 // SpillReg may have been deleted by remat and DCE.
682 if (!LIS.hasInterval(SVI.SpillReg)) {
683 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
684 SibValues.erase(I);
685 return false;
686 }
687
688 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
689 if (!SibLI.containsValue(SVI.SpillVNI)) {
690 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
691 SibValues.erase(I);
692 return false;
693 }
694
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000695 // Conservatively extend the stack slot range to the range of the original
696 // value. We may be able to do better with stack slot coloring by being more
697 // careful here.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000698 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000699 LiveInterval &OrigLI = LIS.getInterval(Original);
700 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000701 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +0000702 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000703 << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000704
705 // Already spilled everywhere.
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000706 if (SVI.AllDefsAreReloads) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000707 DEBUG(dbgs() << "\tno spill needed: " << SVI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000708 ++NumOmitReloadSpill;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000709 return true;
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000710 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000711 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
712 // any later spills of the same value.
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000713 eliminateRedundantSpills(SibLI, SVI.SpillVNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000714
715 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
716 MachineBasicBlock::iterator MII;
717 if (SVI.SpillVNI->isPHIDef())
718 MII = MBB->SkipPHIsAndLabels(MBB->begin());
719 else {
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000720 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
721 assert(DefMI && "Defining instruction disappeared");
722 MII = DefMI;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000723 ++MII;
724 }
725 // Insert spill without kill flag immediately after def.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000726 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
727 MRI.getRegClass(SVI.SpillReg), &TRI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000728 --MII; // Point to store instruction.
729 LIS.InsertMachineInstrInMaps(MII);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000730 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000731
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000732 ++NumSpills;
733 ++NumHoists;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000734 return true;
735}
736
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000737/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
738/// redundant spills of this value in SLI.reg and sibling copies.
739void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000740 assert(VNI && "Missing value");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000741 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
742 WorkList.push_back(std::make_pair(&SLI, VNI));
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000743 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000744
745 do {
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000746 LiveInterval *LI;
747 tie(LI, VNI) = WorkList.pop_back_val();
748 unsigned Reg = LI->reg;
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000749 DEBUG(dbgs() << "Checking redundant spills for "
750 << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000751
752 // Regs to spill are taken care of.
753 if (isRegToSpill(Reg))
754 continue;
755
756 // Add all of VNI's live range to StackInt.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000757 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
758 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000759
760 // Find all spills and copies of VNI.
761 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
762 MachineInstr *MI = UI.skipInstruction();) {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000763 if (!MI->isCopy() && !MI->mayStore())
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000764 continue;
765 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000766 if (LI->getVNInfoAt(Idx) != VNI)
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000767 continue;
768
769 // Follow sibling copies down the dominator tree.
770 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
771 if (isSibling(DstReg)) {
772 LiveInterval &DstLI = LIS.getInterval(DstReg);
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000773 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000774 assert(DstVNI && "Missing defined value");
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000775 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000776 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000777 }
778 continue;
779 }
780
781 // Erase spills.
782 int FI;
783 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
784 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
785 // eliminateDeadDefs won't normally remove stores, so switch opcode.
786 MI->setDesc(TII.get(TargetOpcode::KILL));
787 DeadDefs.push_back(MI);
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000788 ++NumSpillsRemoved;
789 --NumSpills;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000790 }
791 }
792 } while (!WorkList.empty());
793}
794
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000795
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000796//===----------------------------------------------------------------------===//
797// Rematerialization
798//===----------------------------------------------------------------------===//
799
800/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
801/// instruction cannot be eliminated. See through snippet copies
802void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
803 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
804 WorkList.push_back(std::make_pair(LI, VNI));
805 do {
806 tie(LI, VNI) = WorkList.pop_back_val();
807 if (!UsedValues.insert(VNI))
808 continue;
809
810 if (VNI->isPHIDef()) {
811 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
812 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
813 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen194eb712011-11-14 01:39:36 +0000814 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000815 if (PVNI)
816 WorkList.push_back(std::make_pair(LI, PVNI));
817 }
818 continue;
819 }
820
821 // Follow snippet copies.
822 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
823 if (!SnippetCopies.count(MI))
824 continue;
825 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
826 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000827 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000828 assert(SnipVNI && "Snippet undefined before copy");
829 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
830 } while (!WorkList.empty());
831}
832
833/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
834bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
835 MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000836 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
Jakob Stoklund Olesen79413502011-07-18 05:31:59 +0000837 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000838
839 if (!ParentVNI) {
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000840 DEBUG(dbgs() << "\tadding <undef> flags: ");
841 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
842 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000843 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000844 MO.setIsUndef();
845 }
846 DEBUG(dbgs() << UseIdx << '\t' << *MI);
847 return true;
848 }
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000849
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000850 if (SnippetCopies.count(MI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000851 return false;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000852
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000853 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
854 LiveRangeEdit::Remat RM(ParentVNI);
855 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
856 if (SibI != SibValues.end())
857 RM.OrigMI = SibI->second.DefMI;
Pete Cooper8a06af92012-04-02 22:22:53 +0000858 if (!Edit->canRematerializeAt(RM, UseIdx, false)) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000859 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000860 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
861 return false;
862 }
863
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000864 // If the instruction also writes VirtReg.reg, it had better not require the
865 // same register for uses and defs.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000866 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
James Molloyb17cf292012-09-12 10:03:31 +0000867 MIBundleOperands::VirtRegInfo RI =
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000868 MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
869 if (RI.Tied) {
870 markValueUsed(&VirtReg, ParentVNI);
871 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
872 return false;
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000873 }
874
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000875 // Before rematerializing into a register for a single instruction, try to
876 // fold a load into the instruction. That avoids allocating a new register.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000877 if (RM.OrigMI->canFoldAsLoad() &&
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000878 foldMemoryOperand(Ops, RM.OrigMI)) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000879 Edit->markRematerialized(RM.ParentVNI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000880 ++NumFoldedLoads;
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000881 return true;
882 }
883
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000884 // Alocate a new register for the remat.
Pete Cooper8a06af92012-04-02 22:22:53 +0000885 LiveInterval &NewLI = Edit->createFrom(Original);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000886 NewLI.markNotSpillable();
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000887
888 // Finally we can rematerialize OrigMI before MI.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000889 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
Pete Cooper8a06af92012-04-02 22:22:53 +0000890 TRI);
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000891 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000892 << *LIS.getInstructionFromIndex(DefIdx));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000893
894 // Replace operands
895 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000896 MachineOperand &MO = MI->getOperand(Ops[i].second);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000897 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000898 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000899 MO.setIsKill();
900 }
901 }
902 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
903
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000904 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000905 NewLI.addRange(LiveRange(DefIdx, UseIdx.getRegSlot(), DefVNI));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000906 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000907 ++NumRemats;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000908 return true;
909}
910
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000911/// reMaterializeAll - Try to rematerialize as many uses as possible,
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000912/// and trim the live ranges after.
913void InlineSpiller::reMaterializeAll() {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000914 // analyzeSiblingValues has already tested all relevant defining instructions.
Pete Cooper8a06af92012-04-02 22:22:53 +0000915 if (!Edit->anyRematerializable(AA))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000916 return;
917
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000918 UsedValues.clear();
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000919
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000920 // Try to remat before all uses of snippets.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000921 bool anyRemat = false;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000922 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
923 unsigned Reg = RegsToSpill[i];
924 LiveInterval &LI = LIS.getInterval(Reg);
925 for (MachineRegisterInfo::use_nodbg_iterator
926 RI = MRI.use_nodbg_begin(Reg);
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000927 MachineInstr *MI = RI.skipBundle();)
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000928 anyRemat |= reMaterializeFor(LI, MI);
929 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000930 if (!anyRemat)
931 return;
932
933 // Remove any values that were completely rematted.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000934 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
935 unsigned Reg = RegsToSpill[i];
936 LiveInterval &LI = LIS.getInterval(Reg);
937 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
938 I != E; ++I) {
939 VNInfo *VNI = *I;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000940 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000941 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000942 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
943 MI->addRegisterDead(Reg, &TRI);
944 if (!MI->allDefsAreDead())
945 continue;
946 DEBUG(dbgs() << "All defs dead: " << *MI);
947 DeadDefs.push_back(MI);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000948 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000949 }
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000950
951 // Eliminate dead code after remat. Note that some snippet copies may be
952 // deleted here.
953 if (DeadDefs.empty())
954 return;
955 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
Pete Cooper8a06af92012-04-02 22:22:53 +0000956 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000957
958 // Get rid of deleted and empty intervals.
Benjamin Kramere210df22013-05-05 11:29:14 +0000959 unsigned ResultPos = 0;
960 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
961 unsigned Reg = RegsToSpill[i];
962 if (!LIS.hasInterval(Reg))
963 continue;
964
965 LiveInterval &LI = LIS.getInterval(Reg);
966 if (LI.empty()) {
967 Edit->eraseVirtReg(Reg);
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000968 continue;
969 }
Benjamin Kramere210df22013-05-05 11:29:14 +0000970
971 RegsToSpill[ResultPos++] = Reg;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000972 }
Benjamin Kramere210df22013-05-05 11:29:14 +0000973 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000974 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000975}
976
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000977
978//===----------------------------------------------------------------------===//
979// Spilling
980//===----------------------------------------------------------------------===//
981
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000982/// If MI is a load or store of StackSlot, it can be removed.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000983bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000984 int FI = 0;
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000985 unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI);
986 bool IsLoad = InstrReg;
987 if (!IsLoad)
988 InstrReg = TII.isStoreToStackSlot(MI, FI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000989
990 // We have a stack access. Is it the right register and slot?
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000991 if (InstrReg != Reg || FI != StackSlot)
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000992 return false;
993
994 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000995 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000996 MI->eraseFromParent();
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000997
998 if (IsLoad) {
999 ++NumReloadsRemoved;
1000 --NumReloads;
1001 } else {
1002 ++NumSpillsRemoved;
1003 --NumSpills;
1004 }
1005
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001006 return true;
1007}
1008
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001009/// foldMemoryOperand - Try folding stack slot references in Ops into their
1010/// instructions.
1011///
1012/// @param Ops Operand indices from analyzeVirtReg().
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001013/// @param LoadMI Load instruction to use instead of stack slot when non-null.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001014/// @return True on success.
1015bool InlineSpiller::
1016foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops,
1017 MachineInstr *LoadMI) {
1018 if (Ops.empty())
1019 return false;
1020 // Don't attempt folding in bundles.
1021 MachineInstr *MI = Ops.front().first;
1022 if (Ops.back().first != MI || MI->isBundled())
1023 return false;
1024
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001025 bool WasCopy = MI->isCopy();
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001026 unsigned ImpReg = 0;
1027
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001028 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1029 // operands.
1030 SmallVector<unsigned, 8> FoldOps;
1031 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001032 unsigned Idx = Ops[i].second;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001033 MachineOperand &MO = MI->getOperand(Idx);
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001034 if (MO.isImplicit()) {
1035 ImpReg = MO.getReg();
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001036 continue;
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001037 }
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001038 // FIXME: Teach targets to deal with subregs.
1039 if (MO.getSubReg())
1040 return false;
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +00001041 // We cannot fold a load instruction into a def.
1042 if (LoadMI && MO.isDef())
1043 return false;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001044 // Tied use operands should not be passed to foldMemoryOperand.
1045 if (!MI->isRegTiedToDefOperand(Idx))
1046 FoldOps.push_back(Idx);
1047 }
1048
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001049 MachineInstr *FoldMI =
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001050 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
1051 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001052 if (!FoldMI)
1053 return false;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001054 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001055 MI->eraseFromParent();
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001056
1057 // TII.foldMemoryOperand may have left some implicit operands on the
1058 // instruction. Strip them.
1059 if (ImpReg)
1060 for (unsigned i = FoldMI->getNumOperands(); i; --i) {
1061 MachineOperand &MO = FoldMI->getOperand(i - 1);
1062 if (!MO.isReg() || !MO.isImplicit())
1063 break;
1064 if (MO.getReg() == ImpReg)
1065 FoldMI->RemoveOperand(i - 1);
1066 }
1067
1068 DEBUG(dbgs() << "\tfolded: " << LIS.getInstructionIndex(FoldMI) << '\t'
1069 << *FoldMI);
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001070 if (!WasCopy)
1071 ++NumFolded;
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001072 else if (Ops.front().second == 0)
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001073 ++NumSpills;
1074 else
1075 ++NumReloads;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001076 return true;
1077}
1078
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001079/// insertReload - Insert a reload of NewLI.reg before MI.
1080void InlineSpiller::insertReload(LiveInterval &NewLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001081 SlotIndex Idx,
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001082 MachineBasicBlock::iterator MI) {
1083 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001084 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
1085 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001086 --MI; // Point to load instruction.
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +00001087 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getRegSlot();
Jakob Stoklund Olesen27982e12012-07-14 18:45:35 +00001088 // Some (out-of-tree) targets have EC reload instructions.
1089 if (MachineOperand *MO = MI->findRegisterDefOperand(NewLI.reg))
1090 if (MO->isEarlyClobber())
1091 LoadIdx = LoadIdx.getRegSlot(true);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001092 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +00001093 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001094 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001095 ++NumReloads;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001096}
1097
1098/// insertSpill - Insert a spill of NewLI.reg after MI.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001099void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001100 SlotIndex Idx, MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001101 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001102 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
1103 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001104 --MI; // Point to store instruction.
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +00001105 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getRegSlot();
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001106 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +00001107 VNInfo *StoreVNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001108 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001109 ++NumSpills;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001110}
1111
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001112/// spillAroundUses - insert spill code around each use of Reg.
1113void InlineSpiller::spillAroundUses(unsigned Reg) {
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001114 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001115 LiveInterval &OldLI = LIS.getInterval(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001116
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001117 // Iterate over instructions using Reg.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001118 for (MachineRegisterInfo::reg_iterator RegI = MRI.reg_begin(Reg);
1119 MachineInstr *MI = RegI.skipBundle();) {
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001120
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +00001121 // Debug values are not allowed to affect codegen.
1122 if (MI->isDebugValue()) {
1123 // Modify DBG_VALUE now that the value is in a spill slot.
1124 uint64_t Offset = MI->getOperand(1).getImm();
1125 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
1126 DebugLoc DL = MI->getDebugLoc();
David Blaikie6d9dbd52013-06-16 20:34:15 +00001127 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1128 MachineBasicBlock *MBB = MI->getParent();
1129 BuildMI(*MBB, MBB->erase(MI), DL, TII.get(TargetOpcode::DBG_VALUE))
1130 .addFrameIndex(StackSlot).addImm(Offset).addMetadata(MDPtr);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +00001131 continue;
1132 }
1133
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001134 // Ignore copies to/from snippets. We'll delete them.
1135 if (SnippetCopies.count(MI))
1136 continue;
1137
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001138 // Stack slot accesses may coalesce away.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001139 if (coalesceStackAccess(MI, Reg))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001140 continue;
1141
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001142 // Analyze instruction.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001143 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
James Molloyb17cf292012-09-12 10:03:31 +00001144 MIBundleOperands::VirtRegInfo RI =
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001145 MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001146
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001147 // Find the slot index where this instruction reads and writes OldLI.
1148 // This is usually the def slot, except for tied early clobbers.
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +00001149 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1150 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001151 if (SlotIndex::isSameInstr(Idx, VNI->def))
1152 Idx = VNI->def;
1153
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001154 // Check for a sibling copy.
1155 unsigned SibReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001156 if (SibReg && isSibling(SibReg)) {
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001157 // This may actually be a copy between snippets.
1158 if (isRegToSpill(SibReg)) {
1159 DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1160 SnippetCopies.insert(MI);
1161 continue;
1162 }
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001163 if (RI.Writes) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001164 // Hoist the spill of a sib-reg copy.
1165 if (hoistSpill(OldLI, MI)) {
1166 // This COPY is now dead, the value is already in the stack slot.
1167 MI->getOperand(0).setIsDead();
1168 DeadDefs.push_back(MI);
1169 continue;
1170 }
1171 } else {
1172 // This is a reload for a sib-reg copy. Drop spills downstream.
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001173 LiveInterval &SibLI = LIS.getInterval(SibReg);
1174 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1175 // The COPY will fold to a reload below.
1176 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001177 }
1178
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +00001179 // Attempt to fold memory ops.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001180 if (foldMemoryOperand(Ops))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +00001181 continue;
1182
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001183 // Allocate interval around instruction.
1184 // FIXME: Infer regclass from instruction alone.
Pete Cooper8a06af92012-04-02 22:22:53 +00001185 LiveInterval &NewLI = Edit->createFrom(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001186 NewLI.markNotSpillable();
1187
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001188 if (RI.Reads)
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001189 insertReload(NewLI, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001190
1191 // Rewrite instruction operands.
1192 bool hasLiveDef = false;
1193 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001194 MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +00001195 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001196 if (MO.isUse()) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001197 if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second))
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001198 MO.setIsKill();
1199 } else {
1200 if (!MO.isDead())
1201 hasLiveDef = true;
1202 }
1203 }
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001204 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001205
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001206 // FIXME: Use a second vreg if instruction has no tied ops.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001207 if (RI.Writes) {
1208 if (hasLiveDef)
1209 insertSpill(NewLI, OldLI, Idx, MI);
1210 else {
1211 // This instruction defines a dead value. We don't need to spill it,
1212 // but do create a live range for the dead value.
1213 VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
1214 NewLI.addRange(LiveRange(Idx, Idx.getDeadSlot(), VNI));
1215 }
Jakob Stoklund Olesena80444f2011-10-14 00:34:31 +00001216 }
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001217
1218 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001219 }
1220}
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001221
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001222/// spillAll - Spill all registers remaining after rematerialization.
1223void InlineSpiller::spillAll() {
1224 // Update LiveStacks now that we are committed to spilling.
1225 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1226 StackSlot = VRM.assignVirt2StackSlot(Original);
1227 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +00001228 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001229 } else
1230 StackInt = &LSS.getInterval(StackSlot);
1231
1232 if (Original != Edit->getReg())
1233 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1234
1235 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1236 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1237 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
1238 StackInt->getValNumInfo(0));
1239 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1240
1241 // Spill around uses of all RegsToSpill.
1242 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1243 spillAroundUses(RegsToSpill[i]);
1244
1245 // Hoisted spills may cause dead code.
1246 if (!DeadDefs.empty()) {
1247 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
Pete Cooper8a06af92012-04-02 22:22:53 +00001248 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001249 }
1250
1251 // Finally delete the SnippetCopies.
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001252 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1253 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(RegsToSpill[i]);
1254 MachineInstr *MI = RI.skipInstruction();) {
1255 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1256 // FIXME: Do this with a LiveRangeEdit callback.
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001257 LIS.RemoveMachineInstrFromMaps(MI);
1258 MI->eraseFromParent();
1259 }
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001260 }
1261
1262 // Delete all spilled registers.
1263 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
Pete Cooper8a06af92012-04-02 22:22:53 +00001264 Edit->eraseVirtReg(RegsToSpill[i]);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001265}
1266
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001267void InlineSpiller::spill(LiveRangeEdit &edit) {
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001268 ++NumSpilledRanges;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001269 Edit = &edit;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001270 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1271 && "Trying to spill a stack slot.");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001272 // Share a stack slot among all descendants of Original.
1273 Original = VRM.getOriginal(edit.getReg());
1274 StackSlot = VRM.getStackSlot(Original);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001275 StackInt = 0;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001276
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001277 DEBUG(dbgs() << "Inline spilling "
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001278 << MRI.getRegClass(edit.getReg())->getName()
Jakob Stoklund Olesen127cdba2012-06-15 23:47:09 +00001279 << ':' << PrintReg(edit.getReg()) << ' ' << edit.getParent()
1280 << "\nFrom original " << LIS.getInterval(Original) << '\n');
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001281 assert(edit.getParent().isSpillable() &&
1282 "Attempting to spill already spilled value.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001283 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001284
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001285 collectRegsToSpill();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001286 analyzeSiblingValues();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001287 reMaterializeAll();
1288
1289 // Remat may handle everything.
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001290 if (!RegsToSpill.empty())
1291 spillAll();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001292
Pete Cooper8a06af92012-04-02 22:22:53 +00001293 Edit->calculateRegClassAndHint(MF, Loops);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001294}