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 "regalloc"
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"
33 class InlineSpiller : public Spiller {
34 MachineFunctionPass &pass_;
40 MachineFrameInfo &mfi_;
41 MachineRegisterInfo &mri_;
42 const TargetInstrInfo &tii_;
43 const TargetRegisterInfo &tri_;
44 const BitVector reserved_;
46 // Variables that are valid during spill(), but used by multiple methods.
48 const TargetRegisterClass *rc_;
51 // Values that failed to remat at some point.
52 SmallPtrSet<VNInfo*, 8> usedValues_;
57 InlineSpiller(MachineFunctionPass &pass,
62 lis_(pass.getAnalysis<LiveIntervals>()),
63 lss_(pass.getAnalysis<LiveStacks>()),
64 aa_(&pass.getAnalysis<AliasAnalysis>()),
66 mfi_(*mf.getFrameInfo()),
67 mri_(mf.getRegInfo()),
68 tii_(*mf.getTarget().getInstrInfo()),
69 tri_(*mf.getTarget().getRegisterInfo()),
70 reserved_(tri_.getReservedRegs(mf_)) {}
72 void spill(LiveRangeEdit &);
75 bool reMaterializeFor(MachineBasicBlock::iterator MI);
76 void reMaterializeAll();
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);
88 Spiller *createInlineSpiller(MachineFunctionPass &pass,
91 return new InlineSpiller(pass, mf, vrm);
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);
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())
107 DEBUG(dbgs() << UseIdx << '\t' << *MI);
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);
118 // If the instruction also writes edit_->getReg(), it had better not require
119 // the same register for uses and defs.
121 SmallVector<unsigned, 8> Ops;
122 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit_->getReg(), &Ops);
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);
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);
142 // Alocate a new register for the remat.
143 LiveInterval &NewLI = edit_->create(mri_, lis_, vrm_);
144 NewLI.markNotSpillable();
146 // Rematting for a copy: Set allocation hint to be the destination register.
148 mri_.setRegAllocationHint(NewLI.reg, 0, MI->getOperand(0).getReg());
150 // Finally we can rematerialize OrigMI before MI.
151 SlotIndex DefIdx = edit_->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
153 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
154 << *lis_.getInstructionFromIndex(DefIdx));
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);
164 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
166 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, lis_.getVNInfoAllocator());
167 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
168 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
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_))
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);
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) {
196 if (VNI->hasPHIKill() || !edit_->didRematerialize(VNI) ||
197 usedValues_.count(VNI))
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();
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())
216 // Try to preserve the debug value if parent is live immediately after it.
217 MachineBasicBlock::iterator NextMI = MI;
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)))
225 DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
226 MI->eraseFromParent();
230 /// If MI is a load or store of stackSlot_, it can be removed.
231 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI) {
234 if (!(reg = tii_.isLoadFromStackSlot(MI, FI)) &&
235 !(reg = tii_.isStoreToStackSlot(MI, FI)))
238 // We have a stack access. Is it the right register and slot?
239 if (reg != edit_->getReg() || FI != stackSlot_)
242 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
243 lis_.RemoveMachineInstrFromMaps(MI);
244 MI->eraseFromParent();
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
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);
264 // FIXME: Teach targets to deal with subregs.
267 // We cannot fold a load instruction into a def.
268 if (LoadMI && MO.isDef())
270 // Tied use operands should not be passed to foldMemoryOperand.
271 if (!MI->isRegTiedToDefOperand(Idx))
272 FoldOps.push_back(Idx);
275 MachineInstr *FoldMI =
276 LoadMI ? tii_.foldMemoryOperand(MI, FoldOps, LoadMI)
277 : tii_.foldMemoryOperand(MI, FoldOps, stackSlot_);
280 lis_.ReplaceMachineInstrInMaps(MI, FoldMI);
282 vrm_.addSpillSlotUse(stackSlot_, FoldMI);
283 MI->eraseFromParent();
284 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
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));
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();
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");
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));
323 void InlineSpiller::spill(LiveRangeEdit &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.");
336 // Remat may handle everything.
337 if (edit_->getParent().empty())
340 rc_ = mri_.getRegClass(edit.getReg());
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);
348 if (Orig != edit.getReg())
349 vrm_.assignVirt2StackSlot(edit.getReg(), stackSlot_);
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));
357 // Iterate over instructions using register.
358 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(edit.getReg());
359 MachineInstr *MI = RI.skipInstruction();) {
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);
373 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
374 MI->eraseFromParent();
379 // Stack slot accesses may coalesce away.
380 if (coalesceStackAccess(MI))
383 // Analyze instruction.
385 SmallVector<unsigned, 8> Ops;
386 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit.getReg(), &Ops);
388 // Attempt to fold memory ops.
389 if (foldMemoryOperand(MI, Ops))
392 // Allocate interval around instruction.
393 // FIXME: Infer regclass from instruction alone.
394 LiveInterval &NewLI = edit.create(mri_, lis_, vrm_);
395 NewLI.markNotSpillable();
398 insertReload(NewLI, MI);
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);
406 if (!MI->isRegTiedToDefOperand(Ops[i]))
414 // FIXME: Use a second vreg if instruction has no tied ops.
415 if (Writes && hasLiveDef)
416 insertSpill(NewLI, MI);
418 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');