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/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/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
35 class InlineSpiller : public Spiller {
36 MachineFunctionPass &Pass;
41 MachineDominatorTree &MDT;
42 MachineLoopInfo &Loops;
44 MachineFrameInfo &MFI;
45 MachineRegisterInfo &MRI;
46 const TargetInstrInfo &TII;
47 const TargetRegisterInfo &TRI;
49 // Variables that are valid during spill(), but used by multiple methods.
51 const TargetRegisterClass *RC;
55 // All registers to spill to StackSlot, including the main register.
56 SmallVector<unsigned, 8> RegsToSpill;
58 // All COPY instructions to/from snippets.
59 // They are ignored since both operands refer to the same stack slot.
60 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
62 // Values that failed to remat at some point.
63 SmallPtrSet<VNInfo*, 8> UsedValues;
65 // Information about a value that was defined by a copy from a sibling
68 // True when all reaching defs were reloads: No spill is necessary.
69 bool AllDefsAreReloads;
71 // The preferred register to spill.
74 // The value of SpillReg that should be spilled.
77 // A defining instruction that is not a sibling copy or a reload, or NULL.
78 // This can be used as a template for rematerialization.
81 SibValueInfo(unsigned Reg, VNInfo *VNI)
82 : AllDefsAreReloads(false), SpillReg(Reg), SpillVNI(VNI), DefMI(0) {}
85 // Values in RegsToSpill defined by sibling copies.
86 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
87 SibValueMap SibValues;
89 // Dead defs generated during spilling.
90 SmallVector<MachineInstr*, 8> DeadDefs;
95 InlineSpiller(MachineFunctionPass &pass,
100 LIS(pass.getAnalysis<LiveIntervals>()),
101 LSS(pass.getAnalysis<LiveStacks>()),
102 AA(&pass.getAnalysis<AliasAnalysis>()),
103 MDT(pass.getAnalysis<MachineDominatorTree>()),
104 Loops(pass.getAnalysis<MachineLoopInfo>()),
106 MFI(*mf.getFrameInfo()),
107 MRI(mf.getRegInfo()),
108 TII(*mf.getTarget().getInstrInfo()),
109 TRI(*mf.getTarget().getRegisterInfo()) {}
111 void spill(LiveRangeEdit &);
114 bool isSnippet(const LiveInterval &SnipLI);
115 void collectRegsToSpill();
117 bool isRegToSpill(unsigned Reg) {
118 return std::find(RegsToSpill.begin(),
119 RegsToSpill.end(), Reg) != RegsToSpill.end();
122 bool isSibling(unsigned Reg);
123 void traceSiblingValue(unsigned, VNInfo*, VNInfo*);
124 void analyzeSiblingValues();
126 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
127 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
129 bool reMaterializeFor(MachineBasicBlock::iterator MI);
130 void reMaterializeAll();
132 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
133 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
134 const SmallVectorImpl<unsigned> &Ops,
135 MachineInstr *LoadMI = 0);
136 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
137 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
138 MachineBasicBlock::iterator MI);
140 void spillAroundUses(unsigned Reg);
145 Spiller *createInlineSpiller(MachineFunctionPass &pass,
148 return new InlineSpiller(pass, mf, vrm);
152 //===----------------------------------------------------------------------===//
154 //===----------------------------------------------------------------------===//
156 // When spilling a virtual register, we also spill any snippets it is connected
157 // to. The snippets are small live ranges that only have a single real use,
158 // leftovers from live range splitting. Spilling them enables memory operand
159 // folding or tightens the live range around the single use.
161 // This minimizes register pressure and maximizes the store-to-load distance for
162 // spill slots which can be important in tight loops.
164 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
165 /// otherwise return 0.
166 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
169 if (MI->getOperand(0).getSubReg() != 0)
171 if (MI->getOperand(1).getSubReg() != 0)
173 if (MI->getOperand(0).getReg() == Reg)
174 return MI->getOperand(1).getReg();
175 if (MI->getOperand(1).getReg() == Reg)
176 return MI->getOperand(0).getReg();
180 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
181 /// It is assumed that SnipLI is a virtual register with the same original as
183 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
184 unsigned Reg = Edit->getReg();
186 // A snippet is a tiny live range with only a single instruction using it
187 // besides copies to/from Reg or spills/fills. We accept:
189 // %snip = COPY %Reg / FILL fi#
191 // %Reg = COPY %snip / SPILL %snip, fi#
193 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
196 MachineInstr *UseMI = 0;
198 // Check that all uses satisfy our criteria.
199 for (MachineRegisterInfo::reg_nodbg_iterator
200 RI = MRI.reg_nodbg_begin(SnipLI.reg);
201 MachineInstr *MI = RI.skipInstruction();) {
203 // Allow copies to/from Reg.
204 if (isFullCopyOf(MI, Reg))
207 // Allow stack slot loads.
209 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
212 // Allow stack slot stores.
213 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
216 // Allow a single additional instruction.
217 if (UseMI && MI != UseMI)
224 /// collectRegsToSpill - Collect live range snippets that only have a single
226 void InlineSpiller::collectRegsToSpill() {
227 unsigned Reg = Edit->getReg();
229 // Main register always spills.
230 RegsToSpill.assign(1, Reg);
231 SnippetCopies.clear();
233 // Snippets all have the same original, so there can't be any for an original
238 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
239 MachineInstr *MI = RI.skipInstruction();) {
240 unsigned SnipReg = isFullCopyOf(MI, Reg);
241 if (!isSibling(SnipReg))
243 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
244 if (!isSnippet(SnipLI))
246 SnippetCopies.insert(MI);
247 if (!isRegToSpill(SnipReg))
248 RegsToSpill.push_back(SnipReg);
250 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
255 //===----------------------------------------------------------------------===//
257 //===----------------------------------------------------------------------===//
259 // After live range splitting, some values to be spilled may be defined by
260 // copies from sibling registers. We trace the sibling copies back to the
261 // original value if it still exists. We need it for rematerialization.
263 // Even when the value can't be rematerialized, we still want to determine if
264 // the value has already been spilled, or we may want to hoist the spill from a
267 bool InlineSpiller::isSibling(unsigned Reg) {
268 return TargetRegisterInfo::isVirtualRegister(Reg) &&
269 VRM.getOriginal(Reg) == Original;
272 /// traceSiblingValue - Trace a value that is about to be spilled back to the
273 /// real defining instructions by looking through sibling copies. Always stay
274 /// within the range of OrigVNI so the registers are known to carry the same
277 /// Determine if the value is defined by all reloads, so spilling isn't
278 /// necessary - the value is already in the stack slot.
280 /// Find a defining instruction that may be a candidate for rematerialization.
282 void InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
284 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
285 << UseVNI->id << '@' << UseVNI->def << '\n');
286 SmallPtrSet<VNInfo*, 8> Visited;
287 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
288 WorkList.push_back(std::make_pair(UseReg, UseVNI));
290 // Best spill candidate seen so far. This must dominate UseVNI.
291 SibValueInfo SVI(UseReg, UseVNI);
292 MachineBasicBlock *UseMBB = LIS.getMBBFromIndex(UseVNI->def);
293 unsigned SpillDepth = Loops.getLoopDepth(UseMBB);
294 bool SeenOrigPHI = false; // Original PHI met.
299 tie(Reg, VNI) = WorkList.pop_back_val();
300 if (!Visited.insert(VNI))
303 // Is this value a better spill candidate?
304 if (!isRegToSpill(Reg)) {
305 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
306 if (MBB != UseMBB && MDT.dominates(MBB, UseMBB)) {
307 // This is a valid spill location dominating UseVNI.
308 // Prefer to spill at a smaller loop depth.
309 unsigned Depth = Loops.getLoopDepth(MBB);
310 if (Depth < SpillDepth) {
311 DEBUG(dbgs() << " spill depth " << Depth << ": " << PrintReg(Reg)
312 << ':' << VNI->id << '@' << VNI->def << '\n');
320 // Trace through PHI-defs created by live range splitting.
321 if (VNI->isPHIDef()) {
322 if (VNI->def == OrigVNI->def) {
323 DEBUG(dbgs() << " orig phi value " << PrintReg(Reg) << ':'
324 << VNI->id << '@' << VNI->def << '\n');
328 // Get values live-out of predecessors.
329 LiveInterval &LI = LIS.getInterval(Reg);
330 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
331 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
332 PE = MBB->pred_end(); PI != PE; ++PI) {
333 VNInfo *PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
335 WorkList.push_back(std::make_pair(Reg, PVNI));
340 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
341 assert(MI && "Missing def");
343 // Trace through sibling copies.
344 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
345 if (isSibling(SrcReg)) {
346 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
347 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
348 assert(SrcVNI && "Copy from non-existing value");
349 DEBUG(dbgs() << " copy of " << PrintReg(SrcReg) << ':'
350 << SrcVNI->id << '@' << SrcVNI->def << '\n');
351 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
356 // Track reachable reloads.
358 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
359 DEBUG(dbgs() << " reload " << PrintReg(Reg) << ':'
360 << VNI->id << "@" << VNI->def << '\n');
361 SVI.AllDefsAreReloads = true;
365 // We have an 'original' def. Don't record trivial cases.
367 DEBUG(dbgs() << "Not a sibling copy.\n");
371 // Potential remat candidate.
372 DEBUG(dbgs() << " def " << PrintReg(Reg) << ':'
373 << VNI->id << '@' << VNI->def << '\t' << *MI);
375 } while (!WorkList.empty());
377 if (SeenOrigPHI || SVI.DefMI)
378 SVI.AllDefsAreReloads = false;
381 if (SVI.AllDefsAreReloads)
382 dbgs() << "All defs are reloads.\n";
384 dbgs() << "Prefer to spill " << PrintReg(SVI.SpillReg) << ':'
385 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def << '\n';
387 SibValues.insert(std::make_pair(UseVNI, SVI));
390 /// analyzeSiblingValues - Trace values defined by sibling copies back to
391 /// something that isn't a sibling copy.
392 void InlineSpiller::analyzeSiblingValues() {
395 // No siblings at all?
396 if (Edit->getReg() == Original)
399 LiveInterval &OrigLI = LIS.getInterval(Original);
400 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
401 unsigned Reg = RegsToSpill[i];
402 LiveInterval &LI = LIS.getInterval(Reg);
403 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
404 VE = LI.vni_end(); VI != VE; ++VI) {
406 if (VNI->isUnused() || !(VNI->isPHIDef() || VNI->getCopy()))
408 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
409 if (OrigVNI->def != VNI->def)
410 traceSiblingValue(Reg, VNI, OrigVNI);
415 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
416 /// a spill at a better location.
417 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
418 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
419 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
420 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
421 SibValueMap::const_iterator I = SibValues.find(VNI);
422 if (I == SibValues.end())
425 const SibValueInfo &SVI = I->second;
427 // Let the normal folding code deal with the boring case.
428 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
431 // Conservatively extend the stack slot range to the range of the original
432 // value. We may be able to do better with stack slot coloring by being more
434 LiveInterval &StackInt = LSS.getInterval(StackSlot);
435 LiveInterval &OrigLI = LIS.getInterval(Original);
436 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
437 StackInt.MergeValueInAsValue(OrigLI, OrigVNI, StackInt.getValNumInfo(0));
438 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
439 << StackInt << '\n');
441 // Already spilled everywhere.
442 if (SVI.AllDefsAreReloads)
445 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
446 // any later spills of the same value.
447 eliminateRedundantSpills(LIS.getInterval(SVI.SpillReg), SVI.SpillVNI);
449 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
450 MachineBasicBlock::iterator MII;
451 if (SVI.SpillVNI->isPHIDef())
452 MII = MBB->SkipPHIsAndLabels(MBB->begin());
454 MII = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
457 // Insert spill without kill flag immediately after def.
458 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot, RC, &TRI);
459 --MII; // Point to store instruction.
460 LIS.InsertMachineInstrInMaps(MII);
461 VRM.addSpillSlotUse(StackSlot, MII);
462 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
466 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
467 /// redundant spills of this value in SLI.reg and sibling copies.
468 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
469 assert(VNI && "Missing value");
470 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
471 WorkList.push_back(std::make_pair(&SLI, VNI));
472 LiveInterval &StackInt = LSS.getInterval(StackSlot);
476 tie(LI, VNI) = WorkList.pop_back_val();
477 unsigned Reg = LI->reg;
478 DEBUG(dbgs() << "Checking redundant spills for " << PrintReg(Reg) << ':'
479 << VNI->id << '@' << VNI->def << '\n');
481 // Regs to spill are taken care of.
482 if (isRegToSpill(Reg))
485 // Add all of VNI's live range to StackInt.
486 StackInt.MergeValueInAsValue(*LI, VNI, StackInt.getValNumInfo(0));
487 DEBUG(dbgs() << "Merged to stack int: " << StackInt << '\n');
489 // Find all spills and copies of VNI.
490 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
491 MachineInstr *MI = UI.skipInstruction();) {
492 if (!MI->isCopy() && !MI->getDesc().mayStore())
494 SlotIndex Idx = LIS.getInstructionIndex(MI);
495 if (LI->getVNInfoAt(Idx) != VNI)
498 // Follow sibling copies down the dominator tree.
499 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
500 if (isSibling(DstReg)) {
501 LiveInterval &DstLI = LIS.getInterval(DstReg);
502 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
503 assert(DstVNI && "Missing defined value");
504 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
505 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
512 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
513 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
514 // eliminateDeadDefs won't normally remove stores, so switch opcode.
515 MI->setDesc(TII.get(TargetOpcode::KILL));
516 DeadDefs.push_back(MI);
519 } while (!WorkList.empty());
522 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
523 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
524 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
525 VNInfo *OrigVNI = Edit->getParent().getVNInfoAt(UseIdx);
528 DEBUG(dbgs() << "\tadding <undef> flags: ");
529 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
530 MachineOperand &MO = MI->getOperand(i);
531 if (MO.isReg() && MO.isUse() && MO.getReg() == Edit->getReg())
534 DEBUG(dbgs() << UseIdx << '\t' << *MI);
538 // FIXME: Properly remat for snippets as well.
539 if (SnippetCopies.count(MI)) {
540 UsedValues.insert(OrigVNI);
544 LiveRangeEdit::Remat RM(OrigVNI);
545 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
546 UsedValues.insert(OrigVNI);
547 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
551 // If the instruction also writes Edit->getReg(), it had better not require
552 // the same register for uses and defs.
554 SmallVector<unsigned, 8> Ops;
555 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Edit->getReg(), &Ops);
557 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
558 MachineOperand &MO = MI->getOperand(Ops[i]);
559 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
560 UsedValues.insert(OrigVNI);
561 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
567 // Before rematerializing into a register for a single instruction, try to
568 // fold a load into the instruction. That avoids allocating a new register.
569 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
570 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
571 Edit->markRematerialized(RM.ParentVNI);
575 // Alocate a new register for the remat.
576 LiveInterval &NewLI = Edit->create(LIS, VRM);
577 NewLI.markNotSpillable();
579 // Rematting for a copy: Set allocation hint to be the destination register.
581 MRI.setRegAllocationHint(NewLI.reg, 0, MI->getOperand(0).getReg());
583 // Finally we can rematerialize OrigMI before MI.
584 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
586 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
587 << *LIS.getInstructionFromIndex(DefIdx));
590 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
591 MachineOperand &MO = MI->getOperand(Ops[i]);
592 if (MO.isReg() && MO.isUse() && MO.getReg() == Edit->getReg()) {
593 MO.setReg(NewLI.reg);
597 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
599 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
600 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
601 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
605 /// reMaterializeAll - Try to rematerialize as many uses as possible,
606 /// and trim the live ranges after.
607 void InlineSpiller::reMaterializeAll() {
608 // Do a quick scan of the interval values to find if any are remattable.
609 if (!Edit->anyRematerializable(LIS, TII, AA))
614 // Try to remat before all uses of Edit->getReg().
615 bool anyRemat = false;
616 for (MachineRegisterInfo::use_nodbg_iterator
617 RI = MRI.use_nodbg_begin(Edit->getReg());
618 MachineInstr *MI = RI.skipInstruction();)
619 anyRemat |= reMaterializeFor(MI);
624 // Remove any values that were completely rematted.
625 bool anyRemoved = false;
626 for (LiveInterval::vni_iterator I = Edit->getParent().vni_begin(),
627 E = Edit->getParent().vni_end(); I != E; ++I) {
629 if (VNI->hasPHIKill() || !Edit->didRematerialize(VNI) ||
630 UsedValues.count(VNI))
632 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
633 DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
634 LIS.RemoveMachineInstrFromMaps(DefMI);
635 VRM.RemoveMachineInstrFromMaps(DefMI);
636 DefMI->eraseFromParent();
637 VNI->def = SlotIndex();
644 // Removing values may cause debug uses where parent is not live.
645 for (MachineRegisterInfo::use_iterator RI = MRI.use_begin(Edit->getReg());
646 MachineInstr *MI = RI.skipInstruction();) {
647 if (!MI->isDebugValue())
649 // Try to preserve the debug value if parent is live immediately after it.
650 MachineBasicBlock::iterator NextMI = MI;
652 if (NextMI != MI->getParent()->end() && !LIS.isNotInMIMap(NextMI)) {
653 SlotIndex Idx = LIS.getInstructionIndex(NextMI);
654 VNInfo *VNI = Edit->getParent().getVNInfoAt(Idx);
655 if (VNI && (VNI->hasPHIKill() || UsedValues.count(VNI)))
658 DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
659 MI->eraseFromParent();
663 /// If MI is a load or store of StackSlot, it can be removed.
664 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
667 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
668 !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
671 // We have a stack access. Is it the right register and slot?
672 if (InstrReg != Reg || FI != StackSlot)
675 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
676 LIS.RemoveMachineInstrFromMaps(MI);
677 MI->eraseFromParent();
681 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
682 /// @param MI Instruction using or defining the current register.
683 /// @param Ops Operand indices from readsWritesVirtualRegister().
684 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
685 /// @return True on success, and MI will be erased.
686 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
687 const SmallVectorImpl<unsigned> &Ops,
688 MachineInstr *LoadMI) {
689 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
691 SmallVector<unsigned, 8> FoldOps;
692 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
693 unsigned Idx = Ops[i];
694 MachineOperand &MO = MI->getOperand(Idx);
697 // FIXME: Teach targets to deal with subregs.
700 // We cannot fold a load instruction into a def.
701 if (LoadMI && MO.isDef())
703 // Tied use operands should not be passed to foldMemoryOperand.
704 if (!MI->isRegTiedToDefOperand(Idx))
705 FoldOps.push_back(Idx);
708 MachineInstr *FoldMI =
709 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
710 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
713 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
715 VRM.addSpillSlotUse(StackSlot, FoldMI);
716 MI->eraseFromParent();
717 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
721 /// insertReload - Insert a reload of NewLI.reg before MI.
722 void InlineSpiller::insertReload(LiveInterval &NewLI,
723 MachineBasicBlock::iterator MI) {
724 MachineBasicBlock &MBB = *MI->getParent();
725 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
726 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot, RC, &TRI);
727 --MI; // Point to load instruction.
728 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
729 VRM.addSpillSlotUse(StackSlot, MI);
730 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
731 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
732 LIS.getVNInfoAllocator());
733 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
736 /// insertSpill - Insert a spill of NewLI.reg after MI.
737 void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
738 MachineBasicBlock::iterator MI) {
739 MachineBasicBlock &MBB = *MI->getParent();
741 // Get the defined value. It could be an early clobber so keep the def index.
742 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
743 VNInfo *VNI = OldLI.getVNInfoAt(Idx);
744 assert(VNI && VNI->def.getDefIndex() == Idx && "Inconsistent VNInfo");
747 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot, RC, &TRI);
748 --MI; // Point to store instruction.
749 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
750 VRM.addSpillSlotUse(StackSlot, MI);
751 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
752 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
753 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
756 /// spillAroundUses - insert spill code around each use of Reg.
757 void InlineSpiller::spillAroundUses(unsigned Reg) {
758 LiveInterval &OldLI = LIS.getInterval(Reg);
760 // Iterate over instructions using Reg.
761 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
762 MachineInstr *MI = RI.skipInstruction();) {
764 // Debug values are not allowed to affect codegen.
765 if (MI->isDebugValue()) {
766 // Modify DBG_VALUE now that the value is in a spill slot.
767 uint64_t Offset = MI->getOperand(1).getImm();
768 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
769 DebugLoc DL = MI->getDebugLoc();
770 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
771 Offset, MDPtr, DL)) {
772 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
773 MachineBasicBlock *MBB = MI->getParent();
774 MBB->insert(MBB->erase(MI), NewDV);
776 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
777 MI->eraseFromParent();
782 // Ignore copies to/from snippets. We'll delete them.
783 if (SnippetCopies.count(MI))
786 // Stack slot accesses may coalesce away.
787 if (coalesceStackAccess(MI, Reg))
790 // Analyze instruction.
792 SmallVector<unsigned, 8> Ops;
793 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
795 // Check for a sibling copy.
796 unsigned SibReg = isFullCopyOf(MI, Reg);
797 if (SibReg && isSibling(SibReg)) {
799 // Hoist the spill of a sib-reg copy.
800 if (hoistSpill(OldLI, MI)) {
801 // This COPY is now dead, the value is already in the stack slot.
802 MI->getOperand(0).setIsDead();
803 DeadDefs.push_back(MI);
807 // This is a reload for a sib-reg copy. Drop spills downstream.
808 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
809 LiveInterval &SibLI = LIS.getInterval(SibReg);
810 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
811 // The COPY will fold to a reload below.
815 // Attempt to fold memory ops.
816 if (foldMemoryOperand(MI, Ops))
819 // Allocate interval around instruction.
820 // FIXME: Infer regclass from instruction alone.
821 LiveInterval &NewLI = Edit->create(LIS, VRM);
822 NewLI.markNotSpillable();
825 insertReload(NewLI, MI);
827 // Rewrite instruction operands.
828 bool hasLiveDef = false;
829 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
830 MachineOperand &MO = MI->getOperand(Ops[i]);
831 MO.setReg(NewLI.reg);
833 if (!MI->isRegTiedToDefOperand(Ops[i]))
841 // FIXME: Use a second vreg if instruction has no tied ops.
842 if (Writes && hasLiveDef)
843 insertSpill(NewLI, OldLI, MI);
845 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
849 void InlineSpiller::spill(LiveRangeEdit &edit) {
851 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
852 && "Trying to spill a stack slot.");
853 // Share a stack slot among all descendants of Original.
854 Original = VRM.getOriginal(edit.getReg());
855 StackSlot = VRM.getStackSlot(Original);
857 DEBUG(dbgs() << "Inline spilling "
858 << MRI.getRegClass(edit.getReg())->getName()
859 << ':' << edit.getParent() << "\nFrom original "
860 << LIS.getInterval(Original) << '\n');
861 assert(edit.getParent().isSpillable() &&
862 "Attempting to spill already spilled value.");
863 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
865 collectRegsToSpill();
866 analyzeSiblingValues();
869 // Remat may handle everything.
870 if (Edit->getParent().empty())
873 RC = MRI.getRegClass(edit.getReg());
875 if (StackSlot == VirtRegMap::NO_STACK_SLOT)
876 StackSlot = VRM.assignVirt2StackSlot(Original);
878 if (Original != edit.getReg())
879 VRM.assignVirt2StackSlot(edit.getReg(), StackSlot);
881 // Update LiveStacks now that we are committed to spilling.
882 LiveInterval &stacklvr = LSS.getOrCreateInterval(StackSlot, RC);
883 if (!stacklvr.hasAtLeastOneValue())
884 stacklvr.getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
885 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
886 stacklvr.MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
887 stacklvr.getValNumInfo(0));
888 DEBUG(dbgs() << "Merged spilled regs: " << stacklvr << '\n');
890 // Spill around uses of all RegsToSpill.
891 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
892 spillAroundUses(RegsToSpill[i]);
894 // Hoisted spills may cause dead code.
895 if (!DeadDefs.empty()) {
896 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
897 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
900 // Finally delete the SnippetCopies.
901 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(edit.getReg());
902 MachineInstr *MI = RI.skipInstruction();) {
903 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
904 // FIXME: Do this with a LiveRangeEdit callback.
905 VRM.RemoveMachineInstrFromMaps(MI);
906 LIS.RemoveMachineInstrFromMaps(MI);
907 MI->eraseFromParent();
910 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
911 edit.eraseVirtReg(RegsToSpill[i], LIS);