1 //===-------- InlineSpiller.cpp - Insert spills and restores inline -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The inline spiller modifies the machine function directly instead of
11 // inserting spills and restores in VirtRegMap.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "spiller"
17 #include "LiveRangeEdit.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"
36 VerifySpills("verify-spills", cl::desc("Verify after each spill/split"));
39 class InlineSpiller : public Spiller {
40 MachineFunctionPass &pass_;
44 MachineDominatorTree &mdt_;
45 MachineLoopInfo &loops_;
47 MachineFrameInfo &mfi_;
48 MachineRegisterInfo &mri_;
49 const TargetInstrInfo &tii_;
50 const TargetRegisterInfo &tri_;
51 const BitVector reserved_;
53 SplitAnalysis splitAnalysis_;
55 // Variables that are valid during spill(), but used by multiple methods.
57 const TargetRegisterClass *rc_;
60 // Values that failed to remat at some point.
61 SmallPtrSet<VNInfo*, 8> usedValues_;
66 InlineSpiller(MachineFunctionPass &pass,
71 lis_(pass.getAnalysis<LiveIntervals>()),
72 lss_(pass.getAnalysis<LiveStacks>()),
73 mdt_(pass.getAnalysis<MachineDominatorTree>()),
74 loops_(pass.getAnalysis<MachineLoopInfo>()),
76 mfi_(*mf.getFrameInfo()),
77 mri_(mf.getRegInfo()),
78 tii_(*mf.getTarget().getInstrInfo()),
79 tri_(*mf.getTarget().getRegisterInfo()),
80 reserved_(tri_.getReservedRegs(mf_)),
81 splitAnalysis_(mf, lis_, loops_) {}
83 void spill(LiveInterval *li,
84 SmallVectorImpl<LiveInterval*> &newIntervals,
85 SmallVectorImpl<LiveInterval*> &spillIs);
87 void spill(LiveRangeEdit &);
92 bool reMaterializeFor(MachineBasicBlock::iterator MI);
93 void reMaterializeAll();
95 bool coalesceStackAccess(MachineInstr *MI);
96 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
97 const SmallVectorImpl<unsigned> &Ops);
98 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
99 void insertSpill(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
104 Spiller *createInlineSpiller(MachineFunctionPass &pass,
107 return new InlineSpiller(pass, mf, vrm);
111 /// split - try splitting the current interval into pieces that may allocate
112 /// separately. Return true if successful.
113 bool InlineSpiller::split() {
114 splitAnalysis_.analyze(&edit_->getParent());
116 // Try splitting around loops.
117 if (const MachineLoop *loop = splitAnalysis_.getBestSplitLoop()) {
118 SplitEditor(splitAnalysis_, lis_, vrm_, mdt_, *edit_)
119 .splitAroundLoop(loop);
123 // Try splitting into single block intervals.
124 SplitAnalysis::BlockPtrSet blocks;
125 if (splitAnalysis_.getMultiUseBlocks(blocks)) {
126 SplitEditor(splitAnalysis_, lis_, vrm_, mdt_, *edit_)
127 .splitSingleBlocks(blocks);
131 // Try splitting inside a basic block.
132 if (const MachineBasicBlock *MBB = splitAnalysis_.getBlockForInsideSplit()) {
133 SplitEditor(splitAnalysis_, lis_, vrm_, mdt_, *edit_)
134 .splitInsideBlock(MBB);
141 /// reMaterializeFor - Attempt to rematerialize edit_->getReg() before MI instead of
143 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
144 SlotIndex UseIdx = lis_.getInstructionIndex(MI).getUseIndex();
145 VNInfo *OrigVNI = edit_->getParent().getVNInfoAt(UseIdx);
148 DEBUG(dbgs() << "\tadding <undef> flags: ");
149 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
150 MachineOperand &MO = MI->getOperand(i);
151 if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg())
154 DEBUG(dbgs() << UseIdx << '\t' << *MI);
158 LiveRangeEdit::Remat RM = edit_->canRematerializeAt(OrigVNI, UseIdx, false,
161 usedValues_.insert(OrigVNI);
162 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
166 // If the instruction also writes edit_->getReg(), it had better not require
167 // the same register for uses and defs.
169 SmallVector<unsigned, 8> Ops;
170 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit_->getReg(), &Ops);
172 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
173 MachineOperand &MO = MI->getOperand(Ops[i]);
174 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
175 usedValues_.insert(OrigVNI);
176 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
182 // Alocate a new register for the remat.
183 LiveInterval &NewLI = edit_->create(mri_, lis_, vrm_);
184 NewLI.markNotSpillable();
186 // Finally we can rematerialize OrigMI before MI.
187 SlotIndex DefIdx = edit_->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
189 DEBUG(dbgs() << "\tremat: " << DefIdx << '\n');
192 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
193 MachineOperand &MO = MI->getOperand(Ops[i]);
194 if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg()) {
195 MO.setReg(NewLI.reg);
199 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
201 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, lis_.getVNInfoAllocator());
202 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
203 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
207 /// reMaterializeAll - Try to rematerialize as many uses as possible,
208 /// and trim the live ranges after.
209 void InlineSpiller::reMaterializeAll() {
210 // Do a quick scan of the interval values to find if any are remattable.
211 if (!edit_->anyRematerializable(lis_, tii_, 0))
216 // Try to remat before all uses of edit_->getReg().
217 bool anyRemat = false;
218 for (MachineRegisterInfo::use_nodbg_iterator
219 RI = mri_.use_nodbg_begin(edit_->getReg());
220 MachineInstr *MI = RI.skipInstruction();)
221 anyRemat |= reMaterializeFor(MI);
226 // Remove any values that were completely rematted.
227 bool anyRemoved = false;
228 for (LiveInterval::vni_iterator I = edit_->getParent().vni_begin(),
229 E = edit_->getParent().vni_end(); I != E; ++I) {
231 if (VNI->hasPHIKill() || !edit_->didRematerialize(VNI) ||
232 usedValues_.count(VNI))
234 MachineInstr *DefMI = lis_.getInstructionFromIndex(VNI->def);
235 DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
236 lis_.RemoveMachineInstrFromMaps(DefMI);
237 vrm_.RemoveMachineInstrFromMaps(DefMI);
238 DefMI->eraseFromParent();
239 VNI->def = SlotIndex();
246 // Removing values may cause debug uses where parent is not live.
247 for (MachineRegisterInfo::use_iterator RI = mri_.use_begin(edit_->getReg());
248 MachineInstr *MI = RI.skipInstruction();) {
249 if (!MI->isDebugValue())
251 // Try to preserve the debug value if parent is live immediately after it.
252 MachineBasicBlock::iterator NextMI = MI;
254 if (NextMI != MI->getParent()->end() && !lis_.isNotInMIMap(NextMI)) {
255 SlotIndex Idx = lis_.getInstructionIndex(NextMI);
256 VNInfo *VNI = edit_->getParent().getVNInfoAt(Idx);
257 if (VNI && (VNI->hasPHIKill() || usedValues_.count(VNI)))
260 DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
261 MI->eraseFromParent();
265 /// If MI is a load or store of stackSlot_, it can be removed.
266 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI) {
269 if (!(reg = tii_.isLoadFromStackSlot(MI, FI)) &&
270 !(reg = tii_.isStoreToStackSlot(MI, FI)))
273 // We have a stack access. Is it the right register and slot?
274 if (reg != edit_->getReg() || FI != stackSlot_)
277 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
278 lis_.RemoveMachineInstrFromMaps(MI);
279 MI->eraseFromParent();
283 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
284 /// Return true on success, and MI will be erased.
285 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
286 const SmallVectorImpl<unsigned> &Ops) {
287 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
289 SmallVector<unsigned, 8> FoldOps;
290 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
291 unsigned Idx = Ops[i];
292 MachineOperand &MO = MI->getOperand(Idx);
295 // FIXME: Teach targets to deal with subregs.
298 // Tied use operands should not be passed to foldMemoryOperand.
299 if (!MI->isRegTiedToDefOperand(Idx))
300 FoldOps.push_back(Idx);
303 MachineInstr *FoldMI = tii_.foldMemoryOperand(MI, FoldOps, stackSlot_);
306 lis_.ReplaceMachineInstrInMaps(MI, FoldMI);
307 vrm_.addSpillSlotUse(stackSlot_, FoldMI);
308 MI->eraseFromParent();
309 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
313 /// insertReload - Insert a reload of NewLI.reg before MI.
314 void InlineSpiller::insertReload(LiveInterval &NewLI,
315 MachineBasicBlock::iterator MI) {
316 MachineBasicBlock &MBB = *MI->getParent();
317 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
318 tii_.loadRegFromStackSlot(MBB, MI, NewLI.reg, stackSlot_, rc_, &tri_);
319 --MI; // Point to load instruction.
320 SlotIndex LoadIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
321 vrm_.addSpillSlotUse(stackSlot_, MI);
322 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
323 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
324 lis_.getVNInfoAllocator());
325 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
328 /// insertSpill - Insert a spill of NewLI.reg after MI.
329 void InlineSpiller::insertSpill(LiveInterval &NewLI,
330 MachineBasicBlock::iterator MI) {
331 MachineBasicBlock &MBB = *MI->getParent();
332 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
333 tii_.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, stackSlot_, rc_, &tri_);
334 --MI; // Point to store instruction.
335 SlotIndex StoreIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
336 vrm_.addSpillSlotUse(stackSlot_, MI);
337 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
338 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, lis_.getVNInfoAllocator());
339 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
342 void InlineSpiller::spill(LiveInterval *li,
343 SmallVectorImpl<LiveInterval*> &newIntervals,
344 SmallVectorImpl<LiveInterval*> &spillIs) {
345 LiveRangeEdit edit(*li, newIntervals, spillIs);
351 void InlineSpiller::spill(LiveRangeEdit &edit) {
353 DEBUG(dbgs() << "Inline spilling " << edit.getParent() << "\n");
354 assert(edit.getParent().isSpillable() &&
355 "Attempting to spill already spilled value.");
356 assert(!edit.getParent().isStackSlot() && "Trying to spill a stack slot.");
363 // Remat may handle everything.
364 if (edit_->getParent().empty())
367 rc_ = mri_.getRegClass(edit.getReg());
368 stackSlot_ = edit.assignStackSlot(vrm_);
370 // Update LiveStacks now that we are committed to spilling.
371 LiveInterval &stacklvr = lss_.getOrCreateInterval(stackSlot_, rc_);
372 if (!stacklvr.hasAtLeastOneValue())
373 stacklvr.getNextValue(SlotIndex(), 0, lss_.getVNInfoAllocator());
374 stacklvr.MergeRangesInAsValue(edit_->getParent(), stacklvr.getValNumInfo(0));
376 // Iterate over instructions using register.
377 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(edit.getReg());
378 MachineInstr *MI = RI.skipInstruction();) {
380 // Debug values are not allowed to affect codegen.
381 if (MI->isDebugValue()) {
382 // Modify DBG_VALUE now that the value is in a spill slot.
383 uint64_t Offset = MI->getOperand(1).getImm();
384 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
385 DebugLoc DL = MI->getDebugLoc();
386 if (MachineInstr *NewDV = tii_.emitFrameIndexDebugValue(mf_, stackSlot_,
387 Offset, MDPtr, DL)) {
388 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
389 MachineBasicBlock *MBB = MI->getParent();
390 MBB->insert(MBB->erase(MI), NewDV);
392 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
393 MI->eraseFromParent();
398 // Stack slot accesses may coalesce away.
399 if (coalesceStackAccess(MI))
402 // Analyze instruction.
404 SmallVector<unsigned, 8> Ops;
405 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit.getReg(), &Ops);
407 // Attempt to fold memory ops.
408 if (foldMemoryOperand(MI, Ops))
411 // Allocate interval around instruction.
412 // FIXME: Infer regclass from instruction alone.
413 LiveInterval &NewLI = edit.create(mri_, lis_, vrm_);
414 NewLI.markNotSpillable();
417 insertReload(NewLI, MI);
419 // Rewrite instruction operands.
420 bool hasLiveDef = false;
421 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
422 MachineOperand &MO = MI->getOperand(Ops[i]);
423 MO.setReg(NewLI.reg);
425 if (!MI->isRegTiedToDefOperand(Ops[i]))
433 // FIXME: Use a second vreg if instruction has no tied ops.
434 if (Writes && hasLiveDef)
435 insertSpill(NewLI, MI);
437 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');