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"
19 #include "VirtRegMap.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/LiveStackAnalysis.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
37 VerifySpills("verify-spills", cl::desc("Verify after each spill/split"));
40 ExtraSpillerSplits("extra-spiller-splits",
41 cl::desc("Enable additional splitting during splitting"));
44 class InlineSpiller : public Spiller {
45 MachineFunctionPass &pass_;
49 MachineDominatorTree &mdt_;
50 MachineLoopInfo &loops_;
53 MachineFrameInfo &mfi_;
54 MachineRegisterInfo &mri_;
55 const TargetInstrInfo &tii_;
56 const TargetRegisterInfo &tri_;
57 const BitVector reserved_;
59 SplitAnalysis splitAnalysis_;
61 // Variables that are valid during spill(), but used by multiple methods.
63 const TargetRegisterClass *rc_;
66 // Values that failed to remat at some point.
67 SmallPtrSet<VNInfo*, 8> usedValues_;
72 InlineSpiller(MachineFunctionPass &pass,
77 lis_(pass.getAnalysis<LiveIntervals>()),
78 lss_(pass.getAnalysis<LiveStacks>()),
79 mdt_(pass.getAnalysis<MachineDominatorTree>()),
80 loops_(pass.getAnalysis<MachineLoopInfo>()),
81 aa_(&pass.getAnalysis<AliasAnalysis>()),
83 mfi_(*mf.getFrameInfo()),
84 mri_(mf.getRegInfo()),
85 tii_(*mf.getTarget().getInstrInfo()),
86 tri_(*mf.getTarget().getRegisterInfo()),
87 reserved_(tri_.getReservedRegs(mf_)),
88 splitAnalysis_(mf, lis_, loops_) {}
90 void spill(LiveInterval *li,
91 SmallVectorImpl<LiveInterval*> &newIntervals,
92 const SmallVectorImpl<LiveInterval*> &spillIs);
94 void spill(LiveRangeEdit &);
99 bool reMaterializeFor(MachineBasicBlock::iterator MI);
100 void reMaterializeAll();
102 bool coalesceStackAccess(MachineInstr *MI);
103 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
104 const SmallVectorImpl<unsigned> &Ops);
105 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
106 void insertSpill(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
111 Spiller *createInlineSpiller(MachineFunctionPass &pass,
116 return new InlineSpiller(pass, mf, vrm);
120 /// split - try splitting the current interval into pieces that may allocate
121 /// separately. Return true if successful.
122 bool InlineSpiller::split() {
123 splitAnalysis_.analyze(&edit_->getParent());
125 // Try splitting around loops.
126 if (ExtraSpillerSplits) {
127 const MachineLoop *loop = splitAnalysis_.getBestSplitLoop();
129 SplitEditor(splitAnalysis_, lis_, vrm_, mdt_, *edit_)
130 .splitAroundLoop(loop);
135 // Try splitting into single block intervals.
136 SplitAnalysis::BlockPtrSet blocks;
137 if (splitAnalysis_.getMultiUseBlocks(blocks)) {
138 SplitEditor(splitAnalysis_, lis_, vrm_, mdt_, *edit_)
139 .splitSingleBlocks(blocks);
143 // Try splitting inside a basic block.
144 if (ExtraSpillerSplits) {
145 const MachineBasicBlock *MBB = splitAnalysis_.getBlockForInsideSplit();
147 SplitEditor(splitAnalysis_, lis_, vrm_, mdt_, *edit_)
148 .splitInsideBlock(MBB);
156 /// reMaterializeFor - Attempt to rematerialize edit_->getReg() before MI instead of
158 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
159 SlotIndex UseIdx = lis_.getInstructionIndex(MI).getUseIndex();
160 VNInfo *OrigVNI = edit_->getParent().getVNInfoAt(UseIdx);
163 DEBUG(dbgs() << "\tadding <undef> flags: ");
164 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
165 MachineOperand &MO = MI->getOperand(i);
166 if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg())
169 DEBUG(dbgs() << UseIdx << '\t' << *MI);
173 LiveRangeEdit::Remat RM(OrigVNI);
174 if (!edit_->canRematerializeAt(RM, UseIdx, false, lis_)) {
175 usedValues_.insert(OrigVNI);
176 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
180 // If the instruction also writes edit_->getReg(), it had better not require
181 // the same register for uses and defs.
183 SmallVector<unsigned, 8> Ops;
184 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit_->getReg(), &Ops);
186 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
187 MachineOperand &MO = MI->getOperand(Ops[i]);
188 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
189 usedValues_.insert(OrigVNI);
190 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
196 // Alocate a new register for the remat.
197 LiveInterval &NewLI = edit_->create(mri_, lis_, vrm_);
198 NewLI.markNotSpillable();
200 // Finally we can rematerialize OrigMI before MI.
201 SlotIndex DefIdx = edit_->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
203 DEBUG(dbgs() << "\tremat: " << DefIdx << '\n');
206 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
207 MachineOperand &MO = MI->getOperand(Ops[i]);
208 if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg()) {
209 MO.setReg(NewLI.reg);
213 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
215 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, lis_.getVNInfoAllocator());
216 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
217 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
221 /// reMaterializeAll - Try to rematerialize as many uses as possible,
222 /// and trim the live ranges after.
223 void InlineSpiller::reMaterializeAll() {
224 // Do a quick scan of the interval values to find if any are remattable.
225 if (!edit_->anyRematerializable(lis_, tii_, aa_))
230 // Try to remat before all uses of edit_->getReg().
231 bool anyRemat = false;
232 for (MachineRegisterInfo::use_nodbg_iterator
233 RI = mri_.use_nodbg_begin(edit_->getReg());
234 MachineInstr *MI = RI.skipInstruction();)
235 anyRemat |= reMaterializeFor(MI);
240 // Remove any values that were completely rematted.
241 bool anyRemoved = false;
242 for (LiveInterval::vni_iterator I = edit_->getParent().vni_begin(),
243 E = edit_->getParent().vni_end(); I != E; ++I) {
245 if (VNI->hasPHIKill() || !edit_->didRematerialize(VNI) ||
246 usedValues_.count(VNI))
248 MachineInstr *DefMI = lis_.getInstructionFromIndex(VNI->def);
249 DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
250 lis_.RemoveMachineInstrFromMaps(DefMI);
251 vrm_.RemoveMachineInstrFromMaps(DefMI);
252 DefMI->eraseFromParent();
253 VNI->def = SlotIndex();
260 // Removing values may cause debug uses where parent is not live.
261 for (MachineRegisterInfo::use_iterator RI = mri_.use_begin(edit_->getReg());
262 MachineInstr *MI = RI.skipInstruction();) {
263 if (!MI->isDebugValue())
265 // Try to preserve the debug value if parent is live immediately after it.
266 MachineBasicBlock::iterator NextMI = MI;
268 if (NextMI != MI->getParent()->end() && !lis_.isNotInMIMap(NextMI)) {
269 SlotIndex Idx = lis_.getInstructionIndex(NextMI);
270 VNInfo *VNI = edit_->getParent().getVNInfoAt(Idx);
271 if (VNI && (VNI->hasPHIKill() || usedValues_.count(VNI)))
274 DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
275 MI->eraseFromParent();
279 /// If MI is a load or store of stackSlot_, it can be removed.
280 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI) {
283 if (!(reg = tii_.isLoadFromStackSlot(MI, FI)) &&
284 !(reg = tii_.isStoreToStackSlot(MI, FI)))
287 // We have a stack access. Is it the right register and slot?
288 if (reg != edit_->getReg() || FI != stackSlot_)
291 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
292 lis_.RemoveMachineInstrFromMaps(MI);
293 MI->eraseFromParent();
297 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
298 /// Return true on success, and MI will be erased.
299 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
300 const SmallVectorImpl<unsigned> &Ops) {
301 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
303 SmallVector<unsigned, 8> FoldOps;
304 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
305 unsigned Idx = Ops[i];
306 MachineOperand &MO = MI->getOperand(Idx);
309 // FIXME: Teach targets to deal with subregs.
312 // Tied use operands should not be passed to foldMemoryOperand.
313 if (!MI->isRegTiedToDefOperand(Idx))
314 FoldOps.push_back(Idx);
317 MachineInstr *FoldMI = tii_.foldMemoryOperand(MI, FoldOps, stackSlot_);
320 lis_.ReplaceMachineInstrInMaps(MI, FoldMI);
321 vrm_.addSpillSlotUse(stackSlot_, FoldMI);
322 MI->eraseFromParent();
323 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
327 /// insertReload - Insert a reload of NewLI.reg before MI.
328 void InlineSpiller::insertReload(LiveInterval &NewLI,
329 MachineBasicBlock::iterator MI) {
330 MachineBasicBlock &MBB = *MI->getParent();
331 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
332 tii_.loadRegFromStackSlot(MBB, MI, NewLI.reg, stackSlot_, rc_, &tri_);
333 --MI; // Point to load instruction.
334 SlotIndex LoadIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
335 vrm_.addSpillSlotUse(stackSlot_, MI);
336 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
337 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
338 lis_.getVNInfoAllocator());
339 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
342 /// insertSpill - Insert a spill of NewLI.reg after MI.
343 void InlineSpiller::insertSpill(LiveInterval &NewLI,
344 MachineBasicBlock::iterator MI) {
345 MachineBasicBlock &MBB = *MI->getParent();
347 // Get the defined value. It could be an early clobber so keep the def index.
348 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
349 VNInfo *VNI = edit_->getParent().getVNInfoAt(Idx);
350 assert(VNI && VNI->def.getDefIndex() == Idx && "Inconsistent VNInfo");
353 tii_.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, stackSlot_, rc_, &tri_);
354 --MI; // Point to store instruction.
355 SlotIndex StoreIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
356 vrm_.addSpillSlotUse(stackSlot_, MI);
357 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
358 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, lis_.getVNInfoAllocator());
359 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
362 void InlineSpiller::spill(LiveInterval *li,
363 SmallVectorImpl<LiveInterval*> &newIntervals,
364 const SmallVectorImpl<LiveInterval*> &spillIs) {
365 LiveRangeEdit edit(*li, newIntervals, spillIs);
371 void InlineSpiller::spill(LiveRangeEdit &edit) {
373 assert(!edit.getParent().isStackSlot() && "Trying to spill a stack slot.");
374 DEBUG(dbgs() << "Inline spilling "
375 << mri_.getRegClass(edit.getReg())->getName()
376 << ':' << edit.getParent() << "\n");
377 assert(edit.getParent().isSpillable() &&
378 "Attempting to spill already spilled value.");
385 // Remat may handle everything.
386 if (edit_->getParent().empty())
389 rc_ = mri_.getRegClass(edit.getReg());
390 stackSlot_ = vrm_.assignVirt2StackSlot(edit_->getReg());
392 // Update LiveStacks now that we are committed to spilling.
393 LiveInterval &stacklvr = lss_.getOrCreateInterval(stackSlot_, rc_);
394 assert(stacklvr.empty() && "Just created stack slot not empty");
395 stacklvr.getNextValue(SlotIndex(), 0, lss_.getVNInfoAllocator());
396 stacklvr.MergeRangesInAsValue(edit_->getParent(), stacklvr.getValNumInfo(0));
398 // Iterate over instructions using register.
399 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(edit.getReg());
400 MachineInstr *MI = RI.skipInstruction();) {
402 // Debug values are not allowed to affect codegen.
403 if (MI->isDebugValue()) {
404 // Modify DBG_VALUE now that the value is in a spill slot.
405 uint64_t Offset = MI->getOperand(1).getImm();
406 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
407 DebugLoc DL = MI->getDebugLoc();
408 if (MachineInstr *NewDV = tii_.emitFrameIndexDebugValue(mf_, stackSlot_,
409 Offset, MDPtr, DL)) {
410 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
411 MachineBasicBlock *MBB = MI->getParent();
412 MBB->insert(MBB->erase(MI), NewDV);
414 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
415 MI->eraseFromParent();
420 // Stack slot accesses may coalesce away.
421 if (coalesceStackAccess(MI))
424 // Analyze instruction.
426 SmallVector<unsigned, 8> Ops;
427 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit.getReg(), &Ops);
429 // Attempt to fold memory ops.
430 if (foldMemoryOperand(MI, Ops))
433 // Allocate interval around instruction.
434 // FIXME: Infer regclass from instruction alone.
435 LiveInterval &NewLI = edit.create(mri_, lis_, vrm_);
436 NewLI.markNotSpillable();
439 insertReload(NewLI, MI);
441 // Rewrite instruction operands.
442 bool hasLiveDef = false;
443 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
444 MachineOperand &MO = MI->getOperand(Ops[i]);
445 MO.setReg(NewLI.reg);
447 if (!MI->isRegTiedToDefOperand(Ops[i]))
455 // FIXME: Use a second vreg if instruction has no tied ops.
456 if (Writes && hasLiveDef)
457 insertSpill(NewLI, MI);
459 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');