d5c1da9d4b0263790433a7c1d4430c0390db8f15
[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/ADT/Statistic.h"
20 #include "llvm/ADT/TinyPtrVector.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/LiveStackAnalysis.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33
34 using namespace llvm;
35
36 STATISTIC(NumSpilledRanges,   "Number of spilled live ranges");
37 STATISTIC(NumSnippets,        "Number of snippets included in spills");
38 STATISTIC(NumSpills,          "Number of spills inserted");
39 STATISTIC(NumReloads,         "Number of reloads inserted");
40 STATISTIC(NumFolded,          "Number of folded stack accesses");
41 STATISTIC(NumFoldedLoads,     "Number of folded loads");
42 STATISTIC(NumRemats,          "Number of rematerialized defs for spilling");
43 STATISTIC(NumOmitReloadSpill, "Number of omitted spills after reloads");
44 STATISTIC(NumHoistLocal,      "Number of locally hoisted spills");
45 STATISTIC(NumHoistGlobal,     "Number of globally hoisted spills");
46 STATISTIC(NumRedundantSpills, "Number of redundant spills identified");
47
48 namespace {
49 class InlineSpiller : public Spiller {
50   MachineFunctionPass &Pass;
51   MachineFunction &MF;
52   LiveIntervals &LIS;
53   LiveStacks &LSS;
54   AliasAnalysis *AA;
55   MachineDominatorTree &MDT;
56   MachineLoopInfo &Loops;
57   VirtRegMap &VRM;
58   MachineFrameInfo &MFI;
59   MachineRegisterInfo &MRI;
60   const TargetInstrInfo &TII;
61   const TargetRegisterInfo &TRI;
62
63   // Variables that are valid during spill(), but used by multiple methods.
64   LiveRangeEdit *Edit;
65   LiveInterval *StackInt;
66   int StackSlot;
67   unsigned Original;
68
69   // All registers to spill to StackSlot, including the main register.
70   SmallVector<unsigned, 8> RegsToSpill;
71
72   // All COPY instructions to/from snippets.
73   // They are ignored since both operands refer to the same stack slot.
74   SmallPtrSet<MachineInstr*, 8> SnippetCopies;
75
76   // Values that failed to remat at some point.
77   SmallPtrSet<VNInfo*, 8> UsedValues;
78
79 public:
80   // Information about a value that was defined by a copy from a sibling
81   // register.
82   struct SibValueInfo {
83     // True when all reaching defs were reloads: No spill is necessary.
84     bool AllDefsAreReloads;
85
86     // True when value is defined by an original PHI not from splitting.
87     bool DefByOrigPHI;
88
89     // The preferred register to spill.
90     unsigned SpillReg;
91
92     // The value of SpillReg that should be spilled.
93     VNInfo *SpillVNI;
94
95     // The block where SpillVNI should be spilled. Currently, this must be the
96     // block containing SpillVNI->def.
97     MachineBasicBlock *SpillMBB;
98
99     // A defining instruction that is not a sibling copy or a reload, or NULL.
100     // This can be used as a template for rematerialization.
101     MachineInstr *DefMI;
102
103     // List of values that depend on this one.  These values are actually the
104     // same, but live range splitting has placed them in different registers,
105     // or SSA update needed to insert PHI-defs to preserve SSA form.  This is
106     // copies of the current value and phi-kills.  Usually only phi-kills cause
107     // more than one dependent value.
108     TinyPtrVector<VNInfo*> Deps;
109
110     SibValueInfo(unsigned Reg, VNInfo *VNI)
111       : AllDefsAreReloads(true), DefByOrigPHI(false),
112         SpillReg(Reg), SpillVNI(VNI), SpillMBB(0), DefMI(0) {}
113
114     // Returns true when a def has been found.
115     bool hasDef() const { return DefByOrigPHI || DefMI; }
116   };
117
118 private:
119   // Values in RegsToSpill defined by sibling copies.
120   typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
121   SibValueMap SibValues;
122
123   // Values live-out from basic blocks.  This is the same as
124   // LI.getVNInfoAt(LIS.getMBBEndIdx(MBB).getPrevSlot())
125   typedef DenseMap<MachineBasicBlock*, VNInfo*> LiveOutMap;
126   LiveOutMap LiveOutValues;
127
128   // Dead defs generated during spilling.
129   SmallVector<MachineInstr*, 8> DeadDefs;
130
131   ~InlineSpiller() {}
132
133 public:
134   InlineSpiller(MachineFunctionPass &pass,
135                 MachineFunction &mf,
136                 VirtRegMap &vrm)
137     : Pass(pass),
138       MF(mf),
139       LIS(pass.getAnalysis<LiveIntervals>()),
140       LSS(pass.getAnalysis<LiveStacks>()),
141       AA(&pass.getAnalysis<AliasAnalysis>()),
142       MDT(pass.getAnalysis<MachineDominatorTree>()),
143       Loops(pass.getAnalysis<MachineLoopInfo>()),
144       VRM(vrm),
145       MFI(*mf.getFrameInfo()),
146       MRI(mf.getRegInfo()),
147       TII(*mf.getTarget().getInstrInfo()),
148       TRI(*mf.getTarget().getRegisterInfo()) {}
149
150   void spill(LiveRangeEdit &);
151
152 private:
153   bool isSnippet(const LiveInterval &SnipLI);
154   void collectRegsToSpill();
155
156   bool isRegToSpill(unsigned Reg) {
157     return std::find(RegsToSpill.begin(),
158                      RegsToSpill.end(), Reg) != RegsToSpill.end();
159   }
160
161   bool isSibling(unsigned Reg);
162   MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
163   void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = 0);
164   void analyzeSiblingValues();
165
166   bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
167   void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
168
169   void markValueUsed(LiveInterval*, VNInfo*);
170   bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
171   void reMaterializeAll();
172
173   bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
174   bool foldMemoryOperand(MachineBasicBlock::iterator MI,
175                          const SmallVectorImpl<unsigned> &Ops,
176                          MachineInstr *LoadMI = 0);
177   void insertReload(LiveInterval &NewLI, SlotIndex,
178                     MachineBasicBlock::iterator MI);
179   void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
180                    SlotIndex, MachineBasicBlock::iterator MI);
181
182   void spillAroundUses(unsigned Reg);
183   void spillAll();
184 };
185 }
186
187 namespace llvm {
188 Spiller *createInlineSpiller(MachineFunctionPass &pass,
189                              MachineFunction &mf,
190                              VirtRegMap &vrm) {
191   return new InlineSpiller(pass, mf, vrm);
192 }
193 }
194
195 //===----------------------------------------------------------------------===//
196 //                                Snippets
197 //===----------------------------------------------------------------------===//
198
199 // When spilling a virtual register, we also spill any snippets it is connected
200 // to. The snippets are small live ranges that only have a single real use,
201 // leftovers from live range splitting. Spilling them enables memory operand
202 // folding or tightens the live range around the single use.
203 //
204 // This minimizes register pressure and maximizes the store-to-load distance for
205 // spill slots which can be important in tight loops.
206
207 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
208 /// otherwise return 0.
209 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
210   if (!MI->isFullCopy())
211     return 0;
212   if (MI->getOperand(0).getReg() == Reg)
213       return MI->getOperand(1).getReg();
214   if (MI->getOperand(1).getReg() == Reg)
215       return MI->getOperand(0).getReg();
216   return 0;
217 }
218
219 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
220 /// It is assumed that SnipLI is a virtual register with the same original as
221 /// Edit->getReg().
222 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
223   unsigned Reg = Edit->getReg();
224
225   // A snippet is a tiny live range with only a single instruction using it
226   // besides copies to/from Reg or spills/fills. We accept:
227   //
228   //   %snip = COPY %Reg / FILL fi#
229   //   %snip = USE %snip
230   //   %Reg = COPY %snip / SPILL %snip, fi#
231   //
232   if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
233     return false;
234
235   MachineInstr *UseMI = 0;
236
237   // Check that all uses satisfy our criteria.
238   for (MachineRegisterInfo::reg_nodbg_iterator
239          RI = MRI.reg_nodbg_begin(SnipLI.reg);
240        MachineInstr *MI = RI.skipInstruction();) {
241
242     // Allow copies to/from Reg.
243     if (isFullCopyOf(MI, Reg))
244       continue;
245
246     // Allow stack slot loads.
247     int FI;
248     if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
249       continue;
250
251     // Allow stack slot stores.
252     if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
253       continue;
254
255     // Allow a single additional instruction.
256     if (UseMI && MI != UseMI)
257       return false;
258     UseMI = MI;
259   }
260   return true;
261 }
262
263 /// collectRegsToSpill - Collect live range snippets that only have a single
264 /// real use.
265 void InlineSpiller::collectRegsToSpill() {
266   unsigned Reg = Edit->getReg();
267
268   // Main register always spills.
269   RegsToSpill.assign(1, Reg);
270   SnippetCopies.clear();
271
272   // Snippets all have the same original, so there can't be any for an original
273   // register.
274   if (Original == Reg)
275     return;
276
277   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
278        MachineInstr *MI = RI.skipInstruction();) {
279     unsigned SnipReg = isFullCopyOf(MI, Reg);
280     if (!isSibling(SnipReg))
281       continue;
282     LiveInterval &SnipLI = LIS.getInterval(SnipReg);
283     if (!isSnippet(SnipLI))
284       continue;
285     SnippetCopies.insert(MI);
286     if (isRegToSpill(SnipReg))
287       continue;
288     RegsToSpill.push_back(SnipReg);
289     DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
290     ++NumSnippets;
291   }
292 }
293
294
295 //===----------------------------------------------------------------------===//
296 //                            Sibling Values
297 //===----------------------------------------------------------------------===//
298
299 // After live range splitting, some values to be spilled may be defined by
300 // copies from sibling registers. We trace the sibling copies back to the
301 // original value if it still exists. We need it for rematerialization.
302 //
303 // Even when the value can't be rematerialized, we still want to determine if
304 // the value has already been spilled, or we may want to hoist the spill from a
305 // loop.
306
307 bool InlineSpiller::isSibling(unsigned Reg) {
308   return TargetRegisterInfo::isVirtualRegister(Reg) &&
309            VRM.getOriginal(Reg) == Original;
310 }
311
312 #ifndef NDEBUG
313 static raw_ostream &operator<<(raw_ostream &OS,
314                                const InlineSpiller::SibValueInfo &SVI) {
315   OS << "spill " << PrintReg(SVI.SpillReg) << ':'
316      << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
317   if (SVI.AllDefsAreReloads)
318     OS << " all-reloads";
319   if (SVI.DefByOrigPHI)
320     OS << " orig-phi";
321   if (SVI.DefMI)
322     OS << " def: " << *SVI.DefMI;
323   else
324     OS << '\n';
325   return OS;
326 }
327 #endif
328
329 /// propagateSiblingValue - Propagate the value in SVI to dependents if it is
330 /// known.  Otherwise remember the dependency for later.
331 ///
332 /// @param SVI SibValues entry to propagate.
333 /// @param VNI Dependent value, or NULL to propagate to all saved dependents.
334 void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVI,
335                                           VNInfo *VNI) {
336   SibValueInfo &SV = SVI->second;
337
338   if (!SV.SpillMBB)
339     SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
340
341   // Should this value be propagated as a preferred spill candidate?  We don't
342   // propagate values of registers that are about to spill.
343   bool PropSpill = !isRegToSpill(SV.SpillReg);
344   unsigned SpillDepth = ~0u;
345
346   // Further values that need to be updated.
347   SmallVector<VNInfo*, 8> WorkList;
348
349   // Defer propagation if the value is not known yet.
350   if (VNI) {
351     SV.Deps.push_back(VNI);
352     // Don't propagate to other dependents than VNI. SVI hasn't changed.
353     WorkList.push_back(VNI);
354   } else {
355     // No VNI given, update all Deps.
356     WorkList.append(SV.Deps.begin(), SV.Deps.end());
357   }
358
359   // Has the value been completely determined yet?  If not, defer propagation.
360   if (!SV.hasDef())
361     return;
362
363   while (!WorkList.empty()) {
364     SibValueMap::iterator DepSVI = SibValues.find(WorkList.pop_back_val());
365     assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
366     SibValueInfo &DepSV = DepSVI->second;
367     bool Changed = false;
368
369     if (!DepSV.SpillMBB)
370       DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
371
372     // Propagate defining instruction.
373     if (!DepSV.hasDef()) {
374       Changed = true;
375       DepSV.DefMI = SV.DefMI;
376       DepSV.DefByOrigPHI = SV.DefByOrigPHI;
377     }
378
379     // Propagate AllDefsAreReloads.  For PHI values, this computes an AND of
380     // all predecessors.
381     if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
382       Changed = true;
383       DepSV.AllDefsAreReloads = false;
384     }
385
386     // Propagate best spill value.
387     if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
388       if (SV.SpillMBB == DepSV.SpillMBB) {
389         // DepSV is in the same block.  Hoist when dominated.
390         if (SV.SpillVNI->def < DepSV.SpillVNI->def) {
391           // This is an alternative def earlier in the same MBB.
392           // Hoist the spill as far as possible in SpillMBB. This can ease
393           // register pressure:
394           //
395           //   x = def
396           //   y = use x
397           //   s = copy x
398           //
399           // Hoisting the spill of s to immediately after the def removes the
400           // interference between x and y:
401           //
402           //   x = def
403           //   spill x
404           //   y = use x<kill>
405           //
406           Changed = true;
407           DepSV.SpillReg = SV.SpillReg;
408           DepSV.SpillVNI = SV.SpillVNI;
409           DepSV.SpillMBB = SV.SpillMBB;
410         }
411       } else {
412         // DepSV is in a different block.
413         if (SpillDepth == ~0u)
414           SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
415
416         // Also hoist spills to blocks with smaller loop depth, but make sure
417         // that the new value dominates.  Non-phi dependents are always
418         // dominated, phis need checking.
419         if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
420             (!DepSVI->first->isPHIDef() ||
421              MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
422           Changed = true;
423           DepSV.SpillReg = SV.SpillReg;
424           DepSV.SpillVNI = SV.SpillVNI;
425           DepSV.SpillMBB = SV.SpillMBB;
426         }
427       }
428     }
429
430     if (!Changed)
431       continue;
432
433     // Something changed in DepSVI. Propagate to dependents.
434     WorkList.append(DepSV.Deps.begin(), DepSV.Deps.end());
435
436     DEBUG(dbgs() << "  update " << DepSVI->first->id << '@'
437                  << DepSVI->first->def << " to:\t" << DepSV);
438   }
439 }
440
441 /// traceSiblingValue - Trace a value that is about to be spilled back to the
442 /// real defining instructions by looking through sibling copies. Always stay
443 /// within the range of OrigVNI so the registers are known to carry the same
444 /// value.
445 ///
446 /// Determine if the value is defined by all reloads, so spilling isn't
447 /// necessary - the value is already in the stack slot.
448 ///
449 /// Return a defining instruction that may be a candidate for rematerialization.
450 ///
451 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
452                                                VNInfo *OrigVNI) {
453   // Check if a cached value already exists.
454   SibValueMap::iterator SVI;
455   bool Inserted;
456   tie(SVI, Inserted) =
457     SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
458   if (!Inserted) {
459     DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
460                  << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
461     return SVI->second.DefMI;
462   }
463
464   DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
465                << UseVNI->id << '@' << UseVNI->def << '\n');
466
467   // List of (Reg, VNI) that have been inserted into SibValues, but need to be
468   // processed.
469   SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
470   WorkList.push_back(std::make_pair(UseReg, UseVNI));
471
472   do {
473     unsigned Reg;
474     VNInfo *VNI;
475     tie(Reg, VNI) = WorkList.pop_back_val();
476     DEBUG(dbgs() << "  " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
477                  << ":\t");
478
479     // First check if this value has already been computed.
480     SVI = SibValues.find(VNI);
481     assert(SVI != SibValues.end() && "Missing SibValues entry");
482
483     // Trace through PHI-defs created by live range splitting.
484     if (VNI->isPHIDef()) {
485       if (VNI->def == OrigVNI->def) {
486         DEBUG(dbgs() << "orig phi value\n");
487         SVI->second.DefByOrigPHI = true;
488         SVI->second.AllDefsAreReloads = false;
489         propagateSiblingValue(SVI);
490         continue;
491       }
492       // Get values live-out of predecessors.
493       LiveInterval &LI = LIS.getInterval(Reg);
494       MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
495       DEBUG(dbgs() << "split phi value, check " << MBB->pred_size()
496                    << " preds\n");
497       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
498              PE = MBB->pred_end(); PI != PE; ++PI) {
499         // Use a cache of block live-out values.  This is faster than using
500         // getVNInfoAt on complex intervals.
501         VNInfo *&PVNI = LiveOutValues[*PI];
502         if (!PVNI)
503           PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
504         if (!PVNI)
505           continue;
506         // Known predecessor value? Try an insertion.
507         tie(SVI, Inserted) =
508           SibValues.insert(std::make_pair(PVNI, SibValueInfo(Reg, PVNI)));
509         // This is the first time we see PVNI, add it to the worklist.
510         if (Inserted)
511           WorkList.push_back(std::make_pair(Reg, PVNI));
512         propagateSiblingValue(SVI, VNI);
513       }
514       // Next work list item.
515       continue;
516     }
517
518     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
519     assert(MI && "Missing def");
520
521     // Trace through sibling copies.
522     if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
523       if (isSibling(SrcReg)) {
524         LiveInterval &SrcLI = LIS.getInterval(SrcReg);
525         VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
526         assert(SrcVNI && "Copy from non-existing value");
527         DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
528                      << SrcVNI->id << '@' << SrcVNI->def << '\n');
529         // Known sibling source value? Try an insertion.
530         tie(SVI, Inserted) = SibValues.insert(std::make_pair(SrcVNI,
531                                                  SibValueInfo(SrcReg, SrcVNI)));
532         // This is the first time we see Src, add it to the worklist.
533         if (Inserted)
534           WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
535         propagateSiblingValue(SVI, VNI);
536         // Next work list item.
537         continue;
538       }
539     }
540
541     // Track reachable reloads.
542     SVI->second.DefMI = MI;
543     SVI->second.SpillMBB = MI->getParent();
544     int FI;
545     if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
546       DEBUG(dbgs() << "reload\n");
547       propagateSiblingValue(SVI);
548       // Next work list item.
549       continue;
550     }
551
552     // Potential remat candidate.
553     DEBUG(dbgs() << "def " << *MI);
554     SVI->second.AllDefsAreReloads = false;
555     propagateSiblingValue(SVI);
556   } while (!WorkList.empty());
557
558   // Look up the value we were looking for.  We already did this lokup at the
559   // top of the function, but SibValues may have been invalidated.
560   SVI = SibValues.find(UseVNI);
561   assert(SVI != SibValues.end() && "Didn't compute requested info");
562   DEBUG(dbgs() << "  traced to:\t" << SVI->second);
563   return SVI->second.DefMI;
564 }
565
566 /// analyzeSiblingValues - Trace values defined by sibling copies back to
567 /// something that isn't a sibling copy.
568 ///
569 /// Keep track of values that may be rematerializable.
570 void InlineSpiller::analyzeSiblingValues() {
571   SibValues.clear();
572   LiveOutValues.clear();
573
574   // No siblings at all?
575   if (Edit->getReg() == Original)
576     return;
577
578   LiveInterval &OrigLI = LIS.getInterval(Original);
579   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
580     unsigned Reg = RegsToSpill[i];
581     LiveInterval &LI = LIS.getInterval(Reg);
582     for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
583          VE = LI.vni_end(); VI != VE; ++VI) {
584       VNInfo *VNI = *VI;
585       if (VNI->isUnused())
586         continue;
587       MachineInstr *DefMI = 0;
588       // Check possible sibling copies.
589       if (VNI->isPHIDef() || VNI->getCopy()) {
590         VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
591         assert(OrigVNI && "Def outside original live range");
592         if (OrigVNI->def != VNI->def)
593           DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
594       }
595       if (!DefMI && !VNI->isPHIDef())
596         DefMI = LIS.getInstructionFromIndex(VNI->def);
597       if (DefMI && Edit->checkRematerializable(VNI, DefMI, TII, AA)) {
598         DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
599                      << VNI->def << " may remat from " << *DefMI);
600       }
601     }
602   }
603 }
604
605 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
606 /// a spill at a better location.
607 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
608   SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
609   VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
610   assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
611   SibValueMap::iterator I = SibValues.find(VNI);
612   if (I == SibValues.end())
613     return false;
614
615   const SibValueInfo &SVI = I->second;
616
617   // Let the normal folding code deal with the boring case.
618   if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
619     return false;
620
621   // SpillReg may have been deleted by remat and DCE.
622   if (!LIS.hasInterval(SVI.SpillReg)) {
623     DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
624     SibValues.erase(I);
625     return false;
626   }
627
628   LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
629   if (!SibLI.containsValue(SVI.SpillVNI)) {
630     DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
631     SibValues.erase(I);
632     return false;
633   }
634
635   // Conservatively extend the stack slot range to the range of the original
636   // value. We may be able to do better with stack slot coloring by being more
637   // careful here.
638   assert(StackInt && "No stack slot assigned yet.");
639   LiveInterval &OrigLI = LIS.getInterval(Original);
640   VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
641   StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
642   DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
643                << *StackInt << '\n');
644
645   // Already spilled everywhere.
646   if (SVI.AllDefsAreReloads) {
647     DEBUG(dbgs() << "\tno spill needed: " << SVI);
648     ++NumOmitReloadSpill;
649     return true;
650   }
651   // We are going to spill SVI.SpillVNI immediately after its def, so clear out
652   // any later spills of the same value.
653   eliminateRedundantSpills(SibLI, SVI.SpillVNI);
654
655   MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
656   MachineBasicBlock::iterator MII;
657   if (SVI.SpillVNI->isPHIDef())
658     MII = MBB->SkipPHIsAndLabels(MBB->begin());
659   else {
660     MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
661     assert(DefMI && "Defining instruction disappeared");
662     MII = DefMI;
663     ++MII;
664   }
665   // Insert spill without kill flag immediately after def.
666   TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
667                           MRI.getRegClass(SVI.SpillReg), &TRI);
668   --MII; // Point to store instruction.
669   LIS.InsertMachineInstrInMaps(MII);
670   VRM.addSpillSlotUse(StackSlot, MII);
671   DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
672
673   if (MBB == CopyMI->getParent())
674     ++NumHoistLocal;
675   else
676     ++NumHoistGlobal;
677   return true;
678 }
679
680 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
681 /// redundant spills of this value in SLI.reg and sibling copies.
682 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
683   assert(VNI && "Missing value");
684   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
685   WorkList.push_back(std::make_pair(&SLI, VNI));
686   assert(StackInt && "No stack slot assigned yet.");
687
688   do {
689     LiveInterval *LI;
690     tie(LI, VNI) = WorkList.pop_back_val();
691     unsigned Reg = LI->reg;
692     DEBUG(dbgs() << "Checking redundant spills for "
693                  << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
694
695     // Regs to spill are taken care of.
696     if (isRegToSpill(Reg))
697       continue;
698
699     // Add all of VNI's live range to StackInt.
700     StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
701     DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
702
703     // Find all spills and copies of VNI.
704     for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
705          MachineInstr *MI = UI.skipInstruction();) {
706       if (!MI->isCopy() && !MI->getDesc().mayStore())
707         continue;
708       SlotIndex Idx = LIS.getInstructionIndex(MI);
709       if (LI->getVNInfoAt(Idx) != VNI)
710         continue;
711
712       // Follow sibling copies down the dominator tree.
713       if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
714         if (isSibling(DstReg)) {
715            LiveInterval &DstLI = LIS.getInterval(DstReg);
716            VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
717            assert(DstVNI && "Missing defined value");
718            assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
719            WorkList.push_back(std::make_pair(&DstLI, DstVNI));
720         }
721         continue;
722       }
723
724       // Erase spills.
725       int FI;
726       if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
727         DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
728         // eliminateDeadDefs won't normally remove stores, so switch opcode.
729         MI->setDesc(TII.get(TargetOpcode::KILL));
730         DeadDefs.push_back(MI);
731         ++NumRedundantSpills;
732       }
733     }
734   } while (!WorkList.empty());
735 }
736
737
738 //===----------------------------------------------------------------------===//
739 //                            Rematerialization
740 //===----------------------------------------------------------------------===//
741
742 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
743 /// instruction cannot be eliminated. See through snippet copies
744 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
745   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
746   WorkList.push_back(std::make_pair(LI, VNI));
747   do {
748     tie(LI, VNI) = WorkList.pop_back_val();
749     if (!UsedValues.insert(VNI))
750       continue;
751
752     if (VNI->isPHIDef()) {
753       MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
754       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
755              PE = MBB->pred_end(); PI != PE; ++PI) {
756         VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
757         if (PVNI)
758           WorkList.push_back(std::make_pair(LI, PVNI));
759       }
760       continue;
761     }
762
763     // Follow snippet copies.
764     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
765     if (!SnippetCopies.count(MI))
766       continue;
767     LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
768     assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
769     VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex());
770     assert(SnipVNI && "Snippet undefined before copy");
771     WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
772   } while (!WorkList.empty());
773 }
774
775 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
776 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
777                                      MachineBasicBlock::iterator MI) {
778   SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
779   VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
780
781   if (!ParentVNI) {
782     DEBUG(dbgs() << "\tadding <undef> flags: ");
783     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
784       MachineOperand &MO = MI->getOperand(i);
785       if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
786         MO.setIsUndef();
787     }
788     DEBUG(dbgs() << UseIdx << '\t' << *MI);
789     return true;
790   }
791
792   if (SnippetCopies.count(MI))
793     return false;
794
795   // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
796   LiveRangeEdit::Remat RM(ParentVNI);
797   SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
798   if (SibI != SibValues.end())
799     RM.OrigMI = SibI->second.DefMI;
800   if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
801     markValueUsed(&VirtReg, ParentVNI);
802     DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
803     return false;
804   }
805
806   // If the instruction also writes VirtReg.reg, it had better not require the
807   // same register for uses and defs.
808   bool Reads, Writes;
809   SmallVector<unsigned, 8> Ops;
810   tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
811   if (Writes) {
812     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
813       MachineOperand &MO = MI->getOperand(Ops[i]);
814       if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
815         markValueUsed(&VirtReg, ParentVNI);
816         DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
817         return false;
818       }
819     }
820   }
821
822   // Before rematerializing into a register for a single instruction, try to
823   // fold a load into the instruction. That avoids allocating a new register.
824   if (RM.OrigMI->getDesc().canFoldAsLoad() &&
825       foldMemoryOperand(MI, Ops, RM.OrigMI)) {
826     Edit->markRematerialized(RM.ParentVNI);
827     ++NumFoldedLoads;
828     return true;
829   }
830
831   // Alocate a new register for the remat.
832   LiveInterval &NewLI = Edit->createFrom(Original, LIS, VRM);
833   NewLI.markNotSpillable();
834
835   // Finally we can rematerialize OrigMI before MI.
836   SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
837                                            LIS, TII, TRI);
838   DEBUG(dbgs() << "\tremat:  " << DefIdx << '\t'
839                << *LIS.getInstructionFromIndex(DefIdx));
840
841   // Replace operands
842   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
843     MachineOperand &MO = MI->getOperand(Ops[i]);
844     if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
845       MO.setReg(NewLI.reg);
846       MO.setIsKill();
847     }
848   }
849   DEBUG(dbgs() << "\t        " << UseIdx << '\t' << *MI);
850
851   VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
852   NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
853   DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
854   ++NumRemats;
855   return true;
856 }
857
858 /// reMaterializeAll - Try to rematerialize as many uses as possible,
859 /// and trim the live ranges after.
860 void InlineSpiller::reMaterializeAll() {
861   // analyzeSiblingValues has already tested all relevant defining instructions.
862   if (!Edit->anyRematerializable(LIS, TII, AA))
863     return;
864
865   UsedValues.clear();
866
867   // Try to remat before all uses of snippets.
868   bool anyRemat = false;
869   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
870     unsigned Reg = RegsToSpill[i];
871     LiveInterval &LI = LIS.getInterval(Reg);
872     for (MachineRegisterInfo::use_nodbg_iterator
873          RI = MRI.use_nodbg_begin(Reg);
874          MachineInstr *MI = RI.skipInstruction();)
875       anyRemat |= reMaterializeFor(LI, MI);
876   }
877   if (!anyRemat)
878     return;
879
880   // Remove any values that were completely rematted.
881   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
882     unsigned Reg = RegsToSpill[i];
883     LiveInterval &LI = LIS.getInterval(Reg);
884     for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
885          I != E; ++I) {
886       VNInfo *VNI = *I;
887       if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
888         continue;
889       MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
890       MI->addRegisterDead(Reg, &TRI);
891       if (!MI->allDefsAreDead())
892         continue;
893       DEBUG(dbgs() << "All defs dead: " << *MI);
894       DeadDefs.push_back(MI);
895     }
896   }
897
898   // Eliminate dead code after remat. Note that some snippet copies may be
899   // deleted here.
900   if (DeadDefs.empty())
901     return;
902   DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
903   Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
904
905   // Get rid of deleted and empty intervals.
906   for (unsigned i = RegsToSpill.size(); i != 0; --i) {
907     unsigned Reg = RegsToSpill[i-1];
908     if (!LIS.hasInterval(Reg)) {
909       RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
910       continue;
911     }
912     LiveInterval &LI = LIS.getInterval(Reg);
913     if (!LI.empty())
914       continue;
915     Edit->eraseVirtReg(Reg, LIS);
916     RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
917   }
918   DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
919 }
920
921
922 //===----------------------------------------------------------------------===//
923 //                                 Spilling
924 //===----------------------------------------------------------------------===//
925
926 /// If MI is a load or store of StackSlot, it can be removed.
927 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
928   int FI = 0;
929   unsigned InstrReg;
930   if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
931       !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
932     return false;
933
934   // We have a stack access. Is it the right register and slot?
935   if (InstrReg != Reg || FI != StackSlot)
936     return false;
937
938   DEBUG(dbgs() << "Coalescing stack access: " << *MI);
939   LIS.RemoveMachineInstrFromMaps(MI);
940   MI->eraseFromParent();
941   return true;
942 }
943
944 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
945 /// @param MI     Instruction using or defining the current register.
946 /// @param Ops    Operand indices from readsWritesVirtualRegister().
947 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
948 /// @return       True on success, and MI will be erased.
949 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
950                                       const SmallVectorImpl<unsigned> &Ops,
951                                       MachineInstr *LoadMI) {
952   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
953   // operands.
954   SmallVector<unsigned, 8> FoldOps;
955   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
956     unsigned Idx = Ops[i];
957     MachineOperand &MO = MI->getOperand(Idx);
958     if (MO.isImplicit())
959       continue;
960     // FIXME: Teach targets to deal with subregs.
961     if (MO.getSubReg())
962       return false;
963     // We cannot fold a load instruction into a def.
964     if (LoadMI && MO.isDef())
965       return false;
966     // Tied use operands should not be passed to foldMemoryOperand.
967     if (!MI->isRegTiedToDefOperand(Idx))
968       FoldOps.push_back(Idx);
969   }
970
971   MachineInstr *FoldMI =
972                 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
973                        : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
974   if (!FoldMI)
975     return false;
976   LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
977   if (!LoadMI)
978     VRM.addSpillSlotUse(StackSlot, FoldMI);
979   MI->eraseFromParent();
980   DEBUG(dbgs() << "\tfolded: " << *FoldMI);
981   ++NumFolded;
982   return true;
983 }
984
985 /// insertReload - Insert a reload of NewLI.reg before MI.
986 void InlineSpiller::insertReload(LiveInterval &NewLI,
987                                  SlotIndex Idx,
988                                  MachineBasicBlock::iterator MI) {
989   MachineBasicBlock &MBB = *MI->getParent();
990   TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
991                            MRI.getRegClass(NewLI.reg), &TRI);
992   --MI; // Point to load instruction.
993   SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
994   VRM.addSpillSlotUse(StackSlot, MI);
995   DEBUG(dbgs() << "\treload:  " << LoadIdx << '\t' << *MI);
996   VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
997                                        LIS.getVNInfoAllocator());
998   NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
999   ++NumReloads;
1000 }
1001
1002 /// insertSpill - Insert a spill of NewLI.reg after MI.
1003 void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
1004                                 SlotIndex Idx, MachineBasicBlock::iterator MI) {
1005   MachineBasicBlock &MBB = *MI->getParent();
1006   TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
1007                           MRI.getRegClass(NewLI.reg), &TRI);
1008   --MI; // Point to store instruction.
1009   SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
1010   VRM.addSpillSlotUse(StackSlot, MI);
1011   DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
1012   VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
1013   NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
1014   ++NumSpills;
1015 }
1016
1017 /// spillAroundUses - insert spill code around each use of Reg.
1018 void InlineSpiller::spillAroundUses(unsigned Reg) {
1019   DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
1020   LiveInterval &OldLI = LIS.getInterval(Reg);
1021
1022   // Iterate over instructions using Reg.
1023   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
1024        MachineInstr *MI = RI.skipInstruction();) {
1025
1026     // Debug values are not allowed to affect codegen.
1027     if (MI->isDebugValue()) {
1028       // Modify DBG_VALUE now that the value is in a spill slot.
1029       uint64_t Offset = MI->getOperand(1).getImm();
1030       const MDNode *MDPtr = MI->getOperand(2).getMetadata();
1031       DebugLoc DL = MI->getDebugLoc();
1032       if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
1033                                                            Offset, MDPtr, DL)) {
1034         DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1035         MachineBasicBlock *MBB = MI->getParent();
1036         MBB->insert(MBB->erase(MI), NewDV);
1037       } else {
1038         DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
1039         MI->eraseFromParent();
1040       }
1041       continue;
1042     }
1043
1044     // Ignore copies to/from snippets. We'll delete them.
1045     if (SnippetCopies.count(MI))
1046       continue;
1047
1048     // Stack slot accesses may coalesce away.
1049     if (coalesceStackAccess(MI, Reg))
1050       continue;
1051
1052     // Analyze instruction.
1053     bool Reads, Writes;
1054     SmallVector<unsigned, 8> Ops;
1055     tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
1056
1057     // Find the slot index where this instruction reads and writes OldLI.
1058     // This is usually the def slot, except for tied early clobbers.
1059     SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
1060     if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getUseIndex()))
1061       if (SlotIndex::isSameInstr(Idx, VNI->def))
1062         Idx = VNI->def;
1063
1064     // Check for a sibling copy.
1065     unsigned SibReg = isFullCopyOf(MI, Reg);
1066     if (SibReg && isSibling(SibReg)) {
1067       // This may actually be a copy between snippets.
1068       if (isRegToSpill(SibReg)) {
1069         DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1070         SnippetCopies.insert(MI);
1071         continue;
1072       }
1073       if (Writes) {
1074         // Hoist the spill of a sib-reg copy.
1075         if (hoistSpill(OldLI, MI)) {
1076           // This COPY is now dead, the value is already in the stack slot.
1077           MI->getOperand(0).setIsDead();
1078           DeadDefs.push_back(MI);
1079           continue;
1080         }
1081       } else {
1082         // This is a reload for a sib-reg copy. Drop spills downstream.
1083         LiveInterval &SibLI = LIS.getInterval(SibReg);
1084         eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1085         // The COPY will fold to a reload below.
1086       }
1087     }
1088
1089     // Attempt to fold memory ops.
1090     if (foldMemoryOperand(MI, Ops))
1091       continue;
1092
1093     // Allocate interval around instruction.
1094     // FIXME: Infer regclass from instruction alone.
1095     LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM);
1096     NewLI.markNotSpillable();
1097
1098     if (Reads)
1099       insertReload(NewLI, Idx, MI);
1100
1101     // Rewrite instruction operands.
1102     bool hasLiveDef = false;
1103     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1104       MachineOperand &MO = MI->getOperand(Ops[i]);
1105       MO.setReg(NewLI.reg);
1106       if (MO.isUse()) {
1107         if (!MI->isRegTiedToDefOperand(Ops[i]))
1108           MO.setIsKill();
1109       } else {
1110         if (!MO.isDead())
1111           hasLiveDef = true;
1112       }
1113     }
1114     DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
1115
1116     // FIXME: Use a second vreg if instruction has no tied ops.
1117     if (Writes && hasLiveDef)
1118       insertSpill(NewLI, OldLI, Idx, MI);
1119
1120     DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
1121   }
1122 }
1123
1124 /// spillAll - Spill all registers remaining after rematerialization.
1125 void InlineSpiller::spillAll() {
1126   // Update LiveStacks now that we are committed to spilling.
1127   if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1128     StackSlot = VRM.assignVirt2StackSlot(Original);
1129     StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1130     StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
1131   } else
1132     StackInt = &LSS.getInterval(StackSlot);
1133
1134   if (Original != Edit->getReg())
1135     VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1136
1137   assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1138   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1139     StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
1140                                    StackInt->getValNumInfo(0));
1141   DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1142
1143   // Spill around uses of all RegsToSpill.
1144   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1145     spillAroundUses(RegsToSpill[i]);
1146
1147   // Hoisted spills may cause dead code.
1148   if (!DeadDefs.empty()) {
1149     DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1150     Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
1151   }
1152
1153   // Finally delete the SnippetCopies.
1154   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1155     for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(RegsToSpill[i]);
1156          MachineInstr *MI = RI.skipInstruction();) {
1157       assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1158       // FIXME: Do this with a LiveRangeEdit callback.
1159       VRM.RemoveMachineInstrFromMaps(MI);
1160       LIS.RemoveMachineInstrFromMaps(MI);
1161       MI->eraseFromParent();
1162     }
1163   }
1164
1165   // Delete all spilled registers.
1166   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1167     Edit->eraseVirtReg(RegsToSpill[i], LIS);
1168 }
1169
1170 void InlineSpiller::spill(LiveRangeEdit &edit) {
1171   ++NumSpilledRanges;
1172   Edit = &edit;
1173   assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1174          && "Trying to spill a stack slot.");
1175   // Share a stack slot among all descendants of Original.
1176   Original = VRM.getOriginal(edit.getReg());
1177   StackSlot = VRM.getStackSlot(Original);
1178   StackInt = 0;
1179
1180   DEBUG(dbgs() << "Inline spilling "
1181                << MRI.getRegClass(edit.getReg())->getName()
1182                << ':' << edit.getParent() << "\nFrom original "
1183                << LIS.getInterval(Original) << '\n');
1184   assert(edit.getParent().isSpillable() &&
1185          "Attempting to spill already spilled value.");
1186   assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1187
1188   collectRegsToSpill();
1189   analyzeSiblingValues();
1190   reMaterializeAll();
1191
1192   // Remat may handle everything.
1193   if (!RegsToSpill.empty())
1194     spillAll();
1195
1196   Edit->calculateRegClassAndHint(MF, LIS, Loops);
1197 }