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