blob: 85bf4efa77a09354314851a2afdafe1d1798c4a2 [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"
Benjamin Kramer4eed7562013-06-17 19:00:36 +000025#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000026#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineFunction.h"
David Blaikie6d9dbd52013-06-16 20:34:15 +000028#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000029#include "llvm/CodeGen/MachineInstrBundle.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000032#include "llvm/CodeGen/VirtRegMap.h"
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +000033#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000036#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000038
39using namespace llvm;
40
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000041STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000042STATISTIC(NumSnippets, "Number of spilled snippets");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000043STATISTIC(NumSpills, "Number of spills inserted");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000044STATISTIC(NumSpillsRemoved, "Number of spills removed");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000045STATISTIC(NumReloads, "Number of reloads inserted");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000046STATISTIC(NumReloadsRemoved, "Number of reloads removed");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000047STATISTIC(NumFolded, "Number of folded stack accesses");
48STATISTIC(NumFoldedLoads, "Number of folded loads");
49STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000050STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads");
51STATISTIC(NumHoists, "Number of hoisted spills");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000052
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +000053static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
54 cl::desc("Disable inline spill hoisting"));
55
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000056namespace {
57class InlineSpiller : public Spiller {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000058 MachineFunction &MF;
59 LiveIntervals &LIS;
60 LiveStacks &LSS;
61 AliasAnalysis *AA;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000062 MachineDominatorTree &MDT;
63 MachineLoopInfo &Loops;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000064 VirtRegMap &VRM;
65 MachineFrameInfo &MFI;
66 MachineRegisterInfo &MRI;
67 const TargetInstrInfo &TII;
68 const TargetRegisterInfo &TRI;
Benjamin Kramer4eed7562013-06-17 19:00:36 +000069 const MachineBlockFrequencyInfo &MBFI;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +000070
71 // Variables that are valid during spill(), but used by multiple methods.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000072 LiveRangeEdit *Edit;
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +000073 LiveInterval *StackInt;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000074 int StackSlot;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000075 unsigned Original;
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000076
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000077 // All registers to spill to StackSlot, including the main register.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +000078 SmallVector<unsigned, 8> RegsToSpill;
79
80 // All COPY instructions to/from snippets.
81 // They are ignored since both operands refer to the same stack slot.
82 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
83
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +000084 // Values that failed to remat at some point.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000085 SmallPtrSet<VNInfo*, 8> UsedValues;
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +000086
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000087public:
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000088 // Information about a value that was defined by a copy from a sibling
89 // register.
90 struct SibValueInfo {
91 // True when all reaching defs were reloads: No spill is necessary.
92 bool AllDefsAreReloads;
93
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000094 // True when value is defined by an original PHI not from splitting.
95 bool DefByOrigPHI;
96
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +000097 // True when the COPY defining this value killed its source.
98 bool KillsSource;
99
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000100 // The preferred register to spill.
101 unsigned SpillReg;
102
103 // The value of SpillReg that should be spilled.
104 VNInfo *SpillVNI;
105
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000106 // The block where SpillVNI should be spilled. Currently, this must be the
107 // block containing SpillVNI->def.
108 MachineBasicBlock *SpillMBB;
109
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000110 // A defining instruction that is not a sibling copy or a reload, or NULL.
111 // This can be used as a template for rematerialization.
112 MachineInstr *DefMI;
113
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000114 // List of values that depend on this one. These values are actually the
115 // same, but live range splitting has placed them in different registers,
116 // or SSA update needed to insert PHI-defs to preserve SSA form. This is
117 // copies of the current value and phi-kills. Usually only phi-kills cause
118 // more than one dependent value.
119 TinyPtrVector<VNInfo*> Deps;
120
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000121 SibValueInfo(unsigned Reg, VNInfo *VNI)
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000122 : AllDefsAreReloads(true), DefByOrigPHI(false), KillsSource(false),
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000123 SpillReg(Reg), SpillVNI(VNI), SpillMBB(0), DefMI(0) {}
124
125 // Returns true when a def has been found.
126 bool hasDef() const { return DefByOrigPHI || DefMI; }
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000127 };
128
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000129private:
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000130 // Values in RegsToSpill defined by sibling copies.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000131 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
132 SibValueMap SibValues;
133
134 // Dead defs generated during spilling.
135 SmallVector<MachineInstr*, 8> DeadDefs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000136
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000137 ~InlineSpiller() {}
138
139public:
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000140 InlineSpiller(MachineFunctionPass &pass,
141 MachineFunction &mf,
142 VirtRegMap &vrm)
Benjamin Kramer95a9d932012-06-06 19:47:08 +0000143 : MF(mf),
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000144 LIS(pass.getAnalysis<LiveIntervals>()),
145 LSS(pass.getAnalysis<LiveStacks>()),
146 AA(&pass.getAnalysis<AliasAnalysis>()),
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000147 MDT(pass.getAnalysis<MachineDominatorTree>()),
148 Loops(pass.getAnalysis<MachineLoopInfo>()),
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000149 VRM(vrm),
150 MFI(*mf.getFrameInfo()),
151 MRI(mf.getRegInfo()),
152 TII(*mf.getTarget().getInstrInfo()),
Benjamin Kramer4eed7562013-06-17 19:00:36 +0000153 TRI(*mf.getTarget().getRegisterInfo()),
154 MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()) {}
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000155
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000156 void spill(LiveRangeEdit &);
157
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000158private:
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000159 bool isSnippet(const LiveInterval &SnipLI);
160 void collectRegsToSpill();
161
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000162 bool isRegToSpill(unsigned Reg) {
163 return std::find(RegsToSpill.begin(),
164 RegsToSpill.end(), Reg) != RegsToSpill.end();
165 }
166
167 bool isSibling(unsigned Reg);
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000168 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000169 void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = 0);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000170 void analyzeSiblingValues();
171
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000172 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000173 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000174
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000175 void markValueUsed(LiveInterval*, VNInfo*);
176 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000177 void reMaterializeAll();
178
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000179 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000180 bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> >,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000181 MachineInstr *LoadMI = 0);
Mark Laceye742d682013-08-14 23:50:16 +0000182 void insertReload(unsigned VReg, SlotIndex, MachineBasicBlock::iterator MI);
183 void insertSpill(unsigned VReg, bool isKill, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000184
185 void spillAroundUses(unsigned Reg);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000186 void spillAll();
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000187};
188}
189
190namespace llvm {
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000191Spiller *createInlineSpiller(MachineFunctionPass &pass,
192 MachineFunction &mf,
193 VirtRegMap &vrm) {
194 return new InlineSpiller(pass, mf, vrm);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000195}
196}
197
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000198//===----------------------------------------------------------------------===//
199// Snippets
200//===----------------------------------------------------------------------===//
201
202// When spilling a virtual register, we also spill any snippets it is connected
203// to. The snippets are small live ranges that only have a single real use,
204// leftovers from live range splitting. Spilling them enables memory operand
205// folding or tightens the live range around the single use.
206//
207// This minimizes register pressure and maximizes the store-to-load distance for
208// spill slots which can be important in tight loops.
209
210/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
211/// otherwise return 0.
212static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
Rafael Espindolacfe52542011-06-30 21:15:52 +0000213 if (!MI->isFullCopy())
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000214 return 0;
215 if (MI->getOperand(0).getReg() == Reg)
216 return MI->getOperand(1).getReg();
217 if (MI->getOperand(1).getReg() == Reg)
218 return MI->getOperand(0).getReg();
219 return 0;
220}
221
222/// isSnippet - Identify if a live interval is a snippet that should be spilled.
223/// It is assumed that SnipLI is a virtual register with the same original as
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000224/// Edit->getReg().
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000225bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000226 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000227
228 // A snippet is a tiny live range with only a single instruction using it
229 // besides copies to/from Reg or spills/fills. We accept:
230 //
231 // %snip = COPY %Reg / FILL fi#
232 // %snip = USE %snip
233 // %Reg = COPY %snip / SPILL %snip, fi#
234 //
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000235 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000236 return false;
237
238 MachineInstr *UseMI = 0;
239
240 // Check that all uses satisfy our criteria.
241 for (MachineRegisterInfo::reg_nodbg_iterator
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000242 RI = MRI.reg_nodbg_begin(SnipLI.reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000243 MachineInstr *MI = RI.skipInstruction();) {
244
245 // Allow copies to/from Reg.
246 if (isFullCopyOf(MI, Reg))
247 continue;
248
249 // Allow stack slot loads.
250 int FI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000251 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000252 continue;
253
254 // Allow stack slot stores.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000255 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000256 continue;
257
258 // Allow a single additional instruction.
259 if (UseMI && MI != UseMI)
260 return false;
261 UseMI = MI;
262 }
263 return true;
264}
265
266/// collectRegsToSpill - Collect live range snippets that only have a single
267/// real use.
268void InlineSpiller::collectRegsToSpill() {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000269 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000270
271 // Main register always spills.
272 RegsToSpill.assign(1, Reg);
273 SnippetCopies.clear();
274
275 // Snippets all have the same original, so there can't be any for an original
276 // register.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000277 if (Original == Reg)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000278 return;
279
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000280 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000281 MachineInstr *MI = RI.skipInstruction();) {
282 unsigned SnipReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000283 if (!isSibling(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000284 continue;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000285 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000286 if (!isSnippet(SnipLI))
287 continue;
288 SnippetCopies.insert(MI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000289 if (isRegToSpill(SnipReg))
290 continue;
291 RegsToSpill.push_back(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000292 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000293 ++NumSnippets;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000294 }
295}
296
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000297
298//===----------------------------------------------------------------------===//
299// Sibling Values
300//===----------------------------------------------------------------------===//
301
302// After live range splitting, some values to be spilled may be defined by
303// copies from sibling registers. We trace the sibling copies back to the
304// original value if it still exists. We need it for rematerialization.
305//
306// Even when the value can't be rematerialized, we still want to determine if
307// the value has already been spilled, or we may want to hoist the spill from a
308// loop.
309
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000310bool InlineSpiller::isSibling(unsigned Reg) {
311 return TargetRegisterInfo::isVirtualRegister(Reg) &&
312 VRM.getOriginal(Reg) == Original;
313}
314
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000315#ifndef NDEBUG
316static raw_ostream &operator<<(raw_ostream &OS,
317 const InlineSpiller::SibValueInfo &SVI) {
318 OS << "spill " << PrintReg(SVI.SpillReg) << ':'
319 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
320 if (SVI.SpillMBB)
321 OS << " in BB#" << SVI.SpillMBB->getNumber();
322 if (SVI.AllDefsAreReloads)
323 OS << " all-reloads";
324 if (SVI.DefByOrigPHI)
325 OS << " orig-phi";
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000326 if (SVI.KillsSource)
327 OS << " kill";
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000328 OS << " deps[";
329 for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i)
330 OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def;
331 OS << " ]";
332 if (SVI.DefMI)
333 OS << " def: " << *SVI.DefMI;
334 else
335 OS << '\n';
336 return OS;
337}
338#endif
339
340/// propagateSiblingValue - Propagate the value in SVI to dependents if it is
341/// known. Otherwise remember the dependency for later.
342///
Benjamin Kramer2db14ba2013-05-23 15:42:57 +0000343/// @param SVIIter SibValues entry to propagate.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000344/// @param VNI Dependent value, or NULL to propagate to all saved dependents.
Benjamin Kramer2db14ba2013-05-23 15:42:57 +0000345void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVIIter,
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000346 VNInfo *VNI) {
Benjamin Kramer2db14ba2013-05-23 15:42:57 +0000347 SibValueMap::value_type *SVI = &*SVIIter;
348
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000349 // When VNI is non-NULL, add it to SVI's deps, and only propagate to that.
350 TinyPtrVector<VNInfo*> FirstDeps;
351 if (VNI) {
352 FirstDeps.push_back(VNI);
353 SVI->second.Deps.push_back(VNI);
354 }
355
356 // Has the value been completely determined yet? If not, defer propagation.
357 if (!SVI->second.hasDef())
358 return;
359
Benjamin Kramer2db14ba2013-05-23 15:42:57 +0000360 // Work list of values to propagate.
361 SmallSetVector<SibValueMap::value_type *, 8> WorkList;
362 WorkList.insert(SVI);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000363
364 do {
365 SVI = WorkList.pop_back_val();
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000366 TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps;
367 VNI = 0;
368
369 SibValueInfo &SV = SVI->second;
370 if (!SV.SpillMBB)
371 SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
372
373 DEBUG(dbgs() << " prop to " << Deps->size() << ": "
374 << SVI->first->id << '@' << SVI->first->def << ":\t" << SV);
375
376 assert(SV.hasDef() && "Propagating undefined value");
377
378 // Should this value be propagated as a preferred spill candidate? We don't
379 // propagate values of registers that are about to spill.
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +0000380 bool PropSpill = !DisableHoisting && !isRegToSpill(SV.SpillReg);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000381 unsigned SpillDepth = ~0u;
382
383 for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(),
384 DepE = Deps->end(); DepI != DepE; ++DepI) {
385 SibValueMap::iterator DepSVI = SibValues.find(*DepI);
386 assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
387 SibValueInfo &DepSV = DepSVI->second;
388 if (!DepSV.SpillMBB)
389 DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
390
391 bool Changed = false;
392
393 // Propagate defining instruction.
394 if (!DepSV.hasDef()) {
395 Changed = true;
396 DepSV.DefMI = SV.DefMI;
397 DepSV.DefByOrigPHI = SV.DefByOrigPHI;
398 }
399
400 // Propagate AllDefsAreReloads. For PHI values, this computes an AND of
401 // all predecessors.
402 if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
403 Changed = true;
404 DepSV.AllDefsAreReloads = false;
405 }
406
407 // Propagate best spill value.
408 if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
409 if (SV.SpillMBB == DepSV.SpillMBB) {
410 // DepSV is in the same block. Hoist when dominated.
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000411 if (DepSV.KillsSource && SV.SpillVNI->def < DepSV.SpillVNI->def) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000412 // This is an alternative def earlier in the same MBB.
413 // Hoist the spill as far as possible in SpillMBB. This can ease
414 // register pressure:
415 //
416 // x = def
417 // y = use x
418 // s = copy x
419 //
420 // Hoisting the spill of s to immediately after the def removes the
421 // interference between x and y:
422 //
423 // x = def
424 // spill x
425 // y = use x<kill>
426 //
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000427 // This hoist only helps when the DepSV copy kills its source.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000428 Changed = true;
429 DepSV.SpillReg = SV.SpillReg;
430 DepSV.SpillVNI = SV.SpillVNI;
431 DepSV.SpillMBB = SV.SpillMBB;
432 }
433 } else {
434 // DepSV is in a different block.
435 if (SpillDepth == ~0u)
436 SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
437
438 // Also hoist spills to blocks with smaller loop depth, but make sure
439 // that the new value dominates. Non-phi dependents are always
440 // dominated, phis need checking.
441 if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
442 (!DepSVI->first->isPHIDef() ||
443 MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
444 Changed = true;
445 DepSV.SpillReg = SV.SpillReg;
446 DepSV.SpillVNI = SV.SpillVNI;
447 DepSV.SpillMBB = SV.SpillMBB;
448 }
449 }
450 }
451
452 if (!Changed)
453 continue;
454
455 // Something changed in DepSVI. Propagate to dependents.
Benjamin Kramer2db14ba2013-05-23 15:42:57 +0000456 WorkList.insert(&*DepSVI);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000457
458 DEBUG(dbgs() << " update " << DepSVI->first->id << '@'
459 << DepSVI->first->def << " to:\t" << DepSV);
460 }
461 } while (!WorkList.empty());
462}
463
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000464/// traceSiblingValue - Trace a value that is about to be spilled back to the
465/// real defining instructions by looking through sibling copies. Always stay
466/// within the range of OrigVNI so the registers are known to carry the same
467/// value.
468///
469/// Determine if the value is defined by all reloads, so spilling isn't
470/// necessary - the value is already in the stack slot.
471///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000472/// Return a defining instruction that may be a candidate for rematerialization.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000473///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000474MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
475 VNInfo *OrigVNI) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000476 // Check if a cached value already exists.
477 SibValueMap::iterator SVI;
478 bool Inserted;
479 tie(SVI, Inserted) =
480 SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
481 if (!Inserted) {
482 DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
483 << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
484 return SVI->second.DefMI;
485 }
486
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000487 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
488 << UseVNI->id << '@' << UseVNI->def << '\n');
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000489
490 // List of (Reg, VNI) that have been inserted into SibValues, but need to be
491 // processed.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000492 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000493 WorkList.push_back(std::make_pair(UseReg, UseVNI));
494
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000495 do {
496 unsigned Reg;
497 VNInfo *VNI;
498 tie(Reg, VNI) = WorkList.pop_back_val();
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000499 DEBUG(dbgs() << " " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
500 << ":\t");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000501
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000502 // First check if this value has already been computed.
503 SVI = SibValues.find(VNI);
504 assert(SVI != SibValues.end() && "Missing SibValues entry");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000505
506 // Trace through PHI-defs created by live range splitting.
507 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000508 // Stop at original PHIs. We don't know the value at the predecessors.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000509 if (VNI->def == OrigVNI->def) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000510 DEBUG(dbgs() << "orig phi value\n");
511 SVI->second.DefByOrigPHI = true;
512 SVI->second.AllDefsAreReloads = false;
513 propagateSiblingValue(SVI);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000514 continue;
515 }
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000516
517 // This is a PHI inserted by live range splitting. We could trace the
518 // live-out value from predecessor blocks, but that search can be very
519 // expensive if there are many predecessors and many more PHIs as
520 // generated by tail-dup when it sees an indirectbr. Instead, look at
521 // all the non-PHI defs that have the same value as OrigVNI. They must
522 // jointly dominate VNI->def. This is not optimal since VNI may actually
523 // be jointly dominated by a smaller subset of defs, so there is a change
524 // we will miss a AllDefsAreReloads optimization.
525
526 // Separate all values dominated by OrigVNI into PHIs and non-PHIs.
527 SmallVector<VNInfo*, 8> PHIs, NonPHIs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000528 LiveInterval &LI = LIS.getInterval(Reg);
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000529 LiveInterval &OrigLI = LIS.getInterval(Original);
530
531 for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end();
532 VI != VE; ++VI) {
533 VNInfo *VNI2 = *VI;
534 if (VNI2->isUnused())
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000535 continue;
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000536 if (!OrigLI.containsOneValue() &&
537 OrigLI.getVNInfoAt(VNI2->def) != OrigVNI)
538 continue;
539 if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def)
540 PHIs.push_back(VNI2);
541 else
542 NonPHIs.push_back(VNI2);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000543 }
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000544 DEBUG(dbgs() << "split phi value, checking " << PHIs.size()
545 << " phi-defs, and " << NonPHIs.size()
546 << " non-phi/orig defs\n");
547
548 // Create entries for all the PHIs. Don't add them to the worklist, we
549 // are processing all of them in one go here.
550 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
551 SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i])));
552
553 // Add every PHI as a dependent of all the non-PHIs.
554 for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) {
555 VNInfo *NonPHI = NonPHIs[i];
556 // Known value? Try an insertion.
557 tie(SVI, Inserted) =
558 SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI)));
559 // Add all the PHIs as dependents of NonPHI.
560 for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi)
561 SVI->second.Deps.push_back(PHIs[pi]);
562 // This is the first time we see NonPHI, add it to the worklist.
563 if (Inserted)
564 WorkList.push_back(std::make_pair(Reg, NonPHI));
565 else
566 // Propagate to all inserted PHIs, not just VNI.
567 propagateSiblingValue(SVI);
568 }
569
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000570 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000571 continue;
572 }
573
574 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
575 assert(MI && "Missing def");
576
577 // Trace through sibling copies.
578 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000579 if (isSibling(SrcReg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000580 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
Matthias Braun5649e252013-10-10 21:28:52 +0000581 LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
Jakob Stoklund Olesen92a05fa2012-05-20 02:44:33 +0000582 assert(SrcQ.valueIn() && "Copy from non-existing value");
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000583 // Check if this COPY kills its source.
Jakob Stoklund Olesen92a05fa2012-05-20 02:44:33 +0000584 SVI->second.KillsSource = SrcQ.isKill();
585 VNInfo *SrcVNI = SrcQ.valueIn();
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000586 DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000587 << SrcVNI->id << '@' << SrcVNI->def
588 << " kill=" << unsigned(SVI->second.KillsSource) << '\n');
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000589 // Known sibling source value? Try an insertion.
590 tie(SVI, Inserted) = SibValues.insert(std::make_pair(SrcVNI,
591 SibValueInfo(SrcReg, SrcVNI)));
592 // This is the first time we see Src, add it to the worklist.
593 if (Inserted)
594 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
595 propagateSiblingValue(SVI, VNI);
596 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000597 continue;
598 }
599 }
600
601 // Track reachable reloads.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000602 SVI->second.DefMI = MI;
603 SVI->second.SpillMBB = MI->getParent();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000604 int FI;
605 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000606 DEBUG(dbgs() << "reload\n");
607 propagateSiblingValue(SVI);
608 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000609 continue;
610 }
611
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000612 // Potential remat candidate.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000613 DEBUG(dbgs() << "def " << *MI);
614 SVI->second.AllDefsAreReloads = false;
615 propagateSiblingValue(SVI);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000616 } while (!WorkList.empty());
617
Logan Chiene2ac5522012-09-01 12:11:41 +0000618 // Look up the value we were looking for. We already did this lookup at the
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000619 // top of the function, but SibValues may have been invalidated.
620 SVI = SibValues.find(UseVNI);
621 assert(SVI != SibValues.end() && "Didn't compute requested info");
622 DEBUG(dbgs() << " traced to:\t" << SVI->second);
623 return SVI->second.DefMI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000624}
625
626/// analyzeSiblingValues - Trace values defined by sibling copies back to
627/// something that isn't a sibling copy.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000628///
629/// Keep track of values that may be rematerializable.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000630void InlineSpiller::analyzeSiblingValues() {
631 SibValues.clear();
632
633 // No siblings at all?
634 if (Edit->getReg() == Original)
635 return;
636
637 LiveInterval &OrigLI = LIS.getInterval(Original);
638 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
639 unsigned Reg = RegsToSpill[i];
640 LiveInterval &LI = LIS.getInterval(Reg);
641 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
642 VE = LI.vni_end(); VI != VE; ++VI) {
643 VNInfo *VNI = *VI;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000644 if (VNI->isUnused())
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000645 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000646 MachineInstr *DefMI = 0;
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000647 if (!VNI->isPHIDef()) {
648 DefMI = LIS.getInstructionFromIndex(VNI->def);
649 assert(DefMI && "No defining instruction");
650 }
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000651 // Check possible sibling copies.
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000652 if (VNI->isPHIDef() || DefMI->isCopy()) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000653 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
Jakob Stoklund Olesen9693d4c2011-07-05 15:38:41 +0000654 assert(OrigVNI && "Def outside original live range");
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000655 if (OrigVNI->def != VNI->def)
656 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
657 }
Pete Cooper8a06af92012-04-02 22:22:53 +0000658 if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) {
Jakob Stoklund Olesen3b7d9172011-04-20 22:14:20 +0000659 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
660 << VNI->def << " may remat from " << *DefMI);
661 }
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000662 }
663 }
664}
665
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000666/// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
667/// a spill at a better location.
668bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
669 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000670 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
671 assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000672 SibValueMap::iterator I = SibValues.find(VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000673 if (I == SibValues.end())
674 return false;
675
676 const SibValueInfo &SVI = I->second;
677
678 // Let the normal folding code deal with the boring case.
679 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
680 return false;
681
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000682 // SpillReg may have been deleted by remat and DCE.
683 if (!LIS.hasInterval(SVI.SpillReg)) {
684 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
685 SibValues.erase(I);
686 return false;
687 }
688
689 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
690 if (!SibLI.containsValue(SVI.SpillVNI)) {
691 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
692 SibValues.erase(I);
693 return false;
694 }
695
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000696 // Conservatively extend the stack slot range to the range of the original
697 // value. We may be able to do better with stack slot coloring by being more
698 // careful here.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000699 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000700 LiveInterval &OrigLI = LIS.getInterval(Original);
701 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000702 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +0000703 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000704 << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000705
706 // Already spilled everywhere.
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000707 if (SVI.AllDefsAreReloads) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000708 DEBUG(dbgs() << "\tno spill needed: " << SVI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000709 ++NumOmitReloadSpill;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000710 return true;
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000711 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000712 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
713 // any later spills of the same value.
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000714 eliminateRedundantSpills(SibLI, SVI.SpillVNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000715
716 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
717 MachineBasicBlock::iterator MII;
718 if (SVI.SpillVNI->isPHIDef())
719 MII = MBB->SkipPHIsAndLabels(MBB->begin());
720 else {
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000721 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
722 assert(DefMI && "Defining instruction disappeared");
723 MII = DefMI;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000724 ++MII;
725 }
726 // Insert spill without kill flag immediately after def.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000727 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
728 MRI.getRegClass(SVI.SpillReg), &TRI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000729 --MII; // Point to store instruction.
730 LIS.InsertMachineInstrInMaps(MII);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000731 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000732
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000733 ++NumSpills;
734 ++NumHoists;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000735 return true;
736}
737
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000738/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
739/// redundant spills of this value in SLI.reg and sibling copies.
740void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000741 assert(VNI && "Missing value");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000742 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
743 WorkList.push_back(std::make_pair(&SLI, VNI));
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000744 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000745
746 do {
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000747 LiveInterval *LI;
748 tie(LI, VNI) = WorkList.pop_back_val();
749 unsigned Reg = LI->reg;
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000750 DEBUG(dbgs() << "Checking redundant spills for "
751 << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000752
753 // Regs to spill are taken care of.
754 if (isRegToSpill(Reg))
755 continue;
756
757 // Add all of VNI's live range to StackInt.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000758 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
759 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000760
761 // Find all spills and copies of VNI.
762 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
763 MachineInstr *MI = UI.skipInstruction();) {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000764 if (!MI->isCopy() && !MI->mayStore())
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000765 continue;
766 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000767 if (LI->getVNInfoAt(Idx) != VNI)
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000768 continue;
769
770 // Follow sibling copies down the dominator tree.
771 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
772 if (isSibling(DstReg)) {
773 LiveInterval &DstLI = LIS.getInterval(DstReg);
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000774 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000775 assert(DstVNI && "Missing defined value");
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000776 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000777 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000778 }
779 continue;
780 }
781
782 // Erase spills.
783 int FI;
784 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
785 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
786 // eliminateDeadDefs won't normally remove stores, so switch opcode.
787 MI->setDesc(TII.get(TargetOpcode::KILL));
788 DeadDefs.push_back(MI);
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000789 ++NumSpillsRemoved;
790 --NumSpills;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000791 }
792 }
793 } while (!WorkList.empty());
794}
795
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000796
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000797//===----------------------------------------------------------------------===//
798// Rematerialization
799//===----------------------------------------------------------------------===//
800
801/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
802/// instruction cannot be eliminated. See through snippet copies
803void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
804 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
805 WorkList.push_back(std::make_pair(LI, VNI));
806 do {
807 tie(LI, VNI) = WorkList.pop_back_val();
808 if (!UsedValues.insert(VNI))
809 continue;
810
811 if (VNI->isPHIDef()) {
812 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
813 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
814 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen194eb712011-11-14 01:39:36 +0000815 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000816 if (PVNI)
817 WorkList.push_back(std::make_pair(LI, PVNI));
818 }
819 continue;
820 }
821
822 // Follow snippet copies.
823 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
824 if (!SnippetCopies.count(MI))
825 continue;
826 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
827 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000828 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000829 assert(SnipVNI && "Snippet undefined before copy");
830 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
831 } while (!WorkList.empty());
832}
833
834/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
835bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
836 MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000837 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
Jakob Stoklund Olesen79413502011-07-18 05:31:59 +0000838 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000839
840 if (!ParentVNI) {
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000841 DEBUG(dbgs() << "\tadding <undef> flags: ");
842 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
843 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000844 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000845 MO.setIsUndef();
846 }
847 DEBUG(dbgs() << UseIdx << '\t' << *MI);
848 return true;
849 }
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000850
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000851 if (SnippetCopies.count(MI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000852 return false;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000853
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000854 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
855 LiveRangeEdit::Remat RM(ParentVNI);
856 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
857 if (SibI != SibValues.end())
858 RM.OrigMI = SibI->second.DefMI;
Pete Cooper8a06af92012-04-02 22:22:53 +0000859 if (!Edit->canRematerializeAt(RM, UseIdx, false)) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000860 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000861 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
862 return false;
863 }
864
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000865 // If the instruction also writes VirtReg.reg, it had better not require the
866 // same register for uses and defs.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000867 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
James Molloyb17cf292012-09-12 10:03:31 +0000868 MIBundleOperands::VirtRegInfo RI =
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000869 MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
870 if (RI.Tied) {
871 markValueUsed(&VirtReg, ParentVNI);
872 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
873 return false;
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000874 }
875
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000876 // Before rematerializing into a register for a single instruction, try to
877 // fold a load into the instruction. That avoids allocating a new register.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000878 if (RM.OrigMI->canFoldAsLoad() &&
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000879 foldMemoryOperand(Ops, RM.OrigMI)) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000880 Edit->markRematerialized(RM.ParentVNI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000881 ++NumFoldedLoads;
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000882 return true;
883 }
884
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000885 // Alocate a new register for the remat.
Mark Laceye742d682013-08-14 23:50:16 +0000886 unsigned NewVReg = Edit->createFrom(Original);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000887
888 // Finally we can rematerialize OrigMI before MI.
Mark Laceye742d682013-08-14 23:50:16 +0000889 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewVReg, RM,
Pete Cooper8a06af92012-04-02 22:22:53 +0000890 TRI);
Mark Laceye742d682013-08-14 23:50:16 +0000891 (void)DefIdx;
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000892 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000893 << *LIS.getInstructionFromIndex(DefIdx));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000894
895 // Replace operands
896 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000897 MachineOperand &MO = MI->getOperand(Ops[i].second);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000898 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
Mark Laceye742d682013-08-14 23:50:16 +0000899 MO.setReg(NewVReg);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000900 MO.setIsKill();
901 }
902 }
Mark Laceye742d682013-08-14 23:50:16 +0000903 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI << '\n');
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000904
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000905 ++NumRemats;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000906 return true;
907}
908
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000909/// reMaterializeAll - Try to rematerialize as many uses as possible,
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000910/// and trim the live ranges after.
911void InlineSpiller::reMaterializeAll() {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000912 // analyzeSiblingValues has already tested all relevant defining instructions.
Pete Cooper8a06af92012-04-02 22:22:53 +0000913 if (!Edit->anyRematerializable(AA))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000914 return;
915
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000916 UsedValues.clear();
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000917
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000918 // Try to remat before all uses of snippets.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000919 bool anyRemat = false;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000920 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
921 unsigned Reg = RegsToSpill[i];
922 LiveInterval &LI = LIS.getInterval(Reg);
923 for (MachineRegisterInfo::use_nodbg_iterator
924 RI = MRI.use_nodbg_begin(Reg);
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000925 MachineInstr *MI = RI.skipBundle();)
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000926 anyRemat |= reMaterializeFor(LI, MI);
927 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000928 if (!anyRemat)
929 return;
930
931 // Remove any values that were completely rematted.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000932 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
933 unsigned Reg = RegsToSpill[i];
934 LiveInterval &LI = LIS.getInterval(Reg);
935 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
936 I != E; ++I) {
937 VNInfo *VNI = *I;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000938 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000939 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000940 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
941 MI->addRegisterDead(Reg, &TRI);
942 if (!MI->allDefsAreDead())
943 continue;
944 DEBUG(dbgs() << "All defs dead: " << *MI);
945 DeadDefs.push_back(MI);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000946 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000947 }
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000948
949 // Eliminate dead code after remat. Note that some snippet copies may be
950 // deleted here.
951 if (DeadDefs.empty())
952 return;
953 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
Pete Cooper8a06af92012-04-02 22:22:53 +0000954 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000955
956 // Get rid of deleted and empty intervals.
Benjamin Kramere210df22013-05-05 11:29:14 +0000957 unsigned ResultPos = 0;
958 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
959 unsigned Reg = RegsToSpill[i];
960 if (!LIS.hasInterval(Reg))
961 continue;
962
963 LiveInterval &LI = LIS.getInterval(Reg);
964 if (LI.empty()) {
965 Edit->eraseVirtReg(Reg);
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000966 continue;
967 }
Benjamin Kramere210df22013-05-05 11:29:14 +0000968
969 RegsToSpill[ResultPos++] = Reg;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000970 }
Benjamin Kramere210df22013-05-05 11:29:14 +0000971 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000972 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000973}
974
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000975
976//===----------------------------------------------------------------------===//
977// Spilling
978//===----------------------------------------------------------------------===//
979
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000980/// If MI is a load or store of StackSlot, it can be removed.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000981bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000982 int FI = 0;
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000983 unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI);
984 bool IsLoad = InstrReg;
985 if (!IsLoad)
986 InstrReg = TII.isStoreToStackSlot(MI, FI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000987
988 // We have a stack access. Is it the right register and slot?
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000989 if (InstrReg != Reg || FI != StackSlot)
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000990 return false;
991
992 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000993 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000994 MI->eraseFromParent();
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000995
996 if (IsLoad) {
997 ++NumReloadsRemoved;
998 --NumReloads;
999 } else {
1000 ++NumSpillsRemoved;
1001 --NumSpills;
1002 }
1003
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001004 return true;
1005}
1006
Mark Laceye742d682013-08-14 23:50:16 +00001007#if !defined(NDEBUG)
1008// Dump the range of instructions from B to E with their slot indexes.
1009static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
1010 MachineBasicBlock::iterator E,
1011 LiveIntervals const &LIS,
1012 const char *const header,
1013 unsigned VReg =0) {
1014 char NextLine = '\n';
1015 char SlotIndent = '\t';
1016
1017 if (llvm::next(B) == E) {
1018 NextLine = ' ';
1019 SlotIndent = ' ';
1020 }
1021
1022 dbgs() << '\t' << header << ": " << NextLine;
1023
1024 for (MachineBasicBlock::iterator I = B; I != E; ++I) {
1025 SlotIndex Idx = LIS.getInstructionIndex(I).getRegSlot();
1026
1027 // If a register was passed in and this instruction has it as a
1028 // destination that is marked as an early clobber, print the
1029 // early-clobber slot index.
1030 if (VReg) {
1031 MachineOperand *MO = I->findRegisterDefOperand(VReg);
1032 if (MO && MO->isEarlyClobber())
1033 Idx = Idx.getRegSlot(true);
1034 }
1035
1036 dbgs() << SlotIndent << Idx << '\t' << *I;
1037 }
1038}
1039#endif
1040
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001041/// foldMemoryOperand - Try folding stack slot references in Ops into their
1042/// instructions.
1043///
1044/// @param Ops Operand indices from analyzeVirtReg().
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001045/// @param LoadMI Load instruction to use instead of stack slot when non-null.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001046/// @return True on success.
1047bool InlineSpiller::
1048foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops,
1049 MachineInstr *LoadMI) {
1050 if (Ops.empty())
1051 return false;
1052 // Don't attempt folding in bundles.
1053 MachineInstr *MI = Ops.front().first;
1054 if (Ops.back().first != MI || MI->isBundled())
1055 return false;
1056
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001057 bool WasCopy = MI->isCopy();
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001058 unsigned ImpReg = 0;
1059
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001060 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1061 // operands.
1062 SmallVector<unsigned, 8> FoldOps;
1063 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001064 unsigned Idx = Ops[i].second;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001065 MachineOperand &MO = MI->getOperand(Idx);
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001066 if (MO.isImplicit()) {
1067 ImpReg = MO.getReg();
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001068 continue;
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001069 }
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001070 // FIXME: Teach targets to deal with subregs.
1071 if (MO.getSubReg())
1072 return false;
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +00001073 // We cannot fold a load instruction into a def.
1074 if (LoadMI && MO.isDef())
1075 return false;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001076 // Tied use operands should not be passed to foldMemoryOperand.
1077 if (!MI->isRegTiedToDefOperand(Idx))
1078 FoldOps.push_back(Idx);
1079 }
1080
Mark Laceye742d682013-08-14 23:50:16 +00001081 MachineInstrSpan MIS(MI);
1082
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001083 MachineInstr *FoldMI =
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001084 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
1085 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001086 if (!FoldMI)
1087 return false;
Andrew Trickc12c8802013-06-21 18:33:26 +00001088
1089 // Remove LIS for any dead defs in the original MI not in FoldMI.
1090 for (MIBundleOperands MO(MI); MO.isValid(); ++MO) {
1091 if (!MO->isReg())
1092 continue;
1093 unsigned Reg = MO->getReg();
1094 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) ||
1095 MRI.isReserved(Reg)) {
1096 continue;
1097 }
1098 MIBundleOperands::PhysRegInfo RI =
1099 MIBundleOperands(FoldMI).analyzePhysReg(Reg, &TRI);
1100 if (MO->readsReg()) {
1101 assert(RI.Reads && "Cannot fold physreg reader");
1102 continue;
1103 }
1104 if (RI.Defines)
1105 continue;
1106 // FoldMI does not define this physreg. Remove the LI segment.
1107 assert(MO->isDead() && "Cannot fold physreg def");
1108 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) {
1109 if (LiveInterval *LI = LIS.getCachedRegUnit(*Units)) {
1110 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1111 if (VNInfo *VNI = LI->getVNInfoAt(Idx))
1112 LI->removeValNo(VNI);
1113 }
1114 }
1115 }
Mark Laceye742d682013-08-14 23:50:16 +00001116
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001117 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001118 MI->eraseFromParent();
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001119
Mark Laceye742d682013-08-14 23:50:16 +00001120 // Insert any new instructions other than FoldMI into the LIS maps.
1121 assert(!MIS.empty() && "Unexpected empty span of instructions!");
1122 for (MachineBasicBlock::iterator MII = MIS.begin(), End = MIS.end();
1123 MII != End; ++MII)
1124 if (&*MII != FoldMI)
1125 LIS.InsertMachineInstrInMaps(&*MII);
1126
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001127 // TII.foldMemoryOperand may have left some implicit operands on the
1128 // instruction. Strip them.
1129 if (ImpReg)
1130 for (unsigned i = FoldMI->getNumOperands(); i; --i) {
1131 MachineOperand &MO = FoldMI->getOperand(i - 1);
1132 if (!MO.isReg() || !MO.isImplicit())
1133 break;
1134 if (MO.getReg() == ImpReg)
1135 FoldMI->RemoveOperand(i - 1);
1136 }
1137
Mark Laceye742d682013-08-14 23:50:16 +00001138 DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
1139 "folded"));
1140
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001141 if (!WasCopy)
1142 ++NumFolded;
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001143 else if (Ops.front().second == 0)
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001144 ++NumSpills;
1145 else
1146 ++NumReloads;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001147 return true;
1148}
1149
Mark Laceye742d682013-08-14 23:50:16 +00001150void InlineSpiller::insertReload(unsigned NewVReg,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001151 SlotIndex Idx,
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001152 MachineBasicBlock::iterator MI) {
1153 MachineBasicBlock &MBB = *MI->getParent();
Mark Laceye742d682013-08-14 23:50:16 +00001154
1155 MachineInstrSpan MIS(MI);
1156 TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
1157 MRI.getRegClass(NewVReg), &TRI);
1158
1159 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
1160
1161 DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
1162 NewVReg));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001163 ++NumReloads;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001164}
1165
Mark Laceye742d682013-08-14 23:50:16 +00001166/// insertSpill - Insert a spill of NewVReg after MI.
1167void InlineSpiller::insertSpill(unsigned NewVReg, bool isKill,
1168 MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001169 MachineBasicBlock &MBB = *MI->getParent();
Mark Laceye742d682013-08-14 23:50:16 +00001170
1171 MachineInstrSpan MIS(MI);
1172 TII.storeRegToStackSlot(MBB, llvm::next(MI), NewVReg, isKill, StackSlot,
1173 MRI.getRegClass(NewVReg), &TRI);
1174
1175 LIS.InsertMachineInstrRangeInMaps(llvm::next(MI), MIS.end());
1176
1177 DEBUG(dumpMachineInstrRangeWithSlotIndex(llvm::next(MI), MIS.end(), LIS,
1178 "spill"));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001179 ++NumSpills;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001180}
1181
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001182/// spillAroundUses - insert spill code around each use of Reg.
1183void InlineSpiller::spillAroundUses(unsigned Reg) {
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001184 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001185 LiveInterval &OldLI = LIS.getInterval(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001186
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001187 // Iterate over instructions using Reg.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001188 for (MachineRegisterInfo::reg_iterator RegI = MRI.reg_begin(Reg);
1189 MachineInstr *MI = RegI.skipBundle();) {
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001190
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +00001191 // Debug values are not allowed to affect codegen.
1192 if (MI->isDebugValue()) {
1193 // Modify DBG_VALUE now that the value is in a spill slot.
Adrian Prantl818833f2013-09-16 23:29:03 +00001194 bool IsIndirect = MI->isIndirectDebugValue();
Adrian Prantl4759f262013-07-10 16:56:47 +00001195 uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +00001196 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
1197 DebugLoc DL = MI->getDebugLoc();
David Blaikie6d9dbd52013-06-16 20:34:15 +00001198 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1199 MachineBasicBlock *MBB = MI->getParent();
1200 BuildMI(*MBB, MBB->erase(MI), DL, TII.get(TargetOpcode::DBG_VALUE))
1201 .addFrameIndex(StackSlot).addImm(Offset).addMetadata(MDPtr);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +00001202 continue;
1203 }
1204
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001205 // Ignore copies to/from snippets. We'll delete them.
1206 if (SnippetCopies.count(MI))
1207 continue;
1208
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001209 // Stack slot accesses may coalesce away.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001210 if (coalesceStackAccess(MI, Reg))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001211 continue;
1212
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001213 // Analyze instruction.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001214 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
James Molloyb17cf292012-09-12 10:03:31 +00001215 MIBundleOperands::VirtRegInfo RI =
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001216 MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001217
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001218 // Find the slot index where this instruction reads and writes OldLI.
1219 // This is usually the def slot, except for tied early clobbers.
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +00001220 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1221 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001222 if (SlotIndex::isSameInstr(Idx, VNI->def))
1223 Idx = VNI->def;
1224
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001225 // Check for a sibling copy.
1226 unsigned SibReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001227 if (SibReg && isSibling(SibReg)) {
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001228 // This may actually be a copy between snippets.
1229 if (isRegToSpill(SibReg)) {
1230 DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1231 SnippetCopies.insert(MI);
1232 continue;
1233 }
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001234 if (RI.Writes) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001235 // Hoist the spill of a sib-reg copy.
1236 if (hoistSpill(OldLI, MI)) {
1237 // This COPY is now dead, the value is already in the stack slot.
1238 MI->getOperand(0).setIsDead();
1239 DeadDefs.push_back(MI);
1240 continue;
1241 }
1242 } else {
1243 // This is a reload for a sib-reg copy. Drop spills downstream.
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001244 LiveInterval &SibLI = LIS.getInterval(SibReg);
1245 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1246 // The COPY will fold to a reload below.
1247 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001248 }
1249
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +00001250 // Attempt to fold memory ops.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001251 if (foldMemoryOperand(Ops))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +00001252 continue;
1253
Mark Laceye742d682013-08-14 23:50:16 +00001254 // Create a new virtual register for spill/fill.
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001255 // FIXME: Infer regclass from instruction alone.
Mark Laceye742d682013-08-14 23:50:16 +00001256 unsigned NewVReg = Edit->createFrom(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001257
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001258 if (RI.Reads)
Mark Laceye742d682013-08-14 23:50:16 +00001259 insertReload(NewVReg, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001260
1261 // Rewrite instruction operands.
1262 bool hasLiveDef = false;
1263 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001264 MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second);
Mark Laceye742d682013-08-14 23:50:16 +00001265 MO.setReg(NewVReg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001266 if (MO.isUse()) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001267 if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second))
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001268 MO.setIsKill();
1269 } else {
1270 if (!MO.isDead())
1271 hasLiveDef = true;
1272 }
1273 }
Mark Laceye742d682013-08-14 23:50:16 +00001274 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n');
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001275
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001276 // FIXME: Use a second vreg if instruction has no tied ops.
Mark Laceye742d682013-08-14 23:50:16 +00001277 if (RI.Writes)
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001278 if (hasLiveDef)
Mark Laceye742d682013-08-14 23:50:16 +00001279 insertSpill(NewVReg, true, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001280 }
1281}
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001282
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001283/// spillAll - Spill all registers remaining after rematerialization.
1284void InlineSpiller::spillAll() {
1285 // Update LiveStacks now that we are committed to spilling.
1286 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1287 StackSlot = VRM.assignVirt2StackSlot(Original);
1288 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +00001289 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001290 } else
1291 StackInt = &LSS.getInterval(StackSlot);
1292
1293 if (Original != Edit->getReg())
1294 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1295
1296 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1297 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
Matthias Braun331de112013-10-10 21:28:43 +00001298 StackInt->MergeSegmentsInAsValue(LIS.getInterval(RegsToSpill[i]),
1299 StackInt->getValNumInfo(0));
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001300 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1301
1302 // Spill around uses of all RegsToSpill.
1303 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1304 spillAroundUses(RegsToSpill[i]);
1305
1306 // Hoisted spills may cause dead code.
1307 if (!DeadDefs.empty()) {
1308 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
Pete Cooper8a06af92012-04-02 22:22:53 +00001309 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001310 }
1311
1312 // Finally delete the SnippetCopies.
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001313 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1314 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(RegsToSpill[i]);
1315 MachineInstr *MI = RI.skipInstruction();) {
1316 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1317 // FIXME: Do this with a LiveRangeEdit callback.
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001318 LIS.RemoveMachineInstrFromMaps(MI);
1319 MI->eraseFromParent();
1320 }
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001321 }
1322
1323 // Delete all spilled registers.
1324 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
Pete Cooper8a06af92012-04-02 22:22:53 +00001325 Edit->eraseVirtReg(RegsToSpill[i]);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001326}
1327
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001328void InlineSpiller::spill(LiveRangeEdit &edit) {
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001329 ++NumSpilledRanges;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001330 Edit = &edit;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001331 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1332 && "Trying to spill a stack slot.");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001333 // Share a stack slot among all descendants of Original.
1334 Original = VRM.getOriginal(edit.getReg());
1335 StackSlot = VRM.getStackSlot(Original);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001336 StackInt = 0;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001337
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001338 DEBUG(dbgs() << "Inline spilling "
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001339 << MRI.getRegClass(edit.getReg())->getName()
Jakob Stoklund Olesen127cdba2012-06-15 23:47:09 +00001340 << ':' << PrintReg(edit.getReg()) << ' ' << edit.getParent()
Mark Laceye742d682013-08-14 23:50:16 +00001341 << "\nFrom original " << PrintReg(Original) << '\n');
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001342 assert(edit.getParent().isSpillable() &&
1343 "Attempting to spill already spilled value.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001344 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001345
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001346 collectRegsToSpill();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001347 analyzeSiblingValues();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001348 reMaterializeAll();
1349
1350 // Remat may handle everything.
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001351 if (!RegsToSpill.empty())
1352 spillAll();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001353
Benjamin Kramer4eed7562013-06-17 19:00:36 +00001354 Edit->calculateRegClassAndHint(MF, Loops, MBFI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001355}