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"
18 #include "VirtRegMap.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
32 class InlineSpiller : public Spiller {
35 MachineLoopInfo &loops_;
37 MachineFrameInfo &mfi_;
38 MachineRegisterInfo &mri_;
39 const TargetInstrInfo &tii_;
40 const TargetRegisterInfo &tri_;
41 const BitVector reserved_;
43 SplitAnalysis splitAnalysis_;
45 // Variables that are valid during spill(), but used by multiple methods.
47 std::vector<LiveInterval*> *newIntervals_;
48 const TargetRegisterClass *rc_;
50 const SmallVectorImpl<LiveInterval*> *spillIs_;
52 // Values of the current interval that can potentially remat.
53 SmallPtrSet<VNInfo*, 8> reMattable_;
55 // Values in reMattable_ that failed to remat at some point.
56 SmallPtrSet<VNInfo*, 8> usedValues_;
61 InlineSpiller(MachineFunctionPass &pass,
65 lis_(pass.getAnalysis<LiveIntervals>()),
66 loops_(pass.getAnalysis<MachineLoopInfo>()),
68 mfi_(*mf.getFrameInfo()),
69 mri_(mf.getRegInfo()),
70 tii_(*mf.getTarget().getInstrInfo()),
71 tri_(*mf.getTarget().getRegisterInfo()),
72 reserved_(tri_.getReservedRegs(mf_)),
73 splitAnalysis_(mf, lis_, loops_) {}
75 void spill(LiveInterval *li,
76 std::vector<LiveInterval*> &newIntervals,
77 SmallVectorImpl<LiveInterval*> &spillIs,
78 SlotIndex *earliestIndex);
83 bool allUsesAvailableAt(const MachineInstr *OrigMI, SlotIndex OrigIdx,
85 bool reMaterializeFor(MachineBasicBlock::iterator MI);
86 void reMaterializeAll();
88 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
89 const SmallVectorImpl<unsigned> &Ops);
90 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
91 void insertSpill(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
96 Spiller *createInlineSpiller(MachineFunctionPass &pass,
99 return new InlineSpiller(pass, mf, vrm);
103 /// split - try splitting the current interval into pieces that may allocate
104 /// separately. Return true if successful.
105 bool InlineSpiller::split() {
106 // FIXME: Add intra-MBB splitting.
107 if (lis_.intervalIsInOneMBB(*li_))
110 splitAnalysis_.analyze(li_);
112 if (const MachineLoop *loop = splitAnalysis_.getBestSplitLoop()) {
113 SplitEditor(splitAnalysis_, lis_, vrm_, *newIntervals_)
114 .splitAroundLoop(loop);
120 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
121 /// OrigIdx are also available with the same value at UseIdx.
122 bool InlineSpiller::allUsesAvailableAt(const MachineInstr *OrigMI,
125 OrigIdx = OrigIdx.getUseIndex();
126 UseIdx = UseIdx.getUseIndex();
127 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
128 const MachineOperand &MO = OrigMI->getOperand(i);
129 if (!MO.isReg() || !MO.getReg() || MO.getReg() == li_->reg)
131 // Reserved registers are OK.
132 if (MO.isUndef() || !lis_.hasInterval(MO.getReg()))
134 // We don't want to move any defs.
137 // We cannot depend on virtual registers in spillIs_. They will be spilled.
138 for (unsigned si = 0, se = spillIs_->size(); si != se; ++si)
139 if ((*spillIs_)[si]->reg == MO.getReg())
142 LiveInterval &LI = lis_.getInterval(MO.getReg());
143 const VNInfo *OVNI = LI.getVNInfoAt(OrigIdx);
146 if (OVNI != LI.getVNInfoAt(UseIdx))
152 /// reMaterializeFor - Attempt to rematerialize li_->reg before MI instead of
154 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
155 SlotIndex UseIdx = lis_.getInstructionIndex(MI).getUseIndex();
156 VNInfo *OrigVNI = li_->getVNInfoAt(UseIdx);
158 DEBUG(dbgs() << "\tadding <undef> flags: ");
159 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
160 MachineOperand &MO = MI->getOperand(i);
161 if (MO.isReg() && MO.isUse() && MO.getReg() == li_->reg)
164 DEBUG(dbgs() << UseIdx << '\t' << *MI);
167 if (!reMattable_.count(OrigVNI)) {
168 DEBUG(dbgs() << "\tusing non-remat valno " << OrigVNI->id << ": "
169 << UseIdx << '\t' << *MI);
172 MachineInstr *OrigMI = lis_.getInstructionFromIndex(OrigVNI->def);
173 if (!allUsesAvailableAt(OrigMI, OrigVNI->def, UseIdx)) {
174 usedValues_.insert(OrigVNI);
175 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
179 // If the instruction also writes li_->reg, it had better not require the same
180 // register for uses and defs.
182 SmallVector<unsigned, 8> Ops;
183 tie(Reads, Writes) = MI->readsWritesVirtualRegister(li_->reg, &Ops);
185 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
186 MachineOperand &MO = MI->getOperand(Ops[i]);
187 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
188 usedValues_.insert(OrigVNI);
189 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
195 // Alocate a new register for the remat.
196 unsigned NewVReg = mri_.createVirtualRegister(rc_);
198 LiveInterval &NewLI = lis_.getOrCreateInterval(NewVReg);
199 NewLI.markNotSpillable();
200 newIntervals_->push_back(&NewLI);
202 // Finally we can rematerialize OrigMI before MI.
203 MachineBasicBlock &MBB = *MI->getParent();
204 tii_.reMaterialize(MBB, MI, NewLI.reg, 0, OrigMI, tri_);
205 MachineBasicBlock::iterator RematMI = MI;
206 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(--RematMI).getDefIndex();
207 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t' << *RematMI);
210 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
211 MachineOperand &MO = MI->getOperand(Ops[i]);
212 if (MO.isReg() && MO.isUse() && MO.getReg() == li_->reg) {
217 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
219 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, true,
220 lis_.getVNInfoAllocator());
221 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
222 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
226 /// reMaterializeAll - Try to rematerialize as many uses of li_ as possible,
227 /// and trim the live ranges after.
228 void InlineSpiller::reMaterializeAll() {
229 // Do a quick scan of the interval values to find if any are remattable.
232 for (LiveInterval::const_vni_iterator I = li_->vni_begin(),
233 E = li_->vni_end(); I != E; ++I) {
235 if (VNI->isUnused() || !VNI->isDefAccurate())
237 MachineInstr *DefMI = lis_.getInstructionFromIndex(VNI->def);
238 if (!DefMI || !tii_.isTriviallyReMaterializable(DefMI))
240 reMattable_.insert(VNI);
243 // Often, no defs are remattable.
244 if (reMattable_.empty())
247 // Try to remat before all uses of li_->reg.
248 bool anyRemat = false;
249 for (MachineRegisterInfo::use_nodbg_iterator
250 RI = mri_.use_nodbg_begin(li_->reg);
251 MachineInstr *MI = RI.skipInstruction();)
252 anyRemat |= reMaterializeFor(MI);
257 // Remove any values that were completely rematted.
258 bool anyRemoved = false;
259 for (SmallPtrSet<VNInfo*, 8>::iterator I = reMattable_.begin(),
260 E = reMattable_.end(); I != E; ++I) {
262 if (VNI->hasPHIKill() || usedValues_.count(VNI))
264 MachineInstr *DefMI = lis_.getInstructionFromIndex(VNI->def);
265 DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
266 lis_.RemoveMachineInstrFromMaps(DefMI);
267 vrm_.RemoveMachineInstrFromMaps(DefMI);
268 DefMI->eraseFromParent();
269 li_->removeValNo(VNI);
276 // Removing values may cause debug uses where li_ is not live.
277 for (MachineRegisterInfo::use_iterator RI = mri_.use_begin(li_->reg);
278 MachineInstr *MI = RI.skipInstruction();) {
279 if (!MI->isDebugValue())
281 // Try to preserve the debug value if li_ is live immediately after it.
282 MachineBasicBlock::iterator NextMI = MI;
284 if (NextMI != MI->getParent()->end() && !lis_.isNotInMIMap(NextMI)) {
285 SlotIndex NearIdx = lis_.getInstructionIndex(NextMI);
286 if (li_->liveAt(NearIdx))
289 DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
290 MI->eraseFromParent();
294 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
295 /// Return true on success, and MI will be erased.
296 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
297 const SmallVectorImpl<unsigned> &Ops) {
298 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
300 SmallVector<unsigned, 8> FoldOps;
301 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
302 unsigned Idx = Ops[i];
303 MachineOperand &MO = MI->getOperand(Idx);
306 // FIXME: Teach targets to deal with subregs.
309 // Tied use operands should not be passed to foldMemoryOperand.
310 if (!MI->isRegTiedToDefOperand(Idx))
311 FoldOps.push_back(Idx);
314 MachineInstr *FoldMI = tii_.foldMemoryOperand(MI, FoldOps, stackSlot_);
317 lis_.ReplaceMachineInstrInMaps(MI, FoldMI);
318 vrm_.addSpillSlotUse(stackSlot_, FoldMI);
319 MI->eraseFromParent();
320 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
324 /// insertReload - Insert a reload of NewLI.reg before MI.
325 void InlineSpiller::insertReload(LiveInterval &NewLI,
326 MachineBasicBlock::iterator MI) {
327 MachineBasicBlock &MBB = *MI->getParent();
328 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
329 tii_.loadRegFromStackSlot(MBB, MI, NewLI.reg, stackSlot_, rc_, &tri_);
330 --MI; // Point to load instruction.
331 SlotIndex LoadIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
332 vrm_.addSpillSlotUse(stackSlot_, MI);
333 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
334 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0, true,
335 lis_.getVNInfoAllocator());
336 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
339 /// insertSpill - Insert a spill of NewLI.reg after MI.
340 void InlineSpiller::insertSpill(LiveInterval &NewLI,
341 MachineBasicBlock::iterator MI) {
342 MachineBasicBlock &MBB = *MI->getParent();
343 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
344 tii_.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, stackSlot_, rc_, &tri_);
345 --MI; // Point to store instruction.
346 SlotIndex StoreIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
347 vrm_.addSpillSlotUse(stackSlot_, MI);
348 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
349 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, true,
350 lis_.getVNInfoAllocator());
351 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
354 void InlineSpiller::spill(LiveInterval *li,
355 std::vector<LiveInterval*> &newIntervals,
356 SmallVectorImpl<LiveInterval*> &spillIs,
357 SlotIndex *earliestIndex) {
358 DEBUG(dbgs() << "Inline spilling " << *li << "\n");
359 assert(li->isSpillable() && "Attempting to spill already spilled value.");
360 assert(!li->isStackSlot() && "Trying to spill a stack slot.");
363 newIntervals_ = &newIntervals;
364 rc_ = mri_.getRegClass(li->reg);
372 // Remat may handle everything.
376 stackSlot_ = vrm_.getStackSlot(li->reg);
377 if (stackSlot_ == VirtRegMap::NO_STACK_SLOT)
378 stackSlot_ = vrm_.assignVirt2StackSlot(li->reg);
380 // Iterate over instructions using register.
381 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(li->reg);
382 MachineInstr *MI = RI.skipInstruction();) {
384 // Debug values are not allowed to affect codegen.
385 if (MI->isDebugValue()) {
386 // Modify DBG_VALUE now that the value is in a spill slot.
387 uint64_t Offset = MI->getOperand(1).getImm();
388 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
389 DebugLoc DL = MI->getDebugLoc();
390 if (MachineInstr *NewDV = tii_.emitFrameIndexDebugValue(mf_, stackSlot_,
391 Offset, MDPtr, DL)) {
392 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
393 MachineBasicBlock *MBB = MI->getParent();
394 MBB->insert(MBB->erase(MI), NewDV);
396 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
397 MI->eraseFromParent();
402 // Analyze instruction.
404 SmallVector<unsigned, 8> Ops;
405 tie(Reads, Writes) = MI->readsWritesVirtualRegister(li->reg, &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 unsigned NewVReg = mri_.createVirtualRegister(rc_);
415 LiveInterval &NewLI = lis_.getOrCreateInterval(NewVReg);
416 NewLI.markNotSpillable();
419 insertReload(NewLI, MI);
421 // Rewrite instruction operands.
422 bool hasLiveDef = false;
423 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
424 MachineOperand &MO = MI->getOperand(Ops[i]);
427 if (!MI->isRegTiedToDefOperand(Ops[i]))
435 // FIXME: Use a second vreg if instruction has no tied ops.
436 if (Writes && hasLiveDef)
437 insertSpill(NewLI, MI);
439 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
440 newIntervals.push_back(&NewLI);