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/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
34 class InlineSpiller : public Spiller {
35 MachineFunctionPass &pass_;
39 MachineLoopInfo &loops_;
41 MachineFrameInfo &mfi_;
42 MachineRegisterInfo &mri_;
43 const TargetInstrInfo &tii_;
44 const TargetRegisterInfo &tri_;
45 const BitVector reserved_;
47 SplitAnalysis splitAnalysis_;
49 // Variables that are valid during spill(), but used by multiple methods.
51 const TargetRegisterClass *rc_;
54 // Values that failed to remat at some point.
55 SmallPtrSet<VNInfo*, 8> usedValues_;
60 InlineSpiller(MachineFunctionPass &pass,
65 lis_(pass.getAnalysis<LiveIntervals>()),
66 lss_(pass.getAnalysis<LiveStacks>()),
67 loops_(pass.getAnalysis<MachineLoopInfo>()),
69 mfi_(*mf.getFrameInfo()),
70 mri_(mf.getRegInfo()),
71 tii_(*mf.getTarget().getInstrInfo()),
72 tri_(*mf.getTarget().getRegisterInfo()),
73 reserved_(tri_.getReservedRegs(mf_)),
74 splitAnalysis_(mf, lis_, loops_) {}
76 void spill(LiveInterval *li,
77 SmallVectorImpl<LiveInterval*> &newIntervals,
78 SmallVectorImpl<LiveInterval*> &spillIs);
80 void spill(LiveRangeEdit &);
85 bool reMaterializeFor(MachineBasicBlock::iterator MI);
86 void reMaterializeAll();
88 bool coalesceStackAccess(MachineInstr *MI);
89 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
90 const SmallVectorImpl<unsigned> &Ops);
91 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
92 void insertSpill(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
97 Spiller *createInlineSpiller(MachineFunctionPass &pass,
100 return new InlineSpiller(pass, mf, vrm);
104 /// split - try splitting the current interval into pieces that may allocate
105 /// separately. Return true if successful.
106 bool InlineSpiller::split() {
107 splitAnalysis_.analyze(&edit_->getParent());
109 // Try splitting around loops.
110 if (const MachineLoop *loop = splitAnalysis_.getBestSplitLoop()) {
111 SplitEditor(splitAnalysis_, lis_, vrm_, *edit_)
112 .splitAroundLoop(loop);
116 // Try splitting into single block intervals.
117 SplitAnalysis::BlockPtrSet blocks;
118 if (splitAnalysis_.getMultiUseBlocks(blocks)) {
119 SplitEditor(splitAnalysis_, lis_, vrm_, *edit_)
120 .splitSingleBlocks(blocks);
124 // Try splitting inside a basic block.
125 if (const MachineBasicBlock *MBB = splitAnalysis_.getBlockForInsideSplit()) {
126 SplitEditor(splitAnalysis_, lis_, vrm_, *edit_)
127 .splitInsideBlock(MBB);
134 /// reMaterializeFor - Attempt to rematerialize edit_->getReg() before MI instead of
136 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
137 SlotIndex UseIdx = lis_.getInstructionIndex(MI).getUseIndex();
138 VNInfo *OrigVNI = edit_->getParent().getVNInfoAt(UseIdx);
141 DEBUG(dbgs() << "\tadding <undef> flags: ");
142 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
143 MachineOperand &MO = MI->getOperand(i);
144 if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg())
147 DEBUG(dbgs() << UseIdx << '\t' << *MI);
151 LiveRangeEdit::Remat RM = edit_->canRematerializeAt(OrigVNI, UseIdx, false,
154 usedValues_.insert(OrigVNI);
155 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
159 // If the instruction also writes edit_->getReg(), it had better not require
160 // the same register for uses and defs.
162 SmallVector<unsigned, 8> Ops;
163 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit_->getReg(), &Ops);
165 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
166 MachineOperand &MO = MI->getOperand(Ops[i]);
167 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
168 usedValues_.insert(OrigVNI);
169 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
175 // Alocate a new register for the remat.
176 LiveInterval &NewLI = edit_->create(mri_, lis_, vrm_);
177 NewLI.markNotSpillable();
179 // Finally we can rematerialize OrigMI before MI.
180 SlotIndex DefIdx = edit_->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
182 DEBUG(dbgs() << "\tremat: " << DefIdx << '\n');
185 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
186 MachineOperand &MO = MI->getOperand(Ops[i]);
187 if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg()) {
188 MO.setReg(NewLI.reg);
192 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
194 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, lis_.getVNInfoAllocator());
195 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
196 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
200 /// reMaterializeAll - Try to rematerialize as many uses as possible,
201 /// and trim the live ranges after.
202 void InlineSpiller::reMaterializeAll() {
203 // Do a quick scan of the interval values to find if any are remattable.
204 if (!edit_->anyRematerializable(lis_, tii_, 0))
209 // Try to remat before all uses of edit_->getReg().
210 bool anyRemat = false;
211 for (MachineRegisterInfo::use_nodbg_iterator
212 RI = mri_.use_nodbg_begin(edit_->getReg());
213 MachineInstr *MI = RI.skipInstruction();)
214 anyRemat |= reMaterializeFor(MI);
219 // Remove any values that were completely rematted.
220 bool anyRemoved = false;
221 for (LiveInterval::vni_iterator I = edit_->getParent().vni_begin(),
222 E = edit_->getParent().vni_end(); I != E; ++I) {
224 if (VNI->hasPHIKill() || !edit_->didRematerialize(VNI) ||
225 usedValues_.count(VNI))
227 MachineInstr *DefMI = lis_.getInstructionFromIndex(VNI->def);
228 DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
229 lis_.RemoveMachineInstrFromMaps(DefMI);
230 vrm_.RemoveMachineInstrFromMaps(DefMI);
231 DefMI->eraseFromParent();
232 VNI->def = SlotIndex();
239 // Removing values may cause debug uses where parent is not live.
240 for (MachineRegisterInfo::use_iterator RI = mri_.use_begin(edit_->getReg());
241 MachineInstr *MI = RI.skipInstruction();) {
242 if (!MI->isDebugValue())
244 // Try to preserve the debug value if parent is live immediately after it.
245 MachineBasicBlock::iterator NextMI = MI;
247 if (NextMI != MI->getParent()->end() && !lis_.isNotInMIMap(NextMI)) {
248 SlotIndex Idx = lis_.getInstructionIndex(NextMI);
249 VNInfo *VNI = edit_->getParent().getVNInfoAt(Idx);
250 if (VNI && (VNI->hasPHIKill() || usedValues_.count(VNI)))
253 DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
254 MI->eraseFromParent();
258 /// If MI is a load or store of stackSlot_, it can be removed.
259 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI) {
262 if (!(reg = tii_.isLoadFromStackSlot(MI, FI)) &&
263 !(reg = tii_.isStoreToStackSlot(MI, FI)))
266 // We have a stack access. Is it the right register and slot?
267 if (reg != edit_->getReg() || FI != stackSlot_)
270 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
271 lis_.RemoveMachineInstrFromMaps(MI);
272 MI->eraseFromParent();
276 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
277 /// Return true on success, and MI will be erased.
278 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
279 const SmallVectorImpl<unsigned> &Ops) {
280 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
282 SmallVector<unsigned, 8> FoldOps;
283 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
284 unsigned Idx = Ops[i];
285 MachineOperand &MO = MI->getOperand(Idx);
288 // FIXME: Teach targets to deal with subregs.
291 // Tied use operands should not be passed to foldMemoryOperand.
292 if (!MI->isRegTiedToDefOperand(Idx))
293 FoldOps.push_back(Idx);
296 MachineInstr *FoldMI = tii_.foldMemoryOperand(MI, FoldOps, stackSlot_);
299 lis_.ReplaceMachineInstrInMaps(MI, FoldMI);
300 vrm_.addSpillSlotUse(stackSlot_, FoldMI);
301 MI->eraseFromParent();
302 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
306 /// insertReload - Insert a reload of NewLI.reg before MI.
307 void InlineSpiller::insertReload(LiveInterval &NewLI,
308 MachineBasicBlock::iterator MI) {
309 MachineBasicBlock &MBB = *MI->getParent();
310 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
311 tii_.loadRegFromStackSlot(MBB, MI, NewLI.reg, stackSlot_, rc_, &tri_);
312 --MI; // Point to load instruction.
313 SlotIndex LoadIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
314 vrm_.addSpillSlotUse(stackSlot_, MI);
315 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
316 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
317 lis_.getVNInfoAllocator());
318 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
321 /// insertSpill - Insert a spill of NewLI.reg after MI.
322 void InlineSpiller::insertSpill(LiveInterval &NewLI,
323 MachineBasicBlock::iterator MI) {
324 MachineBasicBlock &MBB = *MI->getParent();
325 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
326 tii_.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, stackSlot_, rc_, &tri_);
327 --MI; // Point to store instruction.
328 SlotIndex StoreIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
329 vrm_.addSpillSlotUse(stackSlot_, MI);
330 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
331 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, lis_.getVNInfoAllocator());
332 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
335 void InlineSpiller::spill(LiveInterval *li,
336 SmallVectorImpl<LiveInterval*> &newIntervals,
337 SmallVectorImpl<LiveInterval*> &spillIs) {
338 LiveRangeEdit edit(*li, newIntervals, spillIs);
342 void InlineSpiller::spill(LiveRangeEdit &edit) {
344 DEBUG(dbgs() << "Inline spilling " << edit.getParent() << "\n");
345 assert(edit.getParent().isSpillable() &&
346 "Attempting to spill already spilled value.");
347 assert(!edit.getParent().isStackSlot() && "Trying to spill a stack slot.");
354 // Remat may handle everything.
355 if (edit_->getParent().empty())
358 rc_ = mri_.getRegClass(edit.getReg());
359 stackSlot_ = edit.assignStackSlot(vrm_);
361 // Update LiveStacks now that we are committed to spilling.
362 LiveInterval &stacklvr = lss_.getOrCreateInterval(stackSlot_, rc_);
363 if (!stacklvr.hasAtLeastOneValue())
364 stacklvr.getNextValue(SlotIndex(), 0, lss_.getVNInfoAllocator());
365 stacklvr.MergeRangesInAsValue(edit_->getParent(), stacklvr.getValNumInfo(0));
367 // Iterate over instructions using register.
368 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(edit.getReg());
369 MachineInstr *MI = RI.skipInstruction();) {
371 // Debug values are not allowed to affect codegen.
372 if (MI->isDebugValue()) {
373 // Modify DBG_VALUE now that the value is in a spill slot.
374 uint64_t Offset = MI->getOperand(1).getImm();
375 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
376 DebugLoc DL = MI->getDebugLoc();
377 if (MachineInstr *NewDV = tii_.emitFrameIndexDebugValue(mf_, stackSlot_,
378 Offset, MDPtr, DL)) {
379 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
380 MachineBasicBlock *MBB = MI->getParent();
381 MBB->insert(MBB->erase(MI), NewDV);
383 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
384 MI->eraseFromParent();
389 // Stack slot accesses may coalesce away.
390 if (coalesceStackAccess(MI))
393 // Analyze instruction.
395 SmallVector<unsigned, 8> Ops;
396 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit.getReg(), &Ops);
398 // Attempt to fold memory ops.
399 if (foldMemoryOperand(MI, Ops))
402 // Allocate interval around instruction.
403 // FIXME: Infer regclass from instruction alone.
404 LiveInterval &NewLI = edit.create(mri_, lis_, vrm_);
405 NewLI.markNotSpillable();
408 insertReload(NewLI, MI);
410 // Rewrite instruction operands.
411 bool hasLiveDef = false;
412 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
413 MachineOperand &MO = MI->getOperand(Ops[i]);
414 MO.setReg(NewLI.reg);
416 if (!MI->isRegTiedToDefOperand(Ops[i]))
424 // FIXME: Use a second vreg if instruction has no tied ops.
425 if (Writes && hasLiveDef)
426 insertSpill(NewLI, MI);
428 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');