Trace back through sibling copies to hoist spills and find rematerializable defs.
[oota-llvm.git] / lib / CodeGen / InlineSpiller.cpp
1 //===-------- 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
15 #define DEBUG_TYPE "regalloc"
16 #include "Spiller.h"
17 #include "LiveRangeEdit.h"
18 #include "VirtRegMap.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/LiveStackAnalysis.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31
32 using namespace llvm;
33
34 namespace {
35 class InlineSpiller : public Spiller {
36   MachineFunctionPass &Pass;
37   MachineFunction &MF;
38   LiveIntervals &LIS;
39   LiveStacks &LSS;
40   AliasAnalysis *AA;
41   MachineDominatorTree &MDT;
42   MachineLoopInfo &Loops;
43   VirtRegMap &VRM;
44   MachineFrameInfo &MFI;
45   MachineRegisterInfo &MRI;
46   const TargetInstrInfo &TII;
47   const TargetRegisterInfo &TRI;
48
49   // Variables that are valid during spill(), but used by multiple methods.
50   LiveRangeEdit *Edit;
51   const TargetRegisterClass *RC;
52   int StackSlot;
53   unsigned Original;
54
55   // All registers to spill to StackSlot, including the main register.
56   SmallVector<unsigned, 8> RegsToSpill;
57
58   // All COPY instructions to/from snippets.
59   // They are ignored since both operands refer to the same stack slot.
60   SmallPtrSet<MachineInstr*, 8> SnippetCopies;
61
62   // Values that failed to remat at some point.
63   SmallPtrSet<VNInfo*, 8> UsedValues;
64
65   // Information about a value that was defined by a copy from a sibling
66   // register.
67   struct SibValueInfo {
68     // True when all reaching defs were reloads: No spill is necessary.
69     bool AllDefsAreReloads;
70
71     // The preferred register to spill.
72     unsigned SpillReg;
73
74     // The value of SpillReg that should be spilled.
75     VNInfo *SpillVNI;
76
77     // A defining instruction that is not a sibling copy or a reload, or NULL.
78     // This can be used as a template for rematerialization.
79     MachineInstr *DefMI;
80
81     SibValueInfo(unsigned Reg, VNInfo *VNI)
82       : AllDefsAreReloads(false), SpillReg(Reg), SpillVNI(VNI), DefMI(0) {}
83   };
84
85   // Values in RegsToSpill defined by sibling copies.
86   DenseMap<VNInfo*, SibValueInfo> SibValues;
87
88   ~InlineSpiller() {}
89
90 public:
91   InlineSpiller(MachineFunctionPass &pass,
92                 MachineFunction &mf,
93                 VirtRegMap &vrm)
94     : Pass(pass),
95       MF(mf),
96       LIS(pass.getAnalysis<LiveIntervals>()),
97       LSS(pass.getAnalysis<LiveStacks>()),
98       AA(&pass.getAnalysis<AliasAnalysis>()),
99       MDT(pass.getAnalysis<MachineDominatorTree>()),
100       Loops(pass.getAnalysis<MachineLoopInfo>()),
101       VRM(vrm),
102       MFI(*mf.getFrameInfo()),
103       MRI(mf.getRegInfo()),
104       TII(*mf.getTarget().getInstrInfo()),
105       TRI(*mf.getTarget().getRegisterInfo()) {}
106
107   void spill(LiveRangeEdit &);
108
109 private:
110   bool isSnippet(const LiveInterval &SnipLI);
111   void collectRegsToSpill();
112
113   void traceSiblingValue(unsigned, VNInfo*, VNInfo*);
114   void analyzeSiblingValues();
115
116   bool reMaterializeFor(MachineBasicBlock::iterator MI);
117   void reMaterializeAll();
118
119   bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
120   bool foldMemoryOperand(MachineBasicBlock::iterator MI,
121                          const SmallVectorImpl<unsigned> &Ops,
122                          MachineInstr *LoadMI = 0);
123   void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
124   void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
125                    MachineBasicBlock::iterator MI);
126
127   void spillAroundUses(unsigned Reg);
128 };
129 }
130
131 namespace llvm {
132 Spiller *createInlineSpiller(MachineFunctionPass &pass,
133                              MachineFunction &mf,
134                              VirtRegMap &vrm) {
135   return new InlineSpiller(pass, mf, vrm);
136 }
137 }
138
139 //===----------------------------------------------------------------------===//
140 //                                Snippets
141 //===----------------------------------------------------------------------===//
142
143 // When spilling a virtual register, we also spill any snippets it is connected
144 // to. The snippets are small live ranges that only have a single real use,
145 // leftovers from live range splitting. Spilling them enables memory operand
146 // folding or tightens the live range around the single use.
147 //
148 // This minimizes register pressure and maximizes the store-to-load distance for
149 // spill slots which can be important in tight loops.
150
151 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
152 /// otherwise return 0.
153 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
154   if (!MI->isCopy())
155     return 0;
156   if (MI->getOperand(0).getSubReg() != 0)
157     return 0;
158   if (MI->getOperand(1).getSubReg() != 0)
159     return 0;
160   if (MI->getOperand(0).getReg() == Reg)
161       return MI->getOperand(1).getReg();
162   if (MI->getOperand(1).getReg() == Reg)
163       return MI->getOperand(0).getReg();
164   return 0;
165 }
166
167 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
168 /// It is assumed that SnipLI is a virtual register with the same original as
169 /// Edit->getReg().
170 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
171   unsigned Reg = Edit->getReg();
172
173   // A snippet is a tiny live range with only a single instruction using it
174   // besides copies to/from Reg or spills/fills. We accept:
175   //
176   //   %snip = COPY %Reg / FILL fi#
177   //   %snip = USE %snip
178   //   %Reg = COPY %snip / SPILL %snip, fi#
179   //
180   if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
181     return false;
182
183   MachineInstr *UseMI = 0;
184
185   // Check that all uses satisfy our criteria.
186   for (MachineRegisterInfo::reg_nodbg_iterator
187          RI = MRI.reg_nodbg_begin(SnipLI.reg);
188        MachineInstr *MI = RI.skipInstruction();) {
189
190     // Allow copies to/from Reg.
191     if (isFullCopyOf(MI, Reg))
192       continue;
193
194     // Allow stack slot loads.
195     int FI;
196     if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
197       continue;
198
199     // Allow stack slot stores.
200     if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
201       continue;
202
203     // Allow a single additional instruction.
204     if (UseMI && MI != UseMI)
205       return false;
206     UseMI = MI;
207   }
208   return true;
209 }
210
211 /// collectRegsToSpill - Collect live range snippets that only have a single
212 /// real use.
213 void InlineSpiller::collectRegsToSpill() {
214   unsigned Reg = Edit->getReg();
215
216   // Main register always spills.
217   RegsToSpill.assign(1, Reg);
218   SnippetCopies.clear();
219
220   // Snippets all have the same original, so there can't be any for an original
221   // register.
222   if (Original == Reg)
223     return;
224
225   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
226        MachineInstr *MI = RI.skipInstruction();) {
227     unsigned SnipReg = isFullCopyOf(MI, Reg);
228     if (!SnipReg)
229       continue;
230     if (!TargetRegisterInfo::isVirtualRegister(SnipReg))
231       continue;
232     if (VRM.getOriginal(SnipReg) != Original)
233       continue;
234     LiveInterval &SnipLI = LIS.getInterval(SnipReg);
235     if (!isSnippet(SnipLI))
236       continue;
237     SnippetCopies.insert(MI);
238     if (std::find(RegsToSpill.begin(), RegsToSpill.end(),
239                   SnipReg) == RegsToSpill.end())
240       RegsToSpill.push_back(SnipReg);
241
242     DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
243   }
244 }
245
246
247 //===----------------------------------------------------------------------===//
248 //                            Sibling Values
249 //===----------------------------------------------------------------------===//
250
251 // After live range splitting, some values to be spilled may be defined by
252 // copies from sibling registers. We trace the sibling copies back to the
253 // original value if it still exists. We need it for rematerialization.
254 //
255 // Even when the value can't be rematerialized, we still want to determine if
256 // the value has already been spilled, or we may want to hoist the spill from a
257 // loop.
258
259 /// traceSiblingValue - Trace a value that is about to be spilled back to the
260 /// real defining instructions by looking through sibling copies. Always stay
261 /// within the range of OrigVNI so the registers are known to carry the same
262 /// value.
263 ///
264 /// Determine if the value is defined by all reloads, so spilling isn't
265 /// necessary - the value is already in the stack slot.
266 ///
267 /// Find a defining instruction that may be a candidate for rematerialization.
268 ///
269 void InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
270                                       VNInfo *OrigVNI) {
271   DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
272                << UseVNI->id << '@' << UseVNI->def << '\n');
273   SmallPtrSet<VNInfo*, 8> Visited;
274   SmallVector<std::pair<unsigned,VNInfo*>, 8> WorkList;
275   WorkList.push_back(std::make_pair(UseReg, UseVNI));
276
277   // Best spill candidate seen so far. This must dominate UseVNI.
278   SibValueInfo SVI(UseReg, UseVNI);
279   MachineBasicBlock *UseMBB = LIS.getMBBFromIndex(UseVNI->def);
280   MachineBasicBlock *SpillMBB = UseMBB;
281   unsigned SpillDepth = Loops.getLoopDepth(SpillMBB);
282   bool SeenOrigPHI = false; // Original PHI met.
283
284   do {
285     unsigned Reg;
286     VNInfo *VNI;
287     tie(Reg, VNI) = WorkList.pop_back_val();
288     if (!Visited.insert(VNI))
289       continue;
290
291     // Is this value a better spill candidate?
292     if (VNI != SVI.SpillVNI) {
293       MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
294       if (MBB == SpillMBB) {
295         // Prefer to spill a previous value in the same block.
296         if (VNI->def < SVI.SpillVNI->def)
297           SVI.SpillReg = Reg, SVI.SpillVNI = VNI;
298       } else if (MDT.dominates(MBB, UseMBB)) {
299         // This is a valid spill location dominating UseVNI.
300         // Prefer to spill at a smaller loop depth.
301         unsigned Depth = Loops.getLoopDepth(MBB);
302         if (Depth < SpillDepth) {
303           DEBUG(dbgs() << "  spill depth " << Depth << ": " << PrintReg(Reg)
304                        << ':' << VNI->id << '@' << VNI->def << '\n');
305           SVI.SpillReg = Reg;
306           SVI.SpillVNI = VNI;
307           SpillMBB = MBB;
308           SpillDepth = Depth;
309         }
310       }
311     }
312
313     // Trace through PHI-defs created by live range splitting.
314     if (VNI->isPHIDef()) {
315       if (VNI->def == OrigVNI->def) {
316         DEBUG(dbgs() << "  orig phi value " << PrintReg(Reg) << ':'
317                      << VNI->id << '@' << VNI->def << '\n');
318         SeenOrigPHI = true;
319         continue;
320       }
321       // Get values live-out of predecessors.
322       LiveInterval &LI = LIS.getInterval(Reg);
323       MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
324       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
325              PE = MBB->pred_end(); PI != PE; ++PI) {
326         VNInfo *PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
327         if (PVNI)
328           WorkList.push_back(std::make_pair(Reg, PVNI));
329       }
330       continue;
331     }
332
333     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
334     assert(MI && "Missing def");
335
336     // Trace through sibling copies.
337     if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
338       if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
339           VRM.getOriginal(SrcReg) == Original) {
340         LiveInterval &SrcLI = LIS.getInterval(SrcReg);
341         VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
342         assert(SrcVNI && "Copy from non-existing value");
343         DEBUG(dbgs() << "  copy of " << PrintReg(SrcReg) << ':'
344                      << SrcVNI->id << '@' << SrcVNI->def << '\n');
345         WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
346         continue;
347       }
348     }
349
350     // Track reachable reloads.
351     int FI;
352     if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
353       DEBUG(dbgs() << "  reload " << PrintReg(Reg) << ':'
354                    << VNI->id << "@" << VNI->def << '\n');
355       SVI.AllDefsAreReloads = true;
356       continue;
357     }
358
359     // We have an 'original' def. Don't record trivial cases.
360     if (VNI == UseVNI) {
361       DEBUG(dbgs() << "Not a sibling copy.\n");
362       return;
363     }
364
365     // Potential remat candidate.
366     DEBUG(dbgs() << "  def " << PrintReg(Reg) << ':'
367                  << VNI->id << '@' << VNI->def << '\t' << *MI);
368     SVI.DefMI = MI;
369   } while (!WorkList.empty());
370
371   if (SeenOrigPHI || SVI.DefMI)
372     SVI.AllDefsAreReloads = false;
373
374   DEBUG({
375     if (SVI.AllDefsAreReloads)
376       dbgs() << "All defs are reloads.\n";
377     else
378       dbgs() << "Prefer to spill " << PrintReg(SVI.SpillReg) << ':'
379              << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def << '\n';
380   });
381   SibValues.insert(std::make_pair(UseVNI, SVI));
382 }
383
384 /// analyzeSiblingValues - Trace values defined by sibling copies back to
385 /// something that isn't a sibling copy.
386 void InlineSpiller::analyzeSiblingValues() {
387   SibValues.clear();
388
389   // No siblings at all?
390   if (Edit->getReg() == Original)
391     return;
392
393   LiveInterval &OrigLI = LIS.getInterval(Original);
394   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
395     unsigned Reg = RegsToSpill[i];
396     LiveInterval &LI = LIS.getInterval(Reg);
397     for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
398          VE = LI.vni_end(); VI != VE; ++VI) {
399       VNInfo *VNI = *VI;
400       if (VNI->isUnused() || !(VNI->isPHIDef() || VNI->getCopy()))
401         continue;
402       VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
403       if (OrigVNI->def != VNI->def)
404         traceSiblingValue(Reg, VNI, OrigVNI);
405     }
406   }
407 }
408
409 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
410 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
411   SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
412   VNInfo *OrigVNI = Edit->getParent().getVNInfoAt(UseIdx);
413
414   if (!OrigVNI) {
415     DEBUG(dbgs() << "\tadding <undef> flags: ");
416     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
417       MachineOperand &MO = MI->getOperand(i);
418       if (MO.isReg() && MO.isUse() && MO.getReg() == Edit->getReg())
419         MO.setIsUndef();
420     }
421     DEBUG(dbgs() << UseIdx << '\t' << *MI);
422     return true;
423   }
424
425   // FIXME: Properly remat for snippets as well.
426   if (SnippetCopies.count(MI)) {
427     UsedValues.insert(OrigVNI);
428     return false;
429   }
430
431   LiveRangeEdit::Remat RM(OrigVNI);
432   if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
433     UsedValues.insert(OrigVNI);
434     DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
435     return false;
436   }
437
438   // If the instruction also writes Edit->getReg(), it had better not require
439   // the same register for uses and defs.
440   bool Reads, Writes;
441   SmallVector<unsigned, 8> Ops;
442   tie(Reads, Writes) = MI->readsWritesVirtualRegister(Edit->getReg(), &Ops);
443   if (Writes) {
444     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
445       MachineOperand &MO = MI->getOperand(Ops[i]);
446       if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
447         UsedValues.insert(OrigVNI);
448         DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
449         return false;
450       }
451     }
452   }
453
454   // Before rematerializing into a register for a single instruction, try to
455   // fold a load into the instruction. That avoids allocating a new register.
456   if (RM.OrigMI->getDesc().canFoldAsLoad() &&
457       foldMemoryOperand(MI, Ops, RM.OrigMI)) {
458     Edit->markRematerialized(RM.ParentVNI);
459     return true;
460   }
461
462   // Alocate a new register for the remat.
463   LiveInterval &NewLI = Edit->create(MRI, LIS, VRM);
464   NewLI.markNotSpillable();
465
466   // Rematting for a copy: Set allocation hint to be the destination register.
467   if (MI->isCopy())
468     MRI.setRegAllocationHint(NewLI.reg, 0, MI->getOperand(0).getReg());
469
470   // Finally we can rematerialize OrigMI before MI.
471   SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
472                                            LIS, TII, TRI);
473   DEBUG(dbgs() << "\tremat:  " << DefIdx << '\t'
474                << *LIS.getInstructionFromIndex(DefIdx));
475
476   // Replace operands
477   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
478     MachineOperand &MO = MI->getOperand(Ops[i]);
479     if (MO.isReg() && MO.isUse() && MO.getReg() == Edit->getReg()) {
480       MO.setReg(NewLI.reg);
481       MO.setIsKill();
482     }
483   }
484   DEBUG(dbgs() << "\t        " << UseIdx << '\t' << *MI);
485
486   VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
487   NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
488   DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
489   return true;
490 }
491
492 /// reMaterializeAll - Try to rematerialize as many uses as possible,
493 /// and trim the live ranges after.
494 void InlineSpiller::reMaterializeAll() {
495   // Do a quick scan of the interval values to find if any are remattable.
496   if (!Edit->anyRematerializable(LIS, TII, AA))
497     return;
498
499   UsedValues.clear();
500
501   // Try to remat before all uses of Edit->getReg().
502   bool anyRemat = false;
503   for (MachineRegisterInfo::use_nodbg_iterator
504        RI = MRI.use_nodbg_begin(Edit->getReg());
505        MachineInstr *MI = RI.skipInstruction();)
506      anyRemat |= reMaterializeFor(MI);
507
508   if (!anyRemat)
509     return;
510
511   // Remove any values that were completely rematted.
512   bool anyRemoved = false;
513   for (LiveInterval::vni_iterator I = Edit->getParent().vni_begin(),
514        E = Edit->getParent().vni_end(); I != E; ++I) {
515     VNInfo *VNI = *I;
516     if (VNI->hasPHIKill() || !Edit->didRematerialize(VNI) ||
517         UsedValues.count(VNI))
518       continue;
519     MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
520     DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
521     LIS.RemoveMachineInstrFromMaps(DefMI);
522     VRM.RemoveMachineInstrFromMaps(DefMI);
523     DefMI->eraseFromParent();
524     VNI->def = SlotIndex();
525     anyRemoved = true;
526   }
527
528   if (!anyRemoved)
529     return;
530
531   // Removing values may cause debug uses where parent is not live.
532   for (MachineRegisterInfo::use_iterator RI = MRI.use_begin(Edit->getReg());
533        MachineInstr *MI = RI.skipInstruction();) {
534     if (!MI->isDebugValue())
535       continue;
536     // Try to preserve the debug value if parent is live immediately after it.
537     MachineBasicBlock::iterator NextMI = MI;
538     ++NextMI;
539     if (NextMI != MI->getParent()->end() && !LIS.isNotInMIMap(NextMI)) {
540       SlotIndex Idx = LIS.getInstructionIndex(NextMI);
541       VNInfo *VNI = Edit->getParent().getVNInfoAt(Idx);
542       if (VNI && (VNI->hasPHIKill() || UsedValues.count(VNI)))
543         continue;
544     }
545     DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
546     MI->eraseFromParent();
547   }
548 }
549
550 /// If MI is a load or store of StackSlot, it can be removed.
551 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
552   int FI = 0;
553   unsigned InstrReg;
554   if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
555       !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
556     return false;
557
558   // We have a stack access. Is it the right register and slot?
559   if (InstrReg != Reg || FI != StackSlot)
560     return false;
561
562   DEBUG(dbgs() << "Coalescing stack access: " << *MI);
563   LIS.RemoveMachineInstrFromMaps(MI);
564   MI->eraseFromParent();
565   return true;
566 }
567
568 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
569 /// @param MI     Instruction using or defining the current register.
570 /// @param Ops    Operand indices from readsWritesVirtualRegister().
571 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
572 /// @return       True on success, and MI will be erased.
573 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
574                                       const SmallVectorImpl<unsigned> &Ops,
575                                       MachineInstr *LoadMI) {
576   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
577   // operands.
578   SmallVector<unsigned, 8> FoldOps;
579   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
580     unsigned Idx = Ops[i];
581     MachineOperand &MO = MI->getOperand(Idx);
582     if (MO.isImplicit())
583       continue;
584     // FIXME: Teach targets to deal with subregs.
585     if (MO.getSubReg())
586       return false;
587     // We cannot fold a load instruction into a def.
588     if (LoadMI && MO.isDef())
589       return false;
590     // Tied use operands should not be passed to foldMemoryOperand.
591     if (!MI->isRegTiedToDefOperand(Idx))
592       FoldOps.push_back(Idx);
593   }
594
595   MachineInstr *FoldMI =
596                 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
597                        : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
598   if (!FoldMI)
599     return false;
600   LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
601   if (!LoadMI)
602     VRM.addSpillSlotUse(StackSlot, FoldMI);
603   MI->eraseFromParent();
604   DEBUG(dbgs() << "\tfolded: " << *FoldMI);
605   return true;
606 }
607
608 /// insertReload - Insert a reload of NewLI.reg before MI.
609 void InlineSpiller::insertReload(LiveInterval &NewLI,
610                                  MachineBasicBlock::iterator MI) {
611   MachineBasicBlock &MBB = *MI->getParent();
612   SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
613   TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot, RC, &TRI);
614   --MI; // Point to load instruction.
615   SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
616   VRM.addSpillSlotUse(StackSlot, MI);
617   DEBUG(dbgs() << "\treload:  " << LoadIdx << '\t' << *MI);
618   VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
619                                        LIS.getVNInfoAllocator());
620   NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
621 }
622
623 /// insertSpill - Insert a spill of NewLI.reg after MI.
624 void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
625                                 MachineBasicBlock::iterator MI) {
626   MachineBasicBlock &MBB = *MI->getParent();
627
628   // Get the defined value. It could be an early clobber so keep the def index.
629   SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
630   VNInfo *VNI = OldLI.getVNInfoAt(Idx);
631   assert(VNI && VNI->def.getDefIndex() == Idx && "Inconsistent VNInfo");
632   Idx = VNI->def;
633
634   TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot, RC, &TRI);
635   --MI; // Point to store instruction.
636   SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
637   VRM.addSpillSlotUse(StackSlot, MI);
638   DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
639   VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
640   NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
641 }
642
643 /// spillAroundUses - insert spill code around each use of Reg.
644 void InlineSpiller::spillAroundUses(unsigned Reg) {
645   LiveInterval &OldLI = LIS.getInterval(Reg);
646
647   // Iterate over instructions using Reg.
648   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
649        MachineInstr *MI = RI.skipInstruction();) {
650
651     // Debug values are not allowed to affect codegen.
652     if (MI->isDebugValue()) {
653       // Modify DBG_VALUE now that the value is in a spill slot.
654       uint64_t Offset = MI->getOperand(1).getImm();
655       const MDNode *MDPtr = MI->getOperand(2).getMetadata();
656       DebugLoc DL = MI->getDebugLoc();
657       if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
658                                                            Offset, MDPtr, DL)) {
659         DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
660         MachineBasicBlock *MBB = MI->getParent();
661         MBB->insert(MBB->erase(MI), NewDV);
662       } else {
663         DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
664         MI->eraseFromParent();
665       }
666       continue;
667     }
668
669     // Ignore copies to/from snippets. We'll delete them.
670     if (SnippetCopies.count(MI))
671       continue;
672
673     // Stack slot accesses may coalesce away.
674     if (coalesceStackAccess(MI, Reg))
675       continue;
676
677     // Analyze instruction.
678     bool Reads, Writes;
679     SmallVector<unsigned, 8> Ops;
680     tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
681
682     // Attempt to fold memory ops.
683     if (foldMemoryOperand(MI, Ops))
684       continue;
685
686     // Allocate interval around instruction.
687     // FIXME: Infer regclass from instruction alone.
688     LiveInterval &NewLI = Edit->create(MRI, LIS, VRM);
689     NewLI.markNotSpillable();
690
691     if (Reads)
692       insertReload(NewLI, MI);
693
694     // Rewrite instruction operands.
695     bool hasLiveDef = false;
696     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
697       MachineOperand &MO = MI->getOperand(Ops[i]);
698       MO.setReg(NewLI.reg);
699       if (MO.isUse()) {
700         if (!MI->isRegTiedToDefOperand(Ops[i]))
701           MO.setIsKill();
702       } else {
703         if (!MO.isDead())
704           hasLiveDef = true;
705       }
706     }
707
708     // FIXME: Use a second vreg if instruction has no tied ops.
709     if (Writes && hasLiveDef)
710       insertSpill(NewLI, OldLI, MI);
711
712     DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
713   }
714 }
715
716 void InlineSpiller::spill(LiveRangeEdit &edit) {
717   Edit = &edit;
718   assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
719          && "Trying to spill a stack slot.");
720
721   // Share a stack slot among all descendants of Original.
722   Original = VRM.getOriginal(edit.getReg());
723   StackSlot = VRM.getStackSlot(Original);
724
725   DEBUG(dbgs() << "Inline spilling "
726                << MRI.getRegClass(edit.getReg())->getName()
727                << ':' << edit.getParent() << "\nFrom original "
728                << LIS.getInterval(Original) << '\n');
729   assert(edit.getParent().isSpillable() &&
730          "Attempting to spill already spilled value.");
731
732   collectRegsToSpill();
733
734   analyzeSiblingValues();
735
736   reMaterializeAll();
737
738   // Remat may handle everything.
739   if (Edit->getParent().empty())
740     return;
741
742   RC = MRI.getRegClass(edit.getReg());
743
744   if (StackSlot == VirtRegMap::NO_STACK_SLOT)
745     StackSlot = VRM.assignVirt2StackSlot(Original);
746
747   if (Original != edit.getReg())
748     VRM.assignVirt2StackSlot(edit.getReg(), StackSlot);
749
750   // Update LiveStacks now that we are committed to spilling.
751   LiveInterval &stacklvr = LSS.getOrCreateInterval(StackSlot, RC);
752   if (!stacklvr.hasAtLeastOneValue())
753     stacklvr.getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
754   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
755     stacklvr.MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
756                                   stacklvr.getValNumInfo(0));
757
758   // Spill around uses of all RegsToSpill.
759   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
760     spillAroundUses(RegsToSpill[i]);
761
762   // Finally delete the SnippetCopies.
763   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(edit.getReg());
764        MachineInstr *MI = RI.skipInstruction();) {
765     assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
766     // FIXME: Do this with a LiveRangeEdit callback.
767     VRM.RemoveMachineInstrFromMaps(MI);
768     LIS.RemoveMachineInstrFromMaps(MI);
769     MI->eraseFromParent();
770   }
771
772   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
773     edit.eraseVirtReg(RegsToSpill[i], LIS);
774 }