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