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 LiveInterval *StackInt;
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 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
124 void analyzeSiblingValues();
126 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
127 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
129 void markValueUsed(LiveInterval*, VNInfo*);
130 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
131 void reMaterializeAll();
133 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
134 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
135 const SmallVectorImpl<unsigned> &Ops,
136 MachineInstr *LoadMI = 0);
137 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
138 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
139 MachineBasicBlock::iterator MI);
141 void spillAroundUses(unsigned Reg);
147 Spiller *createInlineSpiller(MachineFunctionPass &pass,
150 return new InlineSpiller(pass, mf, vrm);
154 //===----------------------------------------------------------------------===//
156 //===----------------------------------------------------------------------===//
158 // When spilling a virtual register, we also spill any snippets it is connected
159 // to. The snippets are small live ranges that only have a single real use,
160 // leftovers from live range splitting. Spilling them enables memory operand
161 // folding or tightens the live range around the single use.
163 // This minimizes register pressure and maximizes the store-to-load distance for
164 // spill slots which can be important in tight loops.
166 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
167 /// otherwise return 0.
168 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
171 if (MI->getOperand(0).getSubReg() != 0)
173 if (MI->getOperand(1).getSubReg() != 0)
175 if (MI->getOperand(0).getReg() == Reg)
176 return MI->getOperand(1).getReg();
177 if (MI->getOperand(1).getReg() == Reg)
178 return MI->getOperand(0).getReg();
182 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
183 /// It is assumed that SnipLI is a virtual register with the same original as
185 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
186 unsigned Reg = Edit->getReg();
188 // A snippet is a tiny live range with only a single instruction using it
189 // besides copies to/from Reg or spills/fills. We accept:
191 // %snip = COPY %Reg / FILL fi#
193 // %Reg = COPY %snip / SPILL %snip, fi#
195 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
198 MachineInstr *UseMI = 0;
200 // Check that all uses satisfy our criteria.
201 for (MachineRegisterInfo::reg_nodbg_iterator
202 RI = MRI.reg_nodbg_begin(SnipLI.reg);
203 MachineInstr *MI = RI.skipInstruction();) {
205 // Allow copies to/from Reg.
206 if (isFullCopyOf(MI, Reg))
209 // Allow stack slot loads.
211 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
214 // Allow stack slot stores.
215 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
218 // Allow a single additional instruction.
219 if (UseMI && MI != UseMI)
226 /// collectRegsToSpill - Collect live range snippets that only have a single
228 void InlineSpiller::collectRegsToSpill() {
229 unsigned Reg = Edit->getReg();
231 // Main register always spills.
232 RegsToSpill.assign(1, Reg);
233 SnippetCopies.clear();
235 // Snippets all have the same original, so there can't be any for an original
240 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
241 MachineInstr *MI = RI.skipInstruction();) {
242 unsigned SnipReg = isFullCopyOf(MI, Reg);
243 if (!isSibling(SnipReg))
245 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
246 if (!isSnippet(SnipLI))
248 SnippetCopies.insert(MI);
249 if (!isRegToSpill(SnipReg))
250 RegsToSpill.push_back(SnipReg);
252 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
257 //===----------------------------------------------------------------------===//
259 //===----------------------------------------------------------------------===//
261 // After live range splitting, some values to be spilled may be defined by
262 // copies from sibling registers. We trace the sibling copies back to the
263 // original value if it still exists. We need it for rematerialization.
265 // Even when the value can't be rematerialized, we still want to determine if
266 // the value has already been spilled, or we may want to hoist the spill from a
269 bool InlineSpiller::isSibling(unsigned Reg) {
270 return TargetRegisterInfo::isVirtualRegister(Reg) &&
271 VRM.getOriginal(Reg) == Original;
274 /// traceSiblingValue - Trace a value that is about to be spilled back to the
275 /// real defining instructions by looking through sibling copies. Always stay
276 /// within the range of OrigVNI so the registers are known to carry the same
279 /// Determine if the value is defined by all reloads, so spilling isn't
280 /// necessary - the value is already in the stack slot.
282 /// Return a defining instruction that may be a candidate for rematerialization.
284 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
286 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
287 << UseVNI->id << '@' << UseVNI->def << '\n');
288 SmallPtrSet<VNInfo*, 8> Visited;
289 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
290 WorkList.push_back(std::make_pair(UseReg, UseVNI));
292 // Best spill candidate seen so far. This must dominate UseVNI.
293 SibValueInfo SVI(UseReg, UseVNI);
294 MachineBasicBlock *UseMBB = LIS.getMBBFromIndex(UseVNI->def);
295 unsigned SpillDepth = Loops.getLoopDepth(UseMBB);
296 bool SeenOrigPHI = false; // Original PHI met.
301 tie(Reg, VNI) = WorkList.pop_back_val();
302 if (!Visited.insert(VNI))
305 // Is this value a better spill candidate?
306 if (!isRegToSpill(Reg)) {
307 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
308 if (MBB != UseMBB && MDT.dominates(MBB, UseMBB)) {
309 // This is a valid spill location dominating UseVNI.
310 // Prefer to spill at a smaller loop depth.
311 unsigned Depth = Loops.getLoopDepth(MBB);
312 if (Depth < SpillDepth) {
313 DEBUG(dbgs() << " spill depth " << Depth << ": " << PrintReg(Reg)
314 << ':' << VNI->id << '@' << VNI->def << '\n');
322 // Trace through PHI-defs created by live range splitting.
323 if (VNI->isPHIDef()) {
324 if (VNI->def == OrigVNI->def) {
325 DEBUG(dbgs() << " orig phi value " << PrintReg(Reg) << ':'
326 << VNI->id << '@' << VNI->def << '\n');
330 // Get values live-out of predecessors.
331 LiveInterval &LI = LIS.getInterval(Reg);
332 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
333 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
334 PE = MBB->pred_end(); PI != PE; ++PI) {
335 VNInfo *PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
337 WorkList.push_back(std::make_pair(Reg, PVNI));
342 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
343 assert(MI && "Missing def");
345 // Trace through sibling copies.
346 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
347 if (isSibling(SrcReg)) {
348 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
349 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
350 assert(SrcVNI && "Copy from non-existing value");
351 DEBUG(dbgs() << " copy of " << PrintReg(SrcReg) << ':'
352 << SrcVNI->id << '@' << SrcVNI->def << '\n');
353 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
358 // Track reachable reloads.
360 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
361 DEBUG(dbgs() << " reload " << PrintReg(Reg) << ':'
362 << VNI->id << "@" << VNI->def << '\n');
363 SVI.AllDefsAreReloads = true;
367 // We have an 'original' def. Don't record trivial cases.
369 DEBUG(dbgs() << "Not a sibling copy.\n");
373 // Potential remat candidate.
374 DEBUG(dbgs() << " def " << PrintReg(Reg) << ':'
375 << VNI->id << '@' << VNI->def << '\t' << *MI);
377 } while (!WorkList.empty());
379 if (SeenOrigPHI || SVI.DefMI)
380 SVI.AllDefsAreReloads = false;
383 if (SVI.AllDefsAreReloads)
384 dbgs() << "All defs are reloads.\n";
386 dbgs() << "Prefer to spill " << PrintReg(SVI.SpillReg) << ':'
387 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def << '\n';
389 SibValues.insert(std::make_pair(UseVNI, SVI));
393 /// analyzeSiblingValues - Trace values defined by sibling copies back to
394 /// something that isn't a sibling copy.
396 /// Keep track of values that may be rematerializable.
397 void InlineSpiller::analyzeSiblingValues() {
400 // No siblings at all?
401 if (Edit->getReg() == Original)
404 LiveInterval &OrigLI = LIS.getInterval(Original);
405 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
406 unsigned Reg = RegsToSpill[i];
407 LiveInterval &LI = LIS.getInterval(Reg);
408 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
409 VE = LI.vni_end(); VI != VE; ++VI) {
413 MachineInstr *DefMI = 0;
414 // Check possible sibling copies.
415 if (VNI->isPHIDef() || VNI->getCopy()) {
416 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
417 if (OrigVNI->def != VNI->def)
418 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
420 if (!DefMI && !VNI->isPHIDef())
421 DefMI = LIS.getInstructionFromIndex(VNI->def);
423 Edit->checkRematerializable(VNI, DefMI, TII, AA);
428 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
429 /// a spill at a better location.
430 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
431 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
432 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
433 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
434 SibValueMap::const_iterator I = SibValues.find(VNI);
435 if (I == SibValues.end())
438 const SibValueInfo &SVI = I->second;
440 // Let the normal folding code deal with the boring case.
441 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
444 // Conservatively extend the stack slot range to the range of the original
445 // value. We may be able to do better with stack slot coloring by being more
447 assert(StackInt && "No stack slot assigned yet.");
448 LiveInterval &OrigLI = LIS.getInterval(Original);
449 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
450 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
451 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
452 << *StackInt << '\n');
454 // Already spilled everywhere.
455 if (SVI.AllDefsAreReloads)
458 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
459 // any later spills of the same value.
460 eliminateRedundantSpills(LIS.getInterval(SVI.SpillReg), SVI.SpillVNI);
462 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
463 MachineBasicBlock::iterator MII;
464 if (SVI.SpillVNI->isPHIDef())
465 MII = MBB->SkipPHIsAndLabels(MBB->begin());
467 MII = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
470 // Insert spill without kill flag immediately after def.
471 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
472 MRI.getRegClass(SVI.SpillReg), &TRI);
473 --MII; // Point to store instruction.
474 LIS.InsertMachineInstrInMaps(MII);
475 VRM.addSpillSlotUse(StackSlot, MII);
476 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
480 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
481 /// redundant spills of this value in SLI.reg and sibling copies.
482 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
483 assert(VNI && "Missing value");
484 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
485 WorkList.push_back(std::make_pair(&SLI, VNI));
486 assert(StackInt && "No stack slot assigned yet.");
490 tie(LI, VNI) = WorkList.pop_back_val();
491 unsigned Reg = LI->reg;
492 DEBUG(dbgs() << "Checking redundant spills for " << PrintReg(Reg) << ':'
493 << VNI->id << '@' << VNI->def << '\n');
495 // Regs to spill are taken care of.
496 if (isRegToSpill(Reg))
499 // Add all of VNI's live range to StackInt.
500 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
501 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
503 // Find all spills and copies of VNI.
504 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
505 MachineInstr *MI = UI.skipInstruction();) {
506 if (!MI->isCopy() && !MI->getDesc().mayStore())
508 SlotIndex Idx = LIS.getInstructionIndex(MI);
509 if (LI->getVNInfoAt(Idx) != VNI)
512 // Follow sibling copies down the dominator tree.
513 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
514 if (isSibling(DstReg)) {
515 LiveInterval &DstLI = LIS.getInterval(DstReg);
516 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
517 assert(DstVNI && "Missing defined value");
518 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
519 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
526 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
527 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
528 // eliminateDeadDefs won't normally remove stores, so switch opcode.
529 MI->setDesc(TII.get(TargetOpcode::KILL));
530 DeadDefs.push_back(MI);
533 } while (!WorkList.empty());
537 //===----------------------------------------------------------------------===//
539 //===----------------------------------------------------------------------===//
541 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
542 /// instruction cannot be eliminated. See through snippet copies
543 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
544 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
545 WorkList.push_back(std::make_pair(LI, VNI));
547 tie(LI, VNI) = WorkList.pop_back_val();
548 if (!UsedValues.insert(VNI))
551 if (VNI->isPHIDef()) {
552 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
553 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
554 PE = MBB->pred_end(); PI != PE; ++PI) {
555 VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
557 WorkList.push_back(std::make_pair(LI, PVNI));
562 // Follow snippet copies.
563 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
564 if (!SnippetCopies.count(MI))
566 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
567 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
568 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex());
569 assert(SnipVNI && "Snippet undefined before copy");
570 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
571 } while (!WorkList.empty());
574 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
575 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
576 MachineBasicBlock::iterator MI) {
577 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
578 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx);
581 DEBUG(dbgs() << "\tadding <undef> flags: ");
582 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
583 MachineOperand &MO = MI->getOperand(i);
584 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
587 DEBUG(dbgs() << UseIdx << '\t' << *MI);
591 if (SnippetCopies.count(MI))
594 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
595 LiveRangeEdit::Remat RM(ParentVNI);
596 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
597 if (SibI != SibValues.end())
598 RM.OrigMI = SibI->second.DefMI;
599 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
600 markValueUsed(&VirtReg, ParentVNI);
601 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
605 // If the instruction also writes VirtReg.reg, it had better not require the
606 // same register for uses and defs.
608 SmallVector<unsigned, 8> Ops;
609 tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
611 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
612 MachineOperand &MO = MI->getOperand(Ops[i]);
613 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
614 markValueUsed(&VirtReg, ParentVNI);
615 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
621 // Before rematerializing into a register for a single instruction, try to
622 // fold a load into the instruction. That avoids allocating a new register.
623 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
624 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
625 Edit->markRematerialized(RM.ParentVNI);
629 // Alocate a new register for the remat.
630 LiveInterval &NewLI = Edit->createFrom(Original, LIS, VRM);
631 NewLI.markNotSpillable();
633 // Finally we can rematerialize OrigMI before MI.
634 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
636 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
637 << *LIS.getInstructionFromIndex(DefIdx));
640 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
641 MachineOperand &MO = MI->getOperand(Ops[i]);
642 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
643 MO.setReg(NewLI.reg);
647 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
649 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
650 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
651 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
655 /// reMaterializeAll - Try to rematerialize as many uses as possible,
656 /// and trim the live ranges after.
657 void InlineSpiller::reMaterializeAll() {
658 // analyzeSiblingValues has already tested all relevant defining instructions.
659 if (!Edit->anyRematerializable(LIS, TII, AA))
664 // Try to remat before all uses of snippets.
665 bool anyRemat = false;
666 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
667 unsigned Reg = RegsToSpill[i];
668 LiveInterval &LI = LIS.getInterval(Reg);
669 for (MachineRegisterInfo::use_nodbg_iterator
670 RI = MRI.use_nodbg_begin(Reg);
671 MachineInstr *MI = RI.skipInstruction();)
672 anyRemat |= reMaterializeFor(LI, MI);
677 // Remove any values that were completely rematted.
678 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
679 unsigned Reg = RegsToSpill[i];
680 LiveInterval &LI = LIS.getInterval(Reg);
681 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
684 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
686 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
687 MI->addRegisterDead(Reg, &TRI);
688 if (!MI->allDefsAreDead())
690 DEBUG(dbgs() << "All defs dead: " << *MI);
691 DeadDefs.push_back(MI);
695 // Eliminate dead code after remat. Note that some snippet copies may be
697 if (DeadDefs.empty())
699 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
700 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
702 // Get rid of deleted and empty intervals.
703 for (unsigned i = RegsToSpill.size(); i != 0; --i) {
704 unsigned Reg = RegsToSpill[i-1];
705 if (!LIS.hasInterval(Reg)) {
706 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
709 LiveInterval &LI = LIS.getInterval(Reg);
712 Edit->eraseVirtReg(Reg, LIS);
713 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
715 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
719 //===----------------------------------------------------------------------===//
721 //===----------------------------------------------------------------------===//
723 /// If MI is a load or store of StackSlot, it can be removed.
724 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
727 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
728 !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
731 // We have a stack access. Is it the right register and slot?
732 if (InstrReg != Reg || FI != StackSlot)
735 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
736 LIS.RemoveMachineInstrFromMaps(MI);
737 MI->eraseFromParent();
741 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
742 /// @param MI Instruction using or defining the current register.
743 /// @param Ops Operand indices from readsWritesVirtualRegister().
744 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
745 /// @return True on success, and MI will be erased.
746 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
747 const SmallVectorImpl<unsigned> &Ops,
748 MachineInstr *LoadMI) {
749 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
751 SmallVector<unsigned, 8> FoldOps;
752 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
753 unsigned Idx = Ops[i];
754 MachineOperand &MO = MI->getOperand(Idx);
757 // FIXME: Teach targets to deal with subregs.
760 // We cannot fold a load instruction into a def.
761 if (LoadMI && MO.isDef())
763 // Tied use operands should not be passed to foldMemoryOperand.
764 if (!MI->isRegTiedToDefOperand(Idx))
765 FoldOps.push_back(Idx);
768 MachineInstr *FoldMI =
769 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
770 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
773 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
775 VRM.addSpillSlotUse(StackSlot, FoldMI);
776 MI->eraseFromParent();
777 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
781 /// insertReload - Insert a reload of NewLI.reg before MI.
782 void InlineSpiller::insertReload(LiveInterval &NewLI,
783 MachineBasicBlock::iterator MI) {
784 MachineBasicBlock &MBB = *MI->getParent();
785 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
786 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
787 MRI.getRegClass(NewLI.reg), &TRI);
788 --MI; // Point to load instruction.
789 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
790 VRM.addSpillSlotUse(StackSlot, MI);
791 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
792 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
793 LIS.getVNInfoAllocator());
794 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
797 /// insertSpill - Insert a spill of NewLI.reg after MI.
798 void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
799 MachineBasicBlock::iterator MI) {
800 MachineBasicBlock &MBB = *MI->getParent();
802 // Get the defined value. It could be an early clobber so keep the def index.
803 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
804 VNInfo *VNI = OldLI.getVNInfoAt(Idx);
805 assert(VNI && VNI->def.getDefIndex() == Idx && "Inconsistent VNInfo");
808 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
809 MRI.getRegClass(NewLI.reg), &TRI);
810 --MI; // Point to store instruction.
811 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
812 VRM.addSpillSlotUse(StackSlot, MI);
813 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
814 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
815 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
818 /// spillAroundUses - insert spill code around each use of Reg.
819 void InlineSpiller::spillAroundUses(unsigned Reg) {
820 LiveInterval &OldLI = LIS.getInterval(Reg);
822 // Iterate over instructions using Reg.
823 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
824 MachineInstr *MI = RI.skipInstruction();) {
826 // Debug values are not allowed to affect codegen.
827 if (MI->isDebugValue()) {
828 // Modify DBG_VALUE now that the value is in a spill slot.
829 uint64_t Offset = MI->getOperand(1).getImm();
830 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
831 DebugLoc DL = MI->getDebugLoc();
832 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
833 Offset, MDPtr, DL)) {
834 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
835 MachineBasicBlock *MBB = MI->getParent();
836 MBB->insert(MBB->erase(MI), NewDV);
838 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
839 MI->eraseFromParent();
844 // Ignore copies to/from snippets. We'll delete them.
845 if (SnippetCopies.count(MI))
848 // Stack slot accesses may coalesce away.
849 if (coalesceStackAccess(MI, Reg))
852 // Analyze instruction.
854 SmallVector<unsigned, 8> Ops;
855 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
857 // Check for a sibling copy.
858 unsigned SibReg = isFullCopyOf(MI, Reg);
859 if (SibReg && isSibling(SibReg)) {
861 // Hoist the spill of a sib-reg copy.
862 if (hoistSpill(OldLI, MI)) {
863 // This COPY is now dead, the value is already in the stack slot.
864 MI->getOperand(0).setIsDead();
865 DeadDefs.push_back(MI);
869 // This is a reload for a sib-reg copy. Drop spills downstream.
870 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
871 LiveInterval &SibLI = LIS.getInterval(SibReg);
872 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
873 // The COPY will fold to a reload below.
877 // Attempt to fold memory ops.
878 if (foldMemoryOperand(MI, Ops))
881 // Allocate interval around instruction.
882 // FIXME: Infer regclass from instruction alone.
883 LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM);
884 NewLI.markNotSpillable();
887 insertReload(NewLI, MI);
889 // Rewrite instruction operands.
890 bool hasLiveDef = false;
891 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
892 MachineOperand &MO = MI->getOperand(Ops[i]);
893 MO.setReg(NewLI.reg);
895 if (!MI->isRegTiedToDefOperand(Ops[i]))
903 // FIXME: Use a second vreg if instruction has no tied ops.
904 if (Writes && hasLiveDef)
905 insertSpill(NewLI, OldLI, MI);
907 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
911 /// spillAll - Spill all registers remaining after rematerialization.
912 void InlineSpiller::spillAll() {
913 // Update LiveStacks now that we are committed to spilling.
914 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
915 StackSlot = VRM.assignVirt2StackSlot(Original);
916 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
917 StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
919 StackInt = &LSS.getInterval(StackSlot);
921 if (Original != Edit->getReg())
922 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
924 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
925 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
926 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
927 StackInt->getValNumInfo(0));
928 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
930 // Spill around uses of all RegsToSpill.
931 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
932 spillAroundUses(RegsToSpill[i]);
934 // Hoisted spills may cause dead code.
935 if (!DeadDefs.empty()) {
936 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
937 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
940 // Finally delete the SnippetCopies.
941 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg());
942 MachineInstr *MI = RI.skipInstruction();) {
943 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
944 // FIXME: Do this with a LiveRangeEdit callback.
945 VRM.RemoveMachineInstrFromMaps(MI);
946 LIS.RemoveMachineInstrFromMaps(MI);
947 MI->eraseFromParent();
950 // Delete all spilled registers.
951 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
952 Edit->eraseVirtReg(RegsToSpill[i], LIS);
955 void InlineSpiller::spill(LiveRangeEdit &edit) {
957 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
958 && "Trying to spill a stack slot.");
959 // Share a stack slot among all descendants of Original.
960 Original = VRM.getOriginal(edit.getReg());
961 StackSlot = VRM.getStackSlot(Original);
964 DEBUG(dbgs() << "Inline spilling "
965 << MRI.getRegClass(edit.getReg())->getName()
966 << ':' << edit.getParent() << "\nFrom original "
967 << LIS.getInterval(Original) << '\n');
968 assert(edit.getParent().isSpillable() &&
969 "Attempting to spill already spilled value.");
970 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
972 collectRegsToSpill();
973 analyzeSiblingValues();
976 // Remat may handle everything.
977 if (!RegsToSpill.empty())
980 Edit->calculateRegClassAndHint(MF, LIS, Loops);