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