Change the Spiller interface to take a LiveRangeEdit reference.
[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/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29
30 using namespace llvm;
31
32 namespace {
33 class InlineSpiller : public Spiller {
34   MachineFunctionPass &pass_;
35   MachineFunction &mf_;
36   LiveIntervals &lis_;
37   LiveStacks &lss_;
38   AliasAnalysis *aa_;
39   VirtRegMap &vrm_;
40   MachineFrameInfo &mfi_;
41   MachineRegisterInfo &mri_;
42   const TargetInstrInfo &tii_;
43   const TargetRegisterInfo &tri_;
44   const BitVector reserved_;
45
46   // Variables that are valid during spill(), but used by multiple methods.
47   LiveRangeEdit *edit_;
48   const TargetRegisterClass *rc_;
49   int stackSlot_;
50
51   // Values that failed to remat at some point.
52   SmallPtrSet<VNInfo*, 8> usedValues_;
53
54   ~InlineSpiller() {}
55
56 public:
57   InlineSpiller(MachineFunctionPass &pass,
58                 MachineFunction &mf,
59                 VirtRegMap &vrm)
60     : pass_(pass),
61       mf_(mf),
62       lis_(pass.getAnalysis<LiveIntervals>()),
63       lss_(pass.getAnalysis<LiveStacks>()),
64       aa_(&pass.getAnalysis<AliasAnalysis>()),
65       vrm_(vrm),
66       mfi_(*mf.getFrameInfo()),
67       mri_(mf.getRegInfo()),
68       tii_(*mf.getTarget().getInstrInfo()),
69       tri_(*mf.getTarget().getRegisterInfo()),
70       reserved_(tri_.getReservedRegs(mf_)) {}
71
72   void spill(LiveRangeEdit &);
73
74 private:
75   bool reMaterializeFor(MachineBasicBlock::iterator MI);
76   void reMaterializeAll();
77
78   bool coalesceStackAccess(MachineInstr *MI);
79   bool foldMemoryOperand(MachineBasicBlock::iterator MI,
80                          const SmallVectorImpl<unsigned> &Ops,
81                          MachineInstr *LoadMI = 0);
82   void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
83   void insertSpill(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
84 };
85 }
86
87 namespace llvm {
88 Spiller *createInlineSpiller(MachineFunctionPass &pass,
89                              MachineFunction &mf,
90                              VirtRegMap &vrm) {
91   return new InlineSpiller(pass, mf, vrm);
92 }
93 }
94
95 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
96 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
97   SlotIndex UseIdx = lis_.getInstructionIndex(MI).getUseIndex();
98   VNInfo *OrigVNI = edit_->getParent().getVNInfoAt(UseIdx);
99
100   if (!OrigVNI) {
101     DEBUG(dbgs() << "\tadding <undef> flags: ");
102     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
103       MachineOperand &MO = MI->getOperand(i);
104       if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg())
105         MO.setIsUndef();
106     }
107     DEBUG(dbgs() << UseIdx << '\t' << *MI);
108     return true;
109   }
110
111   LiveRangeEdit::Remat RM(OrigVNI);
112   if (!edit_->canRematerializeAt(RM, UseIdx, false, lis_)) {
113     usedValues_.insert(OrigVNI);
114     DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
115     return false;
116   }
117
118   // If the instruction also writes edit_->getReg(), it had better not require
119   // the same register for uses and defs.
120   bool Reads, Writes;
121   SmallVector<unsigned, 8> Ops;
122   tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit_->getReg(), &Ops);
123   if (Writes) {
124     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
125       MachineOperand &MO = MI->getOperand(Ops[i]);
126       if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
127         usedValues_.insert(OrigVNI);
128         DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
129         return false;
130       }
131     }
132   }
133
134   // Before rematerializing into a register for a single instruction, try to
135   // fold a load into the instruction. That avoids allocating a new register.
136   if (RM.OrigMI->getDesc().canFoldAsLoad() &&
137       foldMemoryOperand(MI, Ops, RM.OrigMI)) {
138     edit_->markRematerialized(RM.ParentVNI);
139     return true;
140   }
141
142   // Alocate a new register for the remat.
143   LiveInterval &NewLI = edit_->create(mri_, lis_, vrm_);
144   NewLI.markNotSpillable();
145
146   // Rematting for a copy: Set allocation hint to be the destination register.
147   if (MI->isCopy())
148     mri_.setRegAllocationHint(NewLI.reg, 0, MI->getOperand(0).getReg());
149
150   // Finally we can rematerialize OrigMI before MI.
151   SlotIndex DefIdx = edit_->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
152                                             lis_, tii_, tri_);
153   DEBUG(dbgs() << "\tremat:  " << DefIdx << '\t'
154                << *lis_.getInstructionFromIndex(DefIdx));
155
156   // Replace operands
157   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
158     MachineOperand &MO = MI->getOperand(Ops[i]);
159     if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg()) {
160       MO.setReg(NewLI.reg);
161       MO.setIsKill();
162     }
163   }
164   DEBUG(dbgs() << "\t        " << UseIdx << '\t' << *MI);
165
166   VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, lis_.getVNInfoAllocator());
167   NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
168   DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
169   return true;
170 }
171
172 /// reMaterializeAll - Try to rematerialize as many uses as possible,
173 /// and trim the live ranges after.
174 void InlineSpiller::reMaterializeAll() {
175   // Do a quick scan of the interval values to find if any are remattable.
176   if (!edit_->anyRematerializable(lis_, tii_, aa_))
177     return;
178
179   usedValues_.clear();
180
181   // Try to remat before all uses of edit_->getReg().
182   bool anyRemat = false;
183   for (MachineRegisterInfo::use_nodbg_iterator
184        RI = mri_.use_nodbg_begin(edit_->getReg());
185        MachineInstr *MI = RI.skipInstruction();)
186      anyRemat |= reMaterializeFor(MI);
187
188   if (!anyRemat)
189     return;
190
191   // Remove any values that were completely rematted.
192   bool anyRemoved = false;
193   for (LiveInterval::vni_iterator I = edit_->getParent().vni_begin(),
194        E = edit_->getParent().vni_end(); I != E; ++I) {
195     VNInfo *VNI = *I;
196     if (VNI->hasPHIKill() || !edit_->didRematerialize(VNI) ||
197         usedValues_.count(VNI))
198       continue;
199     MachineInstr *DefMI = lis_.getInstructionFromIndex(VNI->def);
200     DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
201     lis_.RemoveMachineInstrFromMaps(DefMI);
202     vrm_.RemoveMachineInstrFromMaps(DefMI);
203     DefMI->eraseFromParent();
204     VNI->def = SlotIndex();
205     anyRemoved = true;
206   }
207
208   if (!anyRemoved)
209     return;
210
211   // Removing values may cause debug uses where parent is not live.
212   for (MachineRegisterInfo::use_iterator RI = mri_.use_begin(edit_->getReg());
213        MachineInstr *MI = RI.skipInstruction();) {
214     if (!MI->isDebugValue())
215       continue;
216     // Try to preserve the debug value if parent is live immediately after it.
217     MachineBasicBlock::iterator NextMI = MI;
218     ++NextMI;
219     if (NextMI != MI->getParent()->end() && !lis_.isNotInMIMap(NextMI)) {
220       SlotIndex Idx = lis_.getInstructionIndex(NextMI);
221       VNInfo *VNI = edit_->getParent().getVNInfoAt(Idx);
222       if (VNI && (VNI->hasPHIKill() || usedValues_.count(VNI)))
223         continue;
224     }
225     DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
226     MI->eraseFromParent();
227   }
228 }
229
230 /// If MI is a load or store of stackSlot_, it can be removed.
231 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI) {
232   int FI = 0;
233   unsigned reg;
234   if (!(reg = tii_.isLoadFromStackSlot(MI, FI)) &&
235       !(reg = tii_.isStoreToStackSlot(MI, FI)))
236     return false;
237
238   // We have a stack access. Is it the right register and slot?
239   if (reg != edit_->getReg() || FI != stackSlot_)
240     return false;
241
242   DEBUG(dbgs() << "Coalescing stack access: " << *MI);
243   lis_.RemoveMachineInstrFromMaps(MI);
244   MI->eraseFromParent();
245   return true;
246 }
247
248 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
249 /// @param MI     Instruction using or defining the current register.
250 /// @param Ops    Operand indices from readsWritesVirtualRegister().
251 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
252 /// @return       True on success, and MI will be erased.
253 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
254                                       const SmallVectorImpl<unsigned> &Ops,
255                                       MachineInstr *LoadMI) {
256   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
257   // operands.
258   SmallVector<unsigned, 8> FoldOps;
259   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
260     unsigned Idx = Ops[i];
261     MachineOperand &MO = MI->getOperand(Idx);
262     if (MO.isImplicit())
263       continue;
264     // FIXME: Teach targets to deal with subregs.
265     if (MO.getSubReg())
266       return false;
267     // We cannot fold a load instruction into a def.
268     if (LoadMI && MO.isDef())
269       return false;
270     // Tied use operands should not be passed to foldMemoryOperand.
271     if (!MI->isRegTiedToDefOperand(Idx))
272       FoldOps.push_back(Idx);
273   }
274
275   MachineInstr *FoldMI =
276                 LoadMI ? tii_.foldMemoryOperand(MI, FoldOps, LoadMI)
277                        : tii_.foldMemoryOperand(MI, FoldOps, stackSlot_);
278   if (!FoldMI)
279     return false;
280   lis_.ReplaceMachineInstrInMaps(MI, FoldMI);
281   if (!LoadMI)
282     vrm_.addSpillSlotUse(stackSlot_, FoldMI);
283   MI->eraseFromParent();
284   DEBUG(dbgs() << "\tfolded: " << *FoldMI);
285   return true;
286 }
287
288 /// insertReload - Insert a reload of NewLI.reg before MI.
289 void InlineSpiller::insertReload(LiveInterval &NewLI,
290                                  MachineBasicBlock::iterator MI) {
291   MachineBasicBlock &MBB = *MI->getParent();
292   SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
293   tii_.loadRegFromStackSlot(MBB, MI, NewLI.reg, stackSlot_, rc_, &tri_);
294   --MI; // Point to load instruction.
295   SlotIndex LoadIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
296   vrm_.addSpillSlotUse(stackSlot_, MI);
297   DEBUG(dbgs() << "\treload:  " << LoadIdx << '\t' << *MI);
298   VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
299                                        lis_.getVNInfoAllocator());
300   NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
301 }
302
303 /// insertSpill - Insert a spill of NewLI.reg after MI.
304 void InlineSpiller::insertSpill(LiveInterval &NewLI,
305                                 MachineBasicBlock::iterator MI) {
306   MachineBasicBlock &MBB = *MI->getParent();
307
308   // Get the defined value. It could be an early clobber so keep the def index.
309   SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
310   VNInfo *VNI = edit_->getParent().getVNInfoAt(Idx);
311   assert(VNI && VNI->def.getDefIndex() == Idx && "Inconsistent VNInfo");
312   Idx = VNI->def;
313
314   tii_.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, stackSlot_, rc_, &tri_);
315   --MI; // Point to store instruction.
316   SlotIndex StoreIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
317   vrm_.addSpillSlotUse(stackSlot_, MI);
318   DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
319   VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, lis_.getVNInfoAllocator());
320   NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
321 }
322
323 void InlineSpiller::spill(LiveRangeEdit &edit) {
324   edit_ = &edit;
325   assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
326          && "Trying to spill a stack slot.");
327   DEBUG(dbgs() << "Inline spilling "
328                << mri_.getRegClass(edit.getReg())->getName()
329                << ':' << edit.getParent() << "\nFrom original "
330                << PrintReg(vrm_.getOriginal(edit.getReg())) << '\n');
331   assert(edit.getParent().isSpillable() &&
332          "Attempting to spill already spilled value.");
333
334   reMaterializeAll();
335
336   // Remat may handle everything.
337   if (edit_->getParent().empty())
338     return;
339
340   rc_ = mri_.getRegClass(edit.getReg());
341
342   // Share a stack slot among all descendants of Orig.
343   unsigned Orig = vrm_.getOriginal(edit.getReg());
344   stackSlot_ = vrm_.getStackSlot(Orig);
345   if (stackSlot_ == VirtRegMap::NO_STACK_SLOT)
346     stackSlot_ = vrm_.assignVirt2StackSlot(Orig);
347
348   if (Orig != edit.getReg())
349     vrm_.assignVirt2StackSlot(edit.getReg(), stackSlot_);
350
351   // Update LiveStacks now that we are committed to spilling.
352   LiveInterval &stacklvr = lss_.getOrCreateInterval(stackSlot_, rc_);
353   if (!stacklvr.hasAtLeastOneValue())
354     stacklvr.getNextValue(SlotIndex(), 0, lss_.getVNInfoAllocator());
355   stacklvr.MergeRangesInAsValue(edit_->getParent(), stacklvr.getValNumInfo(0));
356
357   // Iterate over instructions using register.
358   for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(edit.getReg());
359        MachineInstr *MI = RI.skipInstruction();) {
360
361     // Debug values are not allowed to affect codegen.
362     if (MI->isDebugValue()) {
363       // Modify DBG_VALUE now that the value is in a spill slot.
364       uint64_t Offset = MI->getOperand(1).getImm();
365       const MDNode *MDPtr = MI->getOperand(2).getMetadata();
366       DebugLoc DL = MI->getDebugLoc();
367       if (MachineInstr *NewDV = tii_.emitFrameIndexDebugValue(mf_, stackSlot_,
368                                                            Offset, MDPtr, DL)) {
369         DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
370         MachineBasicBlock *MBB = MI->getParent();
371         MBB->insert(MBB->erase(MI), NewDV);
372       } else {
373         DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
374         MI->eraseFromParent();
375       }
376       continue;
377     }
378
379     // Stack slot accesses may coalesce away.
380     if (coalesceStackAccess(MI))
381       continue;
382
383     // Analyze instruction.
384     bool Reads, Writes;
385     SmallVector<unsigned, 8> Ops;
386     tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit.getReg(), &Ops);
387
388     // Attempt to fold memory ops.
389     if (foldMemoryOperand(MI, Ops))
390       continue;
391
392     // Allocate interval around instruction.
393     // FIXME: Infer regclass from instruction alone.
394     LiveInterval &NewLI = edit.create(mri_, lis_, vrm_);
395     NewLI.markNotSpillable();
396
397     if (Reads)
398       insertReload(NewLI, MI);
399
400     // Rewrite instruction operands.
401     bool hasLiveDef = false;
402     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
403       MachineOperand &MO = MI->getOperand(Ops[i]);
404       MO.setReg(NewLI.reg);
405       if (MO.isUse()) {
406         if (!MI->isRegTiedToDefOperand(Ops[i]))
407           MO.setIsKill();
408       } else {
409         if (!MO.isDead())
410           hasLiveDef = true;
411       }
412     }
413
414     // FIXME: Use a second vreg if instruction has no tied ops.
415     if (Writes && hasLiveDef)
416       insertSpill(NewLI, MI);
417
418     DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
419   }
420 }