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